-
-
Notifications
You must be signed in to change notification settings - Fork 113
/
manager.go
614 lines (563 loc) · 15.9 KB
/
manager.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
package main
import (
"context"
"database/sql"
"errors"
"net/http"
"sync"
"time"
"github.com/bwmarrin/discordgo"
"github.com/go-redis/redis/v8"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
_ "modernc.org/sqlite"
)
var (
tickerCount = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "ticker_count",
Help: "Number of tickers.",
},
)
marketcapCount = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "marketcap_count",
Help: "Number of marketcaps.",
},
)
circulatingCount = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "circulating_count",
Help: "Number of circulatings.",
},
)
valuelockedCount = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "valuelocked_count",
Help: "Number of valuelocked.",
},
)
boardCount = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "board_count",
Help: "Number of board.",
},
)
gasCount = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "gas_count",
Help: "Number of gas.",
},
)
tokenCount = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "token_count",
Help: "Number of tokens.",
},
)
holdersCount = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "holders_count",
Help: "Number of holders.",
},
)
floorCount = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "floor_count",
Help: "Number of floor.",
},
)
cacheHits = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "cache_hit",
Help: "Number of times the cache had data",
},
)
cacheMisses = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "cache_miss",
Help: "Number of times the cache lacked data",
},
)
yahooHits = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "yahoo_hits",
Help: "Number of times we got data from yahoo",
},
)
yahooMisses = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "yahoo_misses",
Help: "Number of times we failed to get data from yahoo",
},
)
coingeckoHits = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "coingecko_hits",
Help: "Number of times we got data from coingecko",
},
)
coingeckoMisses = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "coingecko_misses",
Help: "Number of times we failed to get data from coingecko",
},
)
rateLimited = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "ratelimited",
Help: "Number of times we have been rate limited",
},
)
updateError = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "update_error",
Help: "Number of times we have failed to update",
},
)
lastUpdate = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "time_of_last_update",
Help: "Number of seconds since the ticker last updated.",
},
[]string{
"ticker",
"type",
"guild",
},
)
)
// Manager holds a list of the crypto and stocks we are watching
type Manager struct {
WatchingTicker map[string]*Ticker
WatchingMarketCap map[string]*MarketCap
WatchingCirculating map[string]*Circulating
WatchingValueLocked map[string]*ValueLocked
WatchingBoard map[string]*Board
WatchingGas map[string]*Gas
WatchingToken map[string]*Token
WatchingHolders map[string]*Holders
WatchingFloor map[string]*Floor
DB *sql.DB
Cache *redis.Client
Context context.Context
sync.RWMutex
}
// NewManager stores all the information about the current stocks being watched and
func NewManager(address string, dbFile string, count prometheus.Gauge, cache *redis.Client, context context.Context) *Manager {
m := &Manager{
WatchingTicker: make(map[string]*Ticker),
WatchingMarketCap: make(map[string]*MarketCap),
WatchingCirculating: make(map[string]*Circulating),
WatchingValueLocked: make(map[string]*ValueLocked),
WatchingBoard: make(map[string]*Board),
WatchingGas: make(map[string]*Gas),
WatchingToken: make(map[string]*Token),
WatchingHolders: make(map[string]*Holders),
WatchingFloor: make(map[string]*Floor),
DB: dbInit(dbFile),
Cache: cache,
Context: context,
}
// Create a router to accept requests
r := mux.NewRouter()
// Ticker
r.HandleFunc("/ticker", m.AddTicker).Methods("POST")
r.HandleFunc("/ticker/{id}", m.DeleteTicker).Methods("DELETE")
r.HandleFunc("/ticker/{id}", m.RestartTicker).Methods("PATCH")
r.HandleFunc("/ticker", m.GetTickers).Methods("GET")
// MarketCap
r.HandleFunc("/marketcap", m.AddMarketCap).Methods("POST")
r.HandleFunc("/marketcap/{id}", m.DeleteMarketCap).Methods("DELETE")
r.HandleFunc("/marketcap/{id}", m.RestartMarketCap).Methods("PATCH")
r.HandleFunc("/marketcap", m.GetMarketCaps).Methods("GET")
// Circulating
r.HandleFunc("/circulating", m.AddCirculating).Methods("POST")
r.HandleFunc("/circulating/{id}", m.DeleteCirculating).Methods("DELETE")
r.HandleFunc("/circulating/{id}", m.RestartCirculating).Methods("PATCH")
r.HandleFunc("/circulating", m.GetCirculatings).Methods("GET")
// Value Locked
r.HandleFunc("/valuelocked", m.AddValueLocked).Methods("POST")
r.HandleFunc("/valuelocked/{id}", m.DeleteValueLocked).Methods("DELETE")
r.HandleFunc("/valuelocked/{id}", m.RestartValueLocked).Methods("PATCH")
r.HandleFunc("/valuelocked", m.GetValueLockeds).Methods("GET")
// Board
r.HandleFunc("/tickerboard", m.AddBoard).Methods("POST")
r.HandleFunc("/tickerboard/{id}", m.DeleteBoard).Methods("DELETE")
r.HandleFunc("/tickerboard/{id}", m.RestartBoard).Methods("PATCH")
r.HandleFunc("/tickerboard", m.GetBoards).Methods("GET")
// Gas
r.HandleFunc("/gas", m.AddGas).Methods("POST")
r.HandleFunc("/gas/{id}", m.DeleteGas).Methods("DELETE")
r.HandleFunc("/gas/{id}", m.RestartGas).Methods("PATCH")
r.HandleFunc("/gas", m.GetGas).Methods("GET")
// Token
r.HandleFunc("/token", m.AddToken).Methods("POST")
r.HandleFunc("/token/{id}", m.DeleteToken).Methods("DELETE")
r.HandleFunc("/token/{id}", m.RestartToken).Methods("PATCH")
r.HandleFunc("/token", m.GetToken).Methods("GET")
// Holders
r.HandleFunc("/holders", m.AddHolders).Methods("POST")
r.HandleFunc("/holders/{id}", m.DeleteHolders).Methods("DELETE")
r.HandleFunc("/holders/{id}", m.RestartHolders).Methods("PATCH")
r.HandleFunc("/holders", m.GetHolders).Methods("GET")
// Floor
r.HandleFunc("/floor", m.AddFloor).Methods("POST")
r.HandleFunc("/floor/{id}", m.DeleteFloor).Methods("DELETE")
r.HandleFunc("/floor/{id}", m.RestartFloor).Methods("PATCH")
r.HandleFunc("/floor", m.GetFloor).Methods("GET")
// Metrics
prometheus.MustRegister(tickerCount)
prometheus.MustRegister(marketcapCount)
prometheus.MustRegister(circulatingCount)
prometheus.MustRegister(valuelockedCount)
prometheus.MustRegister(boardCount)
prometheus.MustRegister(gasCount)
prometheus.MustRegister(tokenCount)
prometheus.MustRegister(holdersCount)
prometheus.MustRegister(floorCount)
prometheus.MustRegister(lastUpdate)
prometheus.MustRegister(cacheHits)
prometheus.MustRegister(cacheMisses)
prometheus.MustRegister(yahooHits)
prometheus.MustRegister(yahooMisses)
prometheus.MustRegister(coingeckoHits)
prometheus.MustRegister(coingeckoMisses)
prometheus.MustRegister(rateLimited)
prometheus.MustRegister(updateError)
r.Handle("/metrics", promhttp.Handler())
// Pull in existing bots
var noDB *sql.DB
if m.DB != noDB {
m.ImportToken()
m.ImportMarketCap()
m.ImportCirculating()
m.ImportValueLocked()
m.ImportTicker()
m.ImportHolder()
m.ImportGas()
m.ImportBoard()
m.ImportFloor()
}
srv := &http.Server{
Addr: address,
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: r,
}
logger.Infof("Starting api server on %s...", address)
// Run our server in a goroutine so that it doesn't block.
go func() {
if err := srv.ListenAndServe(); err != nil {
logger.Fatal(err)
}
}()
return m
}
func dbInit(fileName string) *sql.DB {
var db *sql.DB
if fileName == "" {
logger.Warning("Will not be storing state.")
return db
}
db, err := sql.Open("sqlite", fileName)
if err != nil {
logger.Errorf("Unable to open db file: %s\n", err)
logger.Warning("Will not be storing state.")
return db
}
bootstrap := `CREATE TABLE IF NOT EXISTS tickers (
id integer primary key autoincrement,
clientId string,
token string,
frequency integer,
ticker string,
name string,
nickname bool,
color bool,
crypto bool,
activity string,
decorator string,
decimals integer,
currency string,
currencySymbol string,
pair string,
pairFlip bool,
multiplier integer,
twelveDataKey string
);
CREATE TABLE IF NOT EXISTS marketcaps (
id integer primary key autoincrement,
clientId string,
token string,
frequency integer,
ticker string,
name string,
nickname bool,
color bool,
activity string,
decorator string,
decimals integer,
currency string,
currencySymbol string
);
CREATE TABLE IF NOT EXISTS circulatings (
id integer primary key autoincrement,
clientId string,
token string,
frequency integer,
ticker string,
name string,
nickname bool,
activity string,
decimals integer,
currencySymbol string
);
CREATE TABLE IF NOT EXISTS valuelocks (
id integer primary key autoincrement,
clientId string,
token string,
frequency integer,
ticker string,
name string,
nickname bool,
color bool,
activity string,
decorator string,
decimals integer,
currency string,
currencySymbol string,
source string
);
CREATE TABLE IF NOT EXISTS tokens (
id integer primary key autoincrement,
clientId string,
token string,
frequency integer,
name string,
nickname bool,
color bool,
activity string,
network string,
contract string,
decorator string,
decimals integer,
source string
);
CREATE TABLE IF NOT EXISTS holders (
id integer primary key autoincrement,
clientId string,
token string,
frequency integer,
nickname bool,
activity string,
network string,
address string,
apiToken string
);
CREATE TABLE IF NOT EXISTS gases (
id integer primary key autoincrement,
clientId string,
token string,
apiToken string,
frequency integer,
nickname bool,
network string
);
CREATE TABLE IF NOT EXISTS boards (
id integer primary key autoincrement,
clientId string,
token string,
frequency integer,
name string,
nickname bool,
color bool,
crypto bool,
header string,
items string
);
CREATE TABLE IF NOT EXISTS floors (
id integer primary key autoincrement,
clientId string,
token string,
frequency integer,
color bool,
currency string,
nickname bool,
activity string,
marketplace string,
name string,
decorator string
);`
_, err = db.Exec(bootstrap)
if err != nil {
logger.Errorf("Unable to bootstrap db file: %s\n", err)
logger.Warning("Will not be storing state.")
var dbNull *sql.DB
return dbNull
}
// v3.8.0 - add multiplier
_, err = db.Exec("alter table tickers add column multiplier default 1;")
if err == nil {
logger.Warnln("Added new column to tickers: multiplier (1)")
} else if err.Error() == "SQL logic error: duplicate column name: multiplier (1)" {
logger.Debug("New column already exists in tickers: multiplier (1)")
} else if err != nil {
logger.Errorln(err)
logger.Warning("Will not be storing state.")
var dbNull *sql.DB
return dbNull
}
// v3.11.0 - add gas API Token
_, err = db.Exec("alter table gases add column apiToken default \"\";")
if err == nil {
logger.Warnln("Added new column to gases: apiToken (1)")
} else if err.Error() == "SQL logic error: duplicate column name: apiToken (1)" {
logger.Debug("New column already exists in gases: apiToken (1)")
} else if err != nil {
logger.Errorln(err)
logger.Warning("Will not be storing state.")
var dbNull *sql.DB
return dbNull
}
// v3.11.0 - add floor activity
_, err = db.Exec("alter table floors add column activity default \"\";")
if err == nil {
logger.Warnln("Added new column to floors: activity (1)")
} else if err.Error() == "SQL logic error: duplicate column name: activity (1)" {
logger.Debug("New column already exists in floors: activity (1)")
} else if err != nil {
logger.Errorln(err)
logger.Warning("Will not be storing state.")
var dbNull *sql.DB
return dbNull
}
// v3.11.0 - add floor color
_, err = db.Exec("alter table floors add column color default false;")
if err == nil {
logger.Warnln("Added new column to floors: color (1)")
} else if err.Error() == "SQL logic error: duplicate column name: color (1)" {
logger.Debug("New column already exists in floors: color (1)")
} else if err != nil {
logger.Errorln(err)
logger.Warning("Will not be storing state.")
var dbNull *sql.DB
return dbNull
}
// v3.11.0 - add floor decorator
_, err = db.Exec("alter table floors add column decorator default \"\";")
if err == nil {
logger.Warnln("Added new column to floors: decorator (1)")
} else if err.Error() == "SQL logic error: duplicate column name: decorator (1)" {
logger.Debug("New column already exists in floors: decorator (1)")
} else if err != nil {
logger.Errorln(err)
logger.Warning("Will not be storing state.")
var dbNull *sql.DB
return dbNull
}
// v3.11.0 - add floor currency
_, err = db.Exec("alter table floors add column currency default \"\";")
if err == nil {
logger.Warnln("Added new column to floors: currency (1)")
} else if err.Error() == "SQL logic error: duplicate column name: currency (1)" {
logger.Debug("New column already exists in floors: currency (1)")
} else if err != nil {
logger.Errorln(err)
logger.Warning("Will not be storing state.")
var dbNull *sql.DB
return dbNull
}
// v3.10.6
_, err = db.Exec("alter table holders add column apiToken default \"\";")
if err == nil {
logger.Warnln("Added new column to holders: apiToken (1)")
} else if err.Error() == "SQL logic error: duplicate column name: apiToken (1)" {
logger.Debug("New column already exists in floors: apiToken (1)")
} else if err != nil {
logger.Errorln(err)
logger.Warning("Will not be storing state.")
var dbNull *sql.DB
return dbNull
}
logger.Infof("Will be storing state in %s\n", fileName)
return db
}
// getID retrive an id for a bot
func getIDToken(token string) (string, error) {
var id string
dg, err := discordgo.New("Bot " + token)
if err != nil {
logger.Errorf("Creating Discord session: %s", err)
return id, err
}
botUser, err := dg.User("@me")
if err != nil {
logger.Errorf("Getting bot user: %s", err)
return id, err
}
return botUser.ID, nil
}
// setName will update a bots name
func setName(session *discordgo.Session, name string) {
user, err := session.User("@me")
if err != nil {
logger.Errorf("Getting bot user: %s", err)
return
}
if user.Username == name {
logger.Debugf("Username already matches: %s", name)
return
}
_, err = session.UserUpdate(name, "")
if err != nil {
logger.Errorf("Updating bot username: %s", err)
return
}
logger.Debugf("%s changed to %s", user.Username, name)
}
// setRole changes color roles based on change
func setRole(session *discordgo.Session, id, guild string, increase bool) error {
var redRole string
var greeenRole string
// get the roles for color changing
roles, err := session.GuildRoles(guild)
if err != nil {
return err
}
// find role ids
for _, r := range roles {
if r.Name == "tickers-red" {
redRole = r.ID
} else if r.Name == "tickers-green" {
greeenRole = r.ID
}
}
// make sure roles exist
if len(redRole) == 0 || len(greeenRole) == 0 {
return errors.New("unable to find roles for color changes")
}
// assign role based on change
if increase {
err = session.GuildMemberRoleRemove(guild, id, redRole)
if err != nil {
return err
}
err = session.GuildMemberRoleAdd(guild, id, greeenRole)
if err != nil {
return err
}
} else {
err = session.GuildMemberRoleRemove(guild, id, greeenRole)
if err != nil {
return err
}
err = session.GuildMemberRoleAdd(guild, id, redRole)
if err != nil {
return err
}
}
return nil
}