plugins/coingecko.go (view raw)
1package plugins
2
3import (
4 "fmt"
5 "strings"
6
7 coingecko "git.icyphox.sh/paprika/plugins/coingecko"
8 "github.com/dustin/go-humanize"
9 "gopkg.in/irc.v3"
10)
11
12type CoinGecko struct{}
13
14func init() {
15 Register(CoinGecko{})
16}
17
18var (
19 aliases = []string{".btc", ".eth", ".doge", ".bsc"}
20 triggers = append([]string{".cg", ".coin", ".crypto"}, aliases...)
21)
22
23func (CoinGecko) Triggers() []string {
24 return triggers
25}
26
27func formatCgNum(field string, value float64, percent bool) string {
28 if percent {
29 v := humanize.CommafWithDigits(value + 0.00000000001, 2)
30 if value < 0 {
31 return fmt.Sprintf("%s: \x0304%s%%\x03 ", field, v)
32 } else {
33 return fmt.Sprintf("%s: \x0303%s%%\x03 ", field, v)
34 }
35 } else if value >= 0.01 {
36 v := humanize.CommafWithDigits(value + 0.00000000001, 2)
37 return fmt.Sprintf("%s: $%s ", field, v)
38 } else {
39 return fmt.Sprintf("%s: $%.3e ", field, value)
40 }
41}
42
43func (CoinGecko) Execute(m *irc.Message) (string, error) {
44 parsed := strings.SplitN(m.Trailing(), " ", 3)
45 if len(parsed) > 2 {
46 return fmt.Sprintf("Usage: %s <Ticker>", parsed[0]), nil
47 }
48 cmd := parsed[0]
49
50 var coin string
51 for _, alias := range aliases {
52 if cmd == alias {
53 coin = alias[1:]
54 break
55 }
56 }
57
58 var sym string
59 if len(parsed) != 2 && coin == "" {
60 return fmt.Sprintf("Usage: %s <Ticker>", parsed[0]), nil
61 } else if coin != "" {
62 sym = coin
63 } else {
64 sym = parsed[1]
65 }
66
67 err := coingecko.CheckUpdateCoinList()
68 if err != nil {
69 return "", err
70 }
71
72 cid, err := coingecko.GetCoinId(sym)
73 if err != nil {
74 return "", err
75 } else if cid == "" {
76 return fmt.Sprintf("No such coin found: %s", sym), nil
77 }
78
79 stats, err := coingecko.GetCoinPrice(cid)
80 if err != nil {
81 return "", err
82 } else if stats == nil {
83 return fmt.Sprintf("No such coin found: %s", sym), nil
84 }
85
86 mData := stats.MarketData
87
88 var outRes strings.Builder
89 outRes.WriteString(fmt.Sprintf(
90 "\x02%s (%s)\x02 - ",
91 stats.Name, stats.Symbol,
92 ))
93 outRes.WriteString(formatCgNum("Current", mData.Current.Usd, false))
94 outRes.WriteString(formatCgNum("High", mData.High.Usd, false))
95 outRes.WriteString(formatCgNum("Low", mData.Low.Usd, false))
96
97 outRes.WriteString(formatCgNum("MCap", mData.MarketCap.Usd, false))
98 outRes.WriteString(fmt.Sprintf("(#%s) ", humanize.Comma(mData.MarketCapRank)))
99
100 outRes.WriteString(formatCgNum("24h", mData.Change24h, true))
101 outRes.WriteString(formatCgNum("7d", mData.Change7d, true))
102 outRes.WriteString(formatCgNum("30d", mData.Change30d, true))
103 outRes.WriteString(formatCgNum("60d", mData.Change60d, true))
104 outRes.WriteString(formatCgNum("1y", mData.Change1y, true))
105
106 return outRes.String(), nil
107}