forked from ubiq/tars-discord
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
655 lines (543 loc) · 15.8 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/boltdb/bolt"
"github.com/bwmarrin/discordgo"
"github.com/decred/dcrd/dcrutil"
"github.com/joho/godotenv"
"github.com/jpatel888/go-bitstamp"
"github.com/jyap808/go-bittrex"
"github.com/jyap808/go-gemini"
"github.com/jyap808/go-poloniex"
"github.com/ubiq/tars-discord/optionalchannelscmd"
"github.com/ubiq/tars-discord/textcmd"
)
// Variables used for command line parameters
var (
bittrex_api_key = ""
bittrex_api_secret = ""
gemini_api_key = ""
gemini_api_secret = ""
poloniex_api_key = ""
poloniex_api_secret = ""
db *bolt.DB
appHomeDir = dcrutil.AppDataDir("ubq-tars-discord", false)
defaultBoldDBFile = filepath.Join(appHomeDir, "exchange_pairs.db")
defaultConfigFile = filepath.Join(appHomeDir, "secrets.env")
hClient = &http.Client{Timeout: 8 * time.Second}
)
func poloPrice(vals *string) *string {
message := ""
poloniex := poloniex.New(poloniex_api_key, poloniex_api_secret)
rawticker := *vals
upperTicker := strings.ToUpper(rawticker)
tickerName := fmt.Sprintf("BTC_%s", upperTicker)
tickers, err := poloniex.GetTickers()
if err != nil {
message = "Error: API not available"
return &message
}
ticker, ok := tickers[tickerName]
if ok {
message = fmt.Sprintf("Poloniex - BID: %.8f ASK: %.8f LAST: %.8f HIGH: %.8f LOW: %.8f VOLUME: %.2f %s, %.4f BTC CHANGE: %.2f%%",
ticker.HighestBid, ticker.LowestAsk, ticker.Last, ticker.High24Hr, ticker.Low24Hr, ticker.QuoteVolume, upperTicker, ticker.BaseVolume, (ticker.PercentChange * 100))
} else {
message = "Error: Polo Invalid market"
}
return &message
}
func trexPrice(vals *string) *string {
message := ""
bittrex := bittrex.New(bittrex_api_key, bittrex_api_secret)
rawticker := vals
upperTicker := strings.ToUpper(*rawticker)
tickerName := fmt.Sprintf("BTC-%s", upperTicker)
marketSummary, err := bittrex.GetMarketSummary(tickerName)
if err != nil {
message = "Error: Trex invalid market"
} else {
y1 := marketSummary[0].PrevDay
y2 := marketSummary[0].Last
change := ((y2 - y1) / y1) * 100
message = fmt.Sprintf("Bittrex - BID: %.8f ASK: %.8f LAST: %.8f HIGH: %.8f LOW: %.8f VOLUME: %.2f %s, %.4f BTC CHANGE: %.2f%%",
marketSummary[0].Bid, marketSummary[0].Ask, marketSummary[0].Last, marketSummary[0].High, marketSummary[0].Low, marketSummary[0].Volume, upperTicker, marketSummary[0].BaseVolume, change)
}
return &message
}
func getUSDto(fiat string) float64 {
r, err := hClient.Get("https://api.fixer.io/latest?base=USD")
if err != nil {
log.Fatal(err)
return -1.0
}
b, readErr := ioutil.ReadAll(r.Body)
if readErr != nil {
log.Fatal(readErr)
return -1.0
}
defer r.Body.Close()
var f interface{}
json.Unmarshal([]byte(b), &f)
return f.(map[string]interface{})["rates"].(map[string]interface{})[fiat].(float64)
}
func ubqEUR(amount *float64) *string {
message := ""
fiatErrMessage := "Error retrieving fiat conversion from remote API's"
// Bittrex lookup
bittrex := bittrex.New(bittrex_api_key, bittrex_api_secret)
upperTicker := "UBQ"
tickerName := fmt.Sprintf("BTC-%s", upperTicker)
ticker, err := bittrex.GetTicker(tickerName)
// BTC lookup
bitstamp := bitstamp.New()
btcTickerName := "btceur"
btcTicker, err := bitstamp.GetTicker(btcTickerName)
if err != nil {
log.Println(err)
return &fiatErrMessage
}
btcPrice := btcTicker.Last
if btcPrice == 0 {
return &fiatErrMessage
} else {
eurValue := *amount * ticker.Ask * btcPrice
message = fmt.Sprintf("```%.1f UBQ = €%.3f EUR```", *amount, eurValue)
return &message
}
}
func ubqUSD(amount *float64) *string {
message := ""
// Bittrex lookup
bittrex := bittrex.New(bittrex_api_key, bittrex_api_secret)
upperTicker := "UBQ"
tickerName := fmt.Sprintf("BTC-%s", upperTicker)
ticker, err := bittrex.GetTicker(tickerName)
// BTC lookup
gemini := gemini.New(gemini_api_key, gemini_api_secret)
btcTickerName := "btcusd"
btcTicker, err := gemini.GetTicker(btcTickerName)
if err != nil {
log.Println(err)
message = "Error retrieving price from remote API's"
return &message
}
btcPrice := btcTicker.Last
usdValue := *amount * ticker.Ask * btcPrice
message = fmt.Sprintf("```%.1f UBQ = $%.3f USD```", *amount, usdValue)
return &message
}
func ubqLambo() *string {
message := ""
// Bittrex lookup
bittrex := bittrex.New(bittrex_api_key, bittrex_api_secret)
upperTicker := "UBQ"
tickerName := fmt.Sprintf("BTC-%s", upperTicker)
ticker, err := bittrex.GetTicker(tickerName)
// BTC lookup
gemini := gemini.New(gemini_api_key, gemini_api_secret)
btcTickerName := "btcusd"
btcTicker, err := gemini.GetTicker(btcTickerName)
if err != nil {
log.Println(err)
message = "Error retrieving price from remote API's"
return &message
}
btcPrice := btcTicker.Last
amount := 1.0
usdValue := amount * ticker.Ask * btcPrice
lamboValue := 300000 / usdValue
message = fmt.Sprintf("```You would need about %.0f UBQ to buy a lambo.```", lamboValue)
return &message
}
func initializeBittrex(db *bolt.DB) (err error) {
// Initial Bittrex table with data
log.Println("initializeBittrex: START")
bittrex := bittrex.New(bittrex_api_key, bittrex_api_secret)
markets, err := bittrex.GetMarkets()
if err != nil {
return err
}
bucketname := []byte("bittrex")
// store some data
err = db.Update(func(tx *bolt.Tx) error {
// Delete bucket
err := tx.DeleteBucket(bucketname)
if err != nil {
log.Println("No bucket deleted")
}
// Open bucket
bucket, err := tx.CreateBucket(bucketname)
if err != nil {
return err
}
for _, market := range markets {
log.Println("initializeBittrex: ADD", market.MarketName)
key := []byte(market.MarketCurrency)
value := []byte(market.MarketCurrencyLong)
err = bucket.Put(key, value)
if err != nil {
return err
}
}
// Store the last updated time
err = bucket.Put([]byte("lastupdated"), []byte(fmt.Sprint(time.Now().Unix())))
if err != nil {
return err
}
return nil
})
if err != nil {
fmt.Println(err)
}
log.Println("initializeBittrex: END")
return nil
}
func initializePoloniex(db *bolt.DB) (err error) {
// Initialize Poloniex table with data
log.Println("initializePoloniex: START")
poloniex := poloniex.New(poloniex_api_key, poloniex_api_secret)
currencies, err := poloniex.GetCurrencies()
if err != nil {
return err
}
bucketname := []byte("poloniex")
// store some data
err = db.Update(func(tx *bolt.Tx) error {
// Delete bucket
err := tx.DeleteBucket(bucketname)
if err != nil {
log.Println("No bucket deleted")
}
// Open bucket
bucket, err := tx.CreateBucket(bucketname)
if err != nil {
return err
}
for ticker, value := range currencies.Pair {
if value.Delisted == 1 {
continue
}
log.Println("initializePoloniex: ADD", ticker)
key := []byte(ticker)
value := []byte(value.Name)
err = bucket.Put(key, value)
if err != nil {
return err
}
}
// Store the last updated time
err = bucket.Put([]byte("lastupdated"), []byte(fmt.Sprint(time.Now().Unix())))
if err != nil {
return err
}
return nil
})
if err != nil {
log.Println(err)
}
log.Println("initializePoloniex: END")
return nil
}
func generatePriceMessage(prices []string, tickerHeader string) *string {
message := ""
beginString := "```"
endString := "```"
headerString := tickerHeader
if len(prices) == 0 {
message = "Ticker not found"
return &message
}
pricesString := strings.Join(prices, "\n")
message = fmt.Sprintf("%s%s\n%s%s", beginString, headerString, pricesString, endString)
return &message
}
func btcPrice() *string {
message := ""
gemini := gemini.New(gemini_api_key, gemini_api_secret)
tickerName := "btcusd"
ticker, err := gemini.GetTicker(tickerName)
if err != nil {
log.Println(err)
message = "Error retrieving price from remote API's"
return &message
}
lastPrice := ticker.Last
if err != nil {
log.Println(err)
message = "Error retrieving price from remote API's"
} else {
message = fmt.Sprintf("```Gemini BTC price: %.2f```", lastPrice)
}
return &message
}
func KeysString(m map[string]bool) string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
return strings.Join(keys, ", ")
}
func handleMessage(s *discordgo.Session, m *discordgo.MessageCreate) *string {
vals := &m.Content
valSplit := strings.Split(*vals, " ")
message := ""
if len(*vals) == 0 {
return nil
}
command := valSplit[0]
arguments := valSplit[1:]
var optionalChannels = map[string]bool{
"china": true,
"decred-stakepool": true,
"gamers": true,
"korea": true,
"music": true,
"nsfw": true,
"russia": true,
"sports": true,
}
switch command {
case "!price":
if len(arguments) == 0 {
message = "Usage: !price [TICKER]"
break
}
ticker := strings.ToUpper(arguments[0])
// Special case to handle BTC price
if ticker == "BTC" {
message = *btcPrice()
break
}
var prices []string
var tickerHeader string
var bittrexUpdate bool
var poloniexUpdate bool
// Check Bittrex - Last updated
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("bittrex"))
if b == nil {
log.Println(".. you need to initialize the pairs database by running: price refresh")
}
updated := b.Get([]byte("lastupdated"))
if updated != nil {
ts, err := strconv.Atoi(string(updated))
if err != nil {
return err
}
t := time.Unix(int64(ts), 0)
if time.Since(t).Seconds() > 3600 {
bittrexUpdate = true
}
}
return nil
})
// Check Bittrex
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("bittrex"))
if b == nil {
log.Println(".. you need to initialize the pairs database by running: price refresh")
}
v := b.Get([]byte(ticker))
if v != nil {
bittrexUpdate = false
tickerHeader = fmt.Sprintf("%s - %s", ticker, v)
price := trexPrice(&ticker)
prices = append(prices, *price)
}
return nil
})
// Check Poloniex - Last updated
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("poloniex"))
if b == nil {
log.Println(".. you need to initialize the pairs database by running: price refresh")
}
updated := b.Get([]byte("lastupdated"))
if updated != nil {
ts, err := strconv.Atoi(string(updated))
if err != nil {
return err
}
t := time.Unix(int64(ts), 0)
if time.Since(t).Seconds() > 3600 {
poloniexUpdate = true
}
}
return nil
})
// Check Poloniex
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("poloniex"))
if b == nil {
log.Println(".. you need to initialize the pairs database by running: price refresh")
}
v := b.Get([]byte(ticker))
if v != nil {
poloniexUpdate = false
if tickerHeader == "" {
tickerHeader = fmt.Sprintf("%s - %s", ticker, v)
}
price := poloPrice(&ticker)
prices = append(prices, *price)
}
return nil
})
if bittrexUpdate {
initializeBittrex(db)
}
if poloniexUpdate {
initializePoloniex(db)
}
message = *generatePriceMessage(prices, tickerHeader)
case "!pricerefresh":
// Refresh coin pairs in Bolt DB
initializeBittrex(db)
initializePoloniex(db)
message = "Exchange pairs refreshed"
case "!ubqusd":
usageStr := "Usage: !ubqusd [AMOUNT] eg. !ubqusd 10"
valueErrStr := fmt.Sprintf("Value error ;_; - %s", usageStr)
if len(arguments) < 1 {
message = usageStr
break
}
amount, err := strconv.ParseFloat(arguments[0], 64)
if err != nil {
message = valueErrStr
break
}
if amount < 0.1 || amount > 100000000 {
message = "ERR: Pick an amount greater than 0.1 an less than 100 million"
break
}
message = *ubqUSD(&amount)
case "!ubqeur":
usageStr := "Usage: !ubqeur [AMOUNT] eg. !ubqeur 10"
valueErrStr := fmt.Sprintf("Value error ;_; - %s", usageStr)
if len(arguments) < 1 {
message = usageStr
break
}
amount, err := strconv.ParseFloat(arguments[0], 64)
if err != nil {
message = valueErrStr
break
}
if amount < 0.1 || amount > 100000000 {
message = "ERR: Pick an amount greater than 0.1 an less than 100 million"
break
}
message = *ubqEUR(&amount)
case "!ubqlambo":
message = *ubqLambo()
// Text commands
// Keep this in alphabetical order. Where possible just use the singular term.
case "!ann", "!apx", "!backup", "!blank", "!bots", "!caps", "!commands", "!compare", "!escher", "!escrow", "!ethunits", "!exchange", "!explorer", "!github", "!hide", "!hidechannels", "!invite", "!market", "!miner", "!mp", "!monetarypolicy", "!nucleus", "!onepage", "!pools", "!quarterly", "!resettabs", "!roadmap", "!site", "!social", "!solidity", "!stats", "!transparency", "!verified", "!verify", "!wallet", "!website", "!shokku", "!vyper":
message = *textcmd.Commands(command)
case "!join":
usageStr := "**Usage:** !join [OPTIONAL_CHANNEL]\n\n"
usageStr += fmt.Sprintf("**Optional Channels:** %s", KeysString(optionalChannels))
if len(arguments) == 0 {
message = usageStr
break
}
channel := strings.ToLower(arguments[0])
channel = strings.TrimPrefix(channel, "#")
if optionalChannels[channel] {
message = *optionalchannelscmd.Join(s, m, channel)
} else {
message = usageStr
}
case "!leave":
usageStr := "**Usage:** !leave [OPTIONAL_CHANNEL]\n\n"
usageStr += fmt.Sprintf("**Optional Channels:** %s", KeysString(optionalChannels))
if len(arguments) == 0 {
message = usageStr
break
}
channel := strings.ToLower(arguments[0])
channel = strings.TrimPrefix(channel, "#")
if optionalChannels[channel] {
message = *optionalchannelscmd.Leave(s, m, channel)
} else {
message = usageStr
}
case "!echo":
if len(arguments) == 0 {
message = "Usage: !echo [TEXT]"
}
valSplit2 := strings.SplitN(*vals, " ", 2)
message = fmt.Sprintf("*Echo:* %s", valSplit2[1])
default:
}
return &message
}
func main() {
godotenv.Load(defaultConfigFile)
token := os.Getenv("DISCORD_API_TOKEN")
// Create the home directory if it doesn't already exist.
err := os.MkdirAll(appHomeDir, 0700)
if err != nil {
// Show a nicer error message if it's because a symlink is
// linked to a directory that does not exist (probably because
// it's not mounted).
if e, ok := err.(*os.PathError); ok && os.IsExist(err) {
if link, lerr := os.Readlink(e.Path); lerr == nil {
str := "is symlink %s -> %s mounted?"
err = fmt.Errorf(str, e.Path, link)
}
}
log.Fatalln("Failed to create config directory")
}
// Optionally open database read only
db, err = bolt.Open(defaultBoldDBFile, 0600, nil)
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Create a new Discord session using the provided bot token.
dg, err := discordgo.New("Bot " + token)
if err != nil {
fmt.Println("error creating Discord session,", err)
return
}
// Register the messageCreate func as a callback for MessageCreate events.
dg.AddHandler(messageCreate)
// Open a websocket connection to Discord and begin listening.
err = dg.Open()
if err != nil {
fmt.Println("error opening connection,", err)
return
}
// Wait here until CTRL-C or other term signal is received.
fmt.Println("Bot is now running. Press CTRL-C to exit.")
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
<-sc
// Cleanly close down the Discord session.
dg.Close()
}
// This function will be called (due to AddHandler above) every time a new
// message is created on any channel that the authenticated bot has access to.
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
// Ignore all messages created by the bot itself
// This isn't required in this specific example but it's a good practice.
if m.Author.ID == s.State.User.ID {
return
}
if len(m.Content) > 0 {
message := handleMessage(s, m)
s.ChannelMessageSend(m.ChannelID, *message)
}
}