-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathmain.js
4763 lines (4113 loc) · 191 KB
/
main.js
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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ------------------------------------------------------------------------
*
* _____ _ _ ____ _
* |_ ____ _ _| | _(_| __ ) ___ | |_
* | |/ __| | | | |/ | | _ \ / _ \| __|
* | |\__ | |_| | <| | |_) | (_) | |_
* |_||___/\__,_|_|\_|_|____/ \___/ \__|
*
*
*
* Author: Logan S. ~ EthyMoney#5000(Discord) ~ EthyMoney(GitHub)
* Base: Forked from "TsukiBot", written by Oscar F. ~ Cehhiro(Discord)
* Program: TsukiBot
* GitHub: https://github.com/EthyMoney/TsukiBot
*
* Discord bot that offers a wide range of services related to cryptocurrencies
*
* No parameters on start except -d for developer mode (disables periodic caching)
*
* If you like this service, consider donating to show support :)
* ETH address: 0x169381506870283cbABC52034E4ECc123f3FAD02
*
*
* Hello from Minnesota USA!
* ⋆⁺₊⋆ ☾ ⋆⁺₊⋆
*
* ------------------------------------------------------------------------ */
// -------------------------------------------
// IMPORTANT STEPS FOR FIRST RUN
// -------------------------------------------
// 1. Make sure you have node.js and npm installed and ready to use. Node version 14.x or newer is required.
// 2. Open a terminal in the project directory and run the command "npm install" to install all required dependencies.
// 3. Create a keys.api file in the common folder to include all of your own keys, tokens, and passwords that are needed for normal operation of all services.
// You can find the template keys.api file to reference in the "How to set up keys file" text file within the docs folder. Just fill in the blanks!
// 4. Head down toward the bottom of this file and take note of the comment in the getChart function. You may need to comment out that executable path for
// chromium depending on your environment. The commend there tells you whether you need to do it or not. (charts may not work if you don't check this!)
// For details on how to structure this file and what you need in it, check the "How to set up keys file" guide in the docs folder.
// 5. Set up your PostgreSQL database according to the schema defined in the docs folder.
// 6. Head into the docs folder and check the fix guide for the graviex package and apply that fix.
// 7. You are now ready to start the bot! Go ahead and run this file to start up. EX: "node main.js"
// If you have any questions or issues, feel free to contact me in the support discord server and I'll try to help you out. Link: https://discordapp.com/invite/VWNUbR5
// Alright the hard part is over. Carry on :)
// -------------------------------------------
// -------------------------------------------
//
// SETUP AND DECLARATIONS
//
// -------------------------------------------
// -------------------------------------------
// Node stuff
const process = require('node:process');
const os = require('node:os');
const crypto = require('node:crypto');
// Dev mode to disable unnecessary operations for testing
const devMode = (process.argv[2] === '-d') ? true : false;
// File read for JSON and PostgreSQL
const fs = require('fs');
const pg = require('pg');
//const pgp = require('pg-promise')(); // TODO: switch non-promise implementation to use this promise based one
// Scheduler
const schedule = require('node-schedule');
// Set the prefix
const prefix = ['-t', '.tb', '-T', '.TB', '.Tb', '.tB'];
// Files allowed
const extensions = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'mov', 'mp4'];
// Include fancy console outputs
const chalk = require('chalk');
// Read in and initialize all files
let keys, pairs_CG, pairs_CG_arr, metadata, admin, shortcutConfig, restricted, tagsJSON;
initializeFiles();
// Top.gg bot statistics reporter
const { AutoPoster } = require('topgg-autoposter');
let poster; // Will be initialized upon startup
// HTTP stuff
const WebSocket = require('ws');
// Include API things
const { Client, GatewayIntentBits, ShardClientUtil, Permissions, EmbedBuilder } = require('discord.js');
const cc = require('cryptocompare');
const CoinMarketCap = require('coinmarketcap-api');
const ccxt = require('ccxt');
const graviex = require('graviex');
const CoinGecko = require('coingecko-api');
const NodeExr = require('currencyexchanges');
const finnhub = require('finnhub');
const Web3 = require('web3');
// Google Cloud language translations
const googleProjectID = keys.googleCloudProjectID;
const googleProjectApiKeyPath = keys.googleCloudProjectKeyPath;
const { Translate } = require('@google-cloud/translate').v2;
// Express server for charts
const path = require('path');
const express = require('express');
const app = express();
const dir = path.join(process.cwd(), 'public');
chartServer();
// Express server for coin prices API
const apiApp = express();
const apiAppPort = 3330;
// Automatic color selector for embeds
const colorAverager = require('fast-average-color-node');
// Puppeteer for interacting with the headless server and manipulating charts
const { Cluster } = require('puppeteer-cluster');
let cluster;
chartsProcessingCluster();
// PNG image comparison tool for validating charts images
const PixelDiff = require('pixel-diff');
// Unique ID generator // TODO: (will get used in the future for scheduled actions stuff)
//const uniqid = require('uniqid');
// CMC/CG Cache
let cmcArray = {};
let cmcArrayDict = {};
let cmcArrayDictParsed = [];
let cgArrayDictParsed = [];
let cgArrayDict = {};
let fails = 0;
let auto = true;
let selectedKey = 0;
let cacheUpdateRunning = false;
let startupProgress = 0;
let forexRates = {};
// Spellcheck
const didyoumean = require('didyoumean');
// JS DOM Selections
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
// Connect to database
const conString = 'postgres://bigboi:' + keys.tsukibot + '@' + keys.dbAddress + ':5432/tsukibot';
//const connp = pgp(conString); // TODO: switch non-promise implementation to use this promise based one
// Declare general global variables
let messageCount = 0;
let referenceTime = Date.now();
let yeetLimit = 0; // Spam limit count
let chartTagID = 0;
let globalCGSleepTimeout = 25000; // used to set sleep interval between cg cache update queries
// Initialize api things
const clientKraken = new ccxt.kraken();
const bitmex = new ccxt.bitmex();
const CoinGeckoClient = new CoinGecko();
const clientPoloniex = new ccxt.poloniex();
const clientBinance = new ccxt.binance();
const clientBittrex = new ccxt.bittrex();
const clientBitfinex = new ccxt.bitfinex2();
const clientCoinbase = new ccxt.coinbasepro();
const clientStex = new ccxt.stex();
const finnhubClient = new finnhub.DefaultApi();
const translate = new Translate({ projectId: googleProjectID, keyFilename: googleProjectApiKeyPath });
const web3eth = new Web3(`https://mainnet.infura.io/v3/${keys.infura}`);
const ExchangeRate = new NodeExr({ primaryCurrency: 'USD' });
//clientcmc will be re-initialized upon bot startup, key selection will be automatic and this selected key here is temporary
let clientcmc = new CoinMarketCap(keys.coinmarketcapfailover);
graviex.accessKey = keys.graviexAccessKey;
graviex.secretKey = keys.graviexSecretKey;
const fh_api_key = finnhub.ApiClient.instance.authentications.api_key;
fh_api_key.apiKey = keys.finnhub;
// Reload Coins
const reloaderCG = require('./getCoinsCG');
// Donation and footer stuff
const quote = 'Enjoying TsukiBot? Tell your friends!';
const botInviteAdd = '\nAdd the bot to other servers by using `.tb invite` for the link :)';
const inviteLink = 'https://discordapp.com/oauth2/authorize?client_id=506918730790600704&scope=bot&permissions=268823664';
// Scheduled Actions for normal operation
if (!devMode) {
schedule.scheduleJob('*/10 * * * *', getCMCData); // fetch every 10 min
schedule.scheduleJob('*/30 * * * *', getCGData); // fetch every 30 min
schedule.scheduleJob('*/2 * * * *', resetSpamLimit); // reset every 2 min
schedule.scheduleJob('0 12 * * *', updateCoins); // update at 12 am and pm every day
schedule.scheduleJob('*/30 * * * *', getCoin360Heatmap); // fetch every 30 min
schedule.scheduleJob('0 */6 * * *', updateExchangeRates); // update every 6 hours
schedule.scheduleJob('1 */1 * * *', function () { // update cmc key on the first minute after every hour
updateCmcKey(); // explicit call without arguments to prevent the scheduler fireDate from being sent as a key override.
});
}
// -------------------------------------------
// -------------------------------------------
//
// UTILITY FUNCTIONS
//
// -------------------------------------------
// -------------------------------------------
/* --------------------------------------------
These methods are calls on the api of the
respective exchanges and other services
for price checks and so much more.
These methods are the core functionality
of the bot. Command calls will usually end
in one of these.
-------------------------------------------- */
//------------------------------------------
//------------------------------------------
// Function for Coinbase Pro prices
async function getPriceCoinbase(channel, coin1, coin2, author) {
let fail = false;
let tickerJSON = '';
if (typeof coin2 === 'undefined') {
coin2 = 'BTC';
}
if (coin2.toLowerCase() === 'usd' || coin1.toLowerCase() === 'btc' && (coin2.toLowerCase() !== 'gbp' &&
coin2.toLowerCase() !== 'eur' && coin2.toLowerCase() !== 'dai' && coin2.toLowerCase('eth') && coin2.toLowerCase('usdc'))) {
coin2 = 'USD';
}
console.log(chalk.green('Coinbase price requested by ' + chalk.yellow(author.username) + ' for ' + chalk.cyan(coin1) + '/' + chalk.cyan(coin2)));
tickerJSON = await clientCoinbase.fetchTicker(coin1.toUpperCase() + '/' + coin2.toUpperCase()).catch(function () {
console.log(chalk.red.bold('Coinbase error: Ticker ' + chalk.cyan(coin1.toUpperCase() + '/' + coin2.toUpperCase()) + ' not found!'));
channel.send('API Error: Coinbase does not have market symbol __' + coin1.toUpperCase() + '/' + coin2.toUpperCase() + '__');
fail = true;
});
if (fail) {
//exit the function if ticker didn't exist, or api failed to respond
return;
}
let s = parseFloat(tickerJSON.last).toFixed(8);
s = trimDecimalPlaces(s);
let ans = '__Coinbase__ Price for **' + coin1.toUpperCase() + '-' + coin2.toUpperCase() + '** is: `' + s + ' ' + coin2.toUpperCase() + '` .';
channel.send(ans);
}
//------------------------------------------
//------------------------------------------
// Function for Graviex prices
async function getPriceGraviex(channel, coin1, coin2, author) {
let graviexJSON;
let price = 0;
let change = 0;
let volume = 0;
let volumeCoin = 0;
if (typeof coin2 === 'undefined') {
coin2 = 'BTC';
}
if (coin2.toLowerCase() === 'usd' || coin1.toLowerCase() === 'btc') {
coin2 = 'USDT';
}
coin1 = coin1 + '';
coin2 = coin2 + '';
console.log(chalk.green('Graviex price requested by ' + chalk.yellow(author.username) + ' for ' + chalk.cyan(coin1) + '/' + chalk.cyan(coin2)));
await graviex.ticker(coin1.toLowerCase() + coin2.toLowerCase(), function (res) {
let moon = '';
graviexJSON = res;
if (typeof graviexJSON.ticker === 'undefined') {
channel.send('Internal error. Requested pair does not exist or Graviex is overloaded.');
console.log((chalk.red('Graviex error : graviex failed to respond.')));
return;
}
price = trimDecimalPlaces(graviexJSON.ticker.last);
change = graviexJSON.ticker.change;
change = parseFloat(change * 100).toFixed(2);
volume = graviexJSON.ticker.volbtc;
volumeCoin = graviexJSON.ticker.vol;
if (change > 20) { moon = ':full_moon_with_face:'; }
let ans = '__Graviex__ Price for **' + coin1.toUpperCase() + '-' + coin2.toUpperCase() + '** is: `' + price + ' ' + coin2.toUpperCase() + '` ' + '(' + '`' + change + '%' + '`' + ') ' + moon;
if (coin2.toLowerCase() === 'btc') {
ans = ans + '\n \\/\\/\\/\\/**24hr volume **➪ `' + parseFloat(volume).toFixed(4) + ' ' + coin2.toUpperCase() + '` ' + '➪ `' + numberWithCommas(parseFloat(volumeCoin).toFixed(0)) + ' ' + coin1.toUpperCase() + '`';
}
channel.send(ans);
});
}
//------------------------------------------
//------------------------------------------
// Function for STEX prices
async function getPriceSTEX(channel, coin1, coin2, author) {
let fail = false;
let tickerJSON = '';
if (typeof coin2 === 'undefined') {
coin2 = 'BTC';
}
if (coin2.toLowerCase() === 'usd' || coin1.toLowerCase() === 'btc') {
coin2 = 'USDT';
}
console.log(chalk.green('STEX price requested by ' + chalk.yellow(author.username) + ' for ' + chalk.cyan(coin1) + '/' + chalk.cyan(coin2)));
tickerJSON = await clientStex.fetchTicker(coin1.toUpperCase() + '/' + coin2.toUpperCase()).catch(function () {
console.log(chalk.red.bold('STEX error: Ticker ' + chalk.cyan(coin1.toUpperCase() + '/' + coin2.toUpperCase()) + ' not found!'));
channel.send('API Error: STEX does not have market symbol __' + coin1.toUpperCase() + '/' + coin2.toUpperCase() + '__ or the API failed to respond at this time.');
fail = true;
});
if (fail) {
//exit the function if ticker didn't exist, or api failed to respond
return;
}
let s = parseFloat(tickerJSON.last).toFixed(8);
s = trimDecimalPlaces(s);
let c = tickerJSON.info.change;
c = parseFloat(c).toFixed(2);
let ans = '__STEX__ Price for **' + coin1.toUpperCase() + '-' + coin2.toUpperCase() + '** is: `' + s + ' ' + coin2.toUpperCase() + '` ' + '(' + '`' + c + '%' + '`' + ')' + '.';
channel.send(ans);
}
//------------------------------------------
//------------------------------------------
// Function for Coin Gecko prices
async function getPriceCoinGecko(coin, coin2, channel, action, author) {
//don't let command run if cache is still updating for the first time
if (cacheUpdateRunning && !devMode) {
channel.send(`I'm still completing my initial startup procedures. Currently ${startupProgress}% done, try again in a moment please.`);
console.log(chalk.magentaBright('Attempted use of CG command prior to initialization. Notification sent to user.'));
return;
}
// determine whether or not the call was from the conversion command to determine if we need to return the values
let noSend = false;
if (action && action == 'convert') {
noSend = true;
}
let arr = [];
let data = [];
coin = coin.toLowerCase() + '';
// default to usd if no comparison is provided
if (!coin2) {
coin2 = 'usd';
}
coin2 = coin2.toLowerCase();
if (!noSend) console.log(chalk.green('CoinGecko price requested by ' + chalk.yellow(author.username) + ' for ' + chalk.cyan(coin) + '/' + chalk.cyan(coin2)));
// find out the ID for coin requested and also get IDs for any possible duplicate tickers
let foundCount = 0;
let coinID, coinID1, coinID2, coinID3 = '';
for (let i = 0, len = cgArrayDictParsed.length; i < len; i++) {
if (cgArrayDictParsed[i].symbol.toLowerCase() == coin) {
if (foundCount == 0)
coinID = cgArrayDictParsed[i].id;
if (foundCount == 1)
coinID1 = cgArrayDictParsed[i].id;
if (foundCount == 2)
coinID2 = cgArrayDictParsed[i].id;
if (foundCount == 3) {
coinID3 = cgArrayDictParsed[i].id;
}
foundCount++;
}
}
// process for if multiple coins are found with the same ticker
if (foundCount > 1) {
//special handling for conversion calls
if (noSend) {
if (foundCount == 2)
cgArrayDictParsed.forEach((value) => {
if (value.id == coinID || value.id == coinID1) {
data.push(value);
}
});
if (foundCount == 3)
cgArrayDictParsed.forEach((value) => {
if (value.id == coinID || value.id == coinID1 || value.id == coinID2) {
data.push(value);
}
});
if (foundCount == 4)
cgArrayDictParsed.forEach((value) => {
if (value.id == coinID || value.id == coinID1 || value.id == coinID2 || value.id == coinID3) {
data.push(value);
}
});
// sort by MC rank ascending order with nulls placed at the end
data = data.sort(function (a, b) {
return (b.market_cap_rank != null) - (a.market_cap_rank != null) || a.market_cap_rank - b.market_cap_rank;
});
}
// normal cg price call, so we need to check pairing currencies
else {
if (foundCount == 2)
data = await CoinGeckoClient.simple.price({
ids: [coinID, coinID1],
vs_currencies: ['usd', coin2.toLowerCase()],
include_24hr_vol: [true],
include_24hr_change: [true]
});
if (foundCount == 3)
data = await CoinGeckoClient.simple.price({
ids: [coinID, coinID1, coinID2],
vs_currencies: ['usd', coin2.toLowerCase()],
include_24hr_vol: [true],
include_24hr_change: [true]
});
if (foundCount == 4)
data = await CoinGeckoClient.simple.price({
ids: [coinID, coinID1, coinID2, coinID3],
vs_currencies: ['usd', coin2.toLowerCase()],
include_24hr_vol: [true],
include_24hr_change: [true]
});
}
// build the reply message that shows all coins found with the given ticker, and label them by full name
let builtMessage = '';
let errorMessage = '';
let cursor = 0;
if (noSend) {
arr = data;
}
else {
arr = Object.entries(data.data);
}
let conversionArray1 = [];
let conversionArray2 = [];
let conversionArray3 = [];
arr.forEach(element => {
cursor++;
let s, c, name;
if (noSend) {
name = element.name;
s = parseFloat(element.current_price).toFixed(8);
c = parseFloat(element.price_change_percentage_24h).toFixed(2);
}
else {
name = element[0];
s = parseFloat(element[1][coin2]).toFixed(8);
c = Math.round(element[1][coin2.toLowerCase() + '_24h_change'] * 100) / 100;
}
s = trimDecimalPlaces(s);
if (!noSend) {
if (!isNaN(s)) { // looking for NaN, making sure price is valid
if (cursor == 1) {
builtMessage += '__CoinGecko Price for:__\n**' + name.toUpperCase() + '--' + coin2.toUpperCase() + '** is: `' + s +
' ' + coin2.toUpperCase() + '` (`' + c + '%`).\n';
}
else {
builtMessage += '**' + name.toUpperCase() + '--' + coin2.toUpperCase() + '** is: `' + s +
' ' + coin2.toUpperCase() + '` (`' + c + '%`).\n';
}
//console.log(chalk.green('CoinGecko API ticker response: ' + chalk.cyan(s)));
}
else {
errorMessage = 'Pricing not available in terms of **' + coin2.toUpperCase() + '**. Try another pairing!';
}
}
else {
conversionArray1.push(s);
conversionArray2.push(c);
conversionArray3.push(name);
}
});
if (!noSend)
channel.send(builtMessage + errorMessage);
else
return [conversionArray1, conversionArray2, conversionArray3];
}
// process for when only one coin is found for a ticker
else {
if (foundCount == 1) {
let s, c;
if (noSend) {
cgArrayDictParsed.forEach((value) => {
if (value.id == coinID) {
data.push(value);
}
});
s = parseFloat(data[0].current_price).toFixed(8);
c = parseFloat(data[0].price_change_percentage_24h).toFixed(2);
}
else {
data = await CoinGeckoClient.simple.price({
ids: [coinID],
vs_currencies: ['usd', coin2.toLowerCase()],
include_24hr_vol: [true],
include_24hr_change: [true]
});
s = parseFloat(data.data[coinID][coin2]).toFixed(8);
c = Math.round(data.data[coinID][coin2.toLowerCase() + '_24h_change'] * 100) / 100;
}
s = trimDecimalPlaces(s);
if (isNaN(s) || !s) { // looking for NaN, making sure price is valid
channel.send('**' + coin.toUpperCase() + '** was found, but the pairing currency **' + coin2.toUpperCase() + '** was not found. Try another pairing!');
return;
}
if (!noSend) {
channel.send('__CoinGecko__ Price for **' + coin.toUpperCase() + '-' + coin2.toUpperCase() + '** is: `' +
s + ' ' + coin2.toUpperCase() + '` (`' + c + '%`).');
}
else {
return [[s], [c], [null]];
}
}
else {
channel.send('Provided coin **' + coin.toUpperCase() + '** was not found!');
}
}
}
//------------------------------------------
//------------------------------------------
// Function for CoinMarketCap prices
function getPriceCMC(coins, channel, action = '-', ext = 'd') {
// don't let command run if cache is still updating for the first time
if (cacheUpdateRunning && !devMode) {
channel.send(`I'm still completing my initial startup procedures. Currently ${startupProgress}% done, try again in a moment please.`);
console.log(chalk.magentaBright('Attempted use of CG command prior to initialization. Notification sent to user.'));
return;
}
if (!cmcArrayDict.BTC) return;
// check for no input
if (coins.length == 0) {
return;
}
let ordered = {};
let messageHeader;
if (action === 'p') {
messageHeader = '__CoinMarketCap__ Price for Top 10 Coins:\n';
}
else {
messageHeader = '__CoinMarketCap__ Price for:\n';
}
let message = '';
let ep, bp, up; //pricing values (usd, btc, eth)
try {
for (let i = 0; i < coins.length; i++) {
if (!cmcArrayDict[coins[i].toUpperCase()]) {
let g = didyoumean(coins[i].toUpperCase(), Object.keys(cmcArrayDict));
if (!g)
continue;
else
coins[i] = g;
}
// Special case for a specific badly formatted coin from the API
if (coins[i].toLowerCase() == 'lyxe') {
coins[i] = 'LYXe';
}
//log the json entry for selected coin
//console.log(cmcArrayDict[coins[i].toUpperCase()]);
// Get the price data from cache and format it accordingly
let plainPriceUSD = trimDecimalPlaces(parseFloat(cmcArrayDict[coins[i].toUpperCase()].quote.USD.price).toFixed(6));
let plainPriceETH = trimDecimalPlaces(parseFloat(convertToETHPrice(cmcArrayDict[coins[i].toUpperCase()].quote.USD.price)).toFixed(8));
let plainPriceBTC = trimDecimalPlaces(parseFloat(convertToBTCPrice(cmcArrayDict[coins[i].toUpperCase()].quote.USD.price)).toFixed(8));
let upchg = Math.round(parseFloat(cmcArrayDict[coins[i].toUpperCase()].quote.USD.percent_change_24h) * 100) / 100;
// unused due to api key limits
//let bpchg = Math.round(parseFloat(cmcArrayDict[coins[i].toUpperCase()].quote.BTC.percent_change_24h) * 100) / 100;
//let epchg = Math.round(parseFloat(cmcArrayDict[coins[i].toUpperCase()].quote.ETH.percent_change_24h) * 100) / 100;
// Assembling the text lines for response message
up = plainPriceUSD + ' '.repeat(8 - plainPriceUSD.length) + ' USD` (`' + upchg + '%`)';
bp = plainPriceBTC + ' '.repeat(10 - plainPriceBTC.length) + ' BTC` ';//(`' + bpchg + '%`)';
ep = plainPriceETH + ' '.repeat(10 - plainPriceETH.length) + ' ETH` ';//(`'// + epchg + '%`)';
coins[i] = (coins[i].length > 6) ? coins[i].substring(0, 6) : coins[i];
switch (action) {
case '-':
message += ('`• ' + coins[i].toUpperCase() + ' '.repeat(6 - coins[i].length) + ' ⇒` `' + (ext === 's' ? bp : up) + '\n');
break;
case '+':
message += ('`• ' + coins[i].toUpperCase() + ' '.repeat(6 - coins[i].length) + ' ⇒` `' +
bp + '\n');
break;
case '*':
message += ('`• ' + coins[i].toUpperCase() + ' '.repeat(6 - coins[i].length) + ' ⇒ 💵` `' +
up + '\n`| ⇒` `' +
bp + '\n');
break;
case 'e':
message += ('`• ' + coins[i].toUpperCase() + ' '.repeat(6 - coins[i].length) + ' ⇒` `' +
ep + '\n');
break;
case '%':
if (cmcArrayDict[coins[i].toUpperCase()])
ordered[cmcArrayDict[coins[i].toUpperCase()].quote.USD.percent_change_24h] =
('`• ' + coins[i].toUpperCase() + ' '.repeat(6 - coins[i].length) + ' ⇒` `' + (ext === 's' ? bp : up) + '\n');
break;
default:
message += ('`• ' + coins[i].toUpperCase() + ' '.repeat(6 - coins[i].length) + ' ⇒` `' + (ext === 's' ? bp : up) + '\n');
break;
}
}
if (action === '%') {
let k = Object.keys(ordered).sort(function (a, b) { return parseFloat(b) - parseFloat(a); });
for (let k0 in k)
message += ordered[k[k0]];
}
}
catch (err) {
console.log(chalk.redBright('Error in CMC price command processing. ') + chalk.cyanBright('Here is the trace:'));
console.error(err);
return;
}
message += (Math.random() > 0.99) ? '\n' + quote + ' ' + botInviteAdd : '';
if (message !== '')
channel.send(messageHeader + message).catch((err) => {
console.log(chalk.redBright('Error sending response message in CMC price command...') + chalk.cyanBright('Here is the trace:'));
console.error(err);
});
}
//------------------------------------------
//------------------------------------------
// Function for CoinGecko prices
// (in similar format the list-style cmc command above)
function getPriceCG(coins, channel, action = '-', ext = 'd', tbpaIgnoreMultiTickers = false, interaction) {
// don't let command run if cache is still updating for the first time
if (cacheUpdateRunning && !devMode) {
if (interaction) {
interaction.reply(`I'm still completing my initial startup procedures. Currently ${startupProgress}% done, try again in a moment please.`);
return;
}
else {
channel.send(`I'm still completing my initial startup procedures. Currently ${startupProgress}% done, try again in a moment please.`);
console.log(chalk.magentaBright('Attempted use of CG command prior to initialization. Notification sent to user.'));
return;
}
}
// check for no input
if (coins.length == 0) {
return;
}
console.log(chalk.magentaBright('Incoming coins for call:'), chalk.cyanBright(coins));
let ordered = {};
let messageHeader;
let selectedCoinObjects = [];
let message_part1 = '';
if (action === 'p') {
messageHeader = '__CoinGecko__ Price for Top 10 Coins:\n';
}
else if (action === 'm') {
messageHeader = '__CoinGecko__ Price for Top 5 Gainers and Losers:\n';
}
else {
messageHeader = '__CoinGecko__ Price for:\n';
}
let message = '';
let ep, bp, up; //pricing values (ep=ethprice, bp=btcprice, up=usdprice)
for (let i = 0; i < coins.length; i++) {
coins[i] = coins[i].toUpperCase(); //make all input coins uppercase
}
for (let i = 0; i < coins.length; i++) {
// for getting coin by ID (biggest movers action call)
if (action === 'm') {
// look through cache and get each matching coin, but skip those damn worthless peg coins!
cgArrayDictParsed.forEach((coinObject) => {
if (coinObject.id.toUpperCase() == coins[i]) {
if (coinObject.name.includes('Binance-Peg')) {
return; //skip adding this peg coin
}
else {
selectedCoinObjects.push(coinObject);
// replace the id in the coins array with the symbol (for readability)
coins[i] = coinObject.symbol.toUpperCase();
}
}
});
}
// otherwise process as normal call and look for symbols
else {
if (!cgArrayDict[coins[i]]) {
let g = didyoumean(coins[i], Object.keys(cgArrayDict));
if (!g)
continue;
else {
coins[i] = g;
}
}
// look through cache and get each matching coin, but skip those damn worthless peg coins!
cgArrayDictParsed.forEach((coinObject) => {
if (coinObject.symbol.toUpperCase() == coins[i]) {
if (coinObject.name.includes('Binance-Peg')) {
return; //skip adding this peg coin
}
else {
selectedCoinObjects.push(coinObject);
}
}
});
}
// iterate through all instances of an identical ticker if applicable
let coinIdentifier = '';
let tbpaIterator = 0;
selectedCoinObjects.forEach((coinObject) => {
//! This segment is commented since we are not showing the multi tickers for right now
// if (selectedCoinObjects.length > 1 && !tbpaIgnoreMultiTickers) {
// // grab coin name to display next to price in order to differentiate between the other same ticker coins
// coinIdentifier = ` (${coinObject.name})`;
// }
//!
//!!! NOTICE, IMPORTANT!
//! This disables the recently added feature of showing all instances of coins with the same tickers in standard price calls!
//? After deploying this update to the bot I realized it's very messy and just not a great way to handle the issue. I'm putting this
//? feature on pause for now until the user preferences stuff is set up and this feature can be a customizable and configurable option.
const DISABLED_MULTI_TICKER_SUPPORT = true;
// don't iterate through all if tbpa display is active
if (tbpaIgnoreMultiTickers || DISABLED_MULTI_TICKER_SUPPORT) {
tbpaIterator++;
}
if (tbpaIterator > 1) {
return; //ignore tickers after first one if this is a tbpa call (will be updated later, but this is to prevent tbpa's from suddenly getting all messy)
}
// set price string lengths
let usdLength = 8, btcEthLength = 10;
// get the price data from cache and format it accordingly (grabs the coin with the highest MC)
if (!coinObject) {
console.log(chalk.redBright(`ERR in CG price command: Selected coin object came up as undefined for: ${coins[i]}`));
return;
}
// check if the number with 6 decimal places still only shows zeros, switch to 10 places if needed for more resolution
let plainPriceUSD = (parseFloat(coinObject.current_price).toFixed(6) == 0) ?
trimDecimalPlaces(parseFloat(coinObject.current_price).toFixed(10)) :
trimDecimalPlaces(parseFloat(coinObject.current_price).toFixed(6));
let plainPriceETH = trimDecimalPlaces(parseFloat(convertToETHPrice(coinObject.current_price)).toFixed(8));
let plainPriceBTC = trimDecimalPlaces(parseFloat(convertToBTCPrice(coinObject.current_price)).toFixed(8));
let upchg = Math.round(parseFloat(coinObject.price_change_percentage_24h_in_currency) * 100) / 100;
// ignore percent in cases where it's a new coin and 24hr percent is not yet available
if (!upchg && upchg != 0) {
upchg = 'n/a ';
}
// unused due to api limits
//let bpchg = Math.round(parseFloat(cgArrayDict[coins[i]].quote.BTC.percent_change_24h) * 100) / 100;
//let epchg = Math.round(parseFloat(cgArrayDict[coins[i]].quote.ETH.percent_change_24h) * 100) / 100;
// assembling the text lines for response message
if (usdLength - plainPriceUSD.length < 0) {
// special case for bigger numbers (will skip formatting)
up = plainPriceUSD + ' USD` (`' + upchg + '%`)';
}
else {
up = plainPriceUSD + ' '.repeat(usdLength - plainPriceUSD.length) + ' USD` (`' + upchg + '%`)';
}
if (btcEthLength - plainPriceBTC.length < 0 || btcEthLength - plainPriceETH.length < 0) {
// special case for bigger numbers (will skip formatting)
bp = plainPriceBTC + ' BTC` ';
ep = plainPriceETH + ' ETH` ';
}
else {
bp = plainPriceBTC + ' '.repeat(btcEthLength - plainPriceBTC.length) + ' BTC` '; //(`' + bpchg + '%`)';
ep = plainPriceETH + ' '.repeat(btcEthLength - plainPriceETH.length) + ' ETH` '; //(`'// + epchg + '%`)';
}
// TODO: add eur price and chg as well. (will need to get additional pair data from api to do this)
coins[i] = (coins[i].length > 6) ? coins[i].substring(0, 6) : coins[i];
switch (action) {
case '-':
message += ('`• ' + coins[i] + ' '.repeat(6 - coins[i].length) + ' ⇒` `' + (ext === 's' ? bp : up) + coinIdentifier + '\n');
break;
case '+':
message += ('`• ' + coins[i] + ' '.repeat(6 - coins[i].length) + ' ⇒` `' + bp + coinIdentifier + '\n');
break;
case '*':
message += ('`• ' + coins[i] + ' '.repeat(6 - coins[i].length) + ' ⇒ 💵` `' + up + '\n`| ⇒` `' + bp + coinIdentifier + '\n');
break;
case 'e':
message += ('`• ' + coins[i] + ' '.repeat(6 - coins[i].length) + ' ⇒` `' + ep + coinIdentifier + '\n');
break;
case '%':
if (coinObject)
ordered[coinObject.price_change_percentage_24h_in_currency] =
('`• ' + coins[i] + ' '.repeat(6 - coins[i].length) + ' ⇒` `' + (ext === 's' ? bp : up) + coinIdentifier + '\n');
break;
default:
message += ('`• ' + coins[i] + ' '.repeat(6 - coins[i].length) + ' ⇒` `' + (ext === 's' ? bp : up) + coinIdentifier + '\n');
break;
}
});//end of looping through same-ticker coins
coinIdentifier = ''; // clear coin id
selectedCoinObjects = []; // clear array for next coin
// see if we need to overflow into a second message (for really long lists of coins)
let lineLimit = (action == '*') ? 75 : 40;
if (message_part1.length == 0 && 1950 - message.length <= lineLimit) {
message_part1 = message;
message = '';
}
}
if (action === '%') {
let k = Object.keys(ordered).sort(function (a, b) { return parseFloat(b) - parseFloat(a); });
for (let k0 in k) {
// see if we need to overflow into a second message (for really long lists of coins)
if (message_part1.length == 0 && 1950 - message.length <= 40) {
message_part1 = message;
message = '';
}
message += ordered[k[k0]];
}
}
// Random invite notification message
message += (Math.random() > 0.99) ? '\n' + quote + ' ' + botInviteAdd : '';
// Check for confused people looking for help, and prompt them for the real help command
if (coins.length == 1 && coins.includes('HELP')) {
message += '\nLooking for the help with using the bot? Use `/help`.';
}
// Check for message being too long even after the 2-message split
if (message.length > 2000) {
if (interaction) {
interaction.reply('Error: Your tbpa is too long to send! Please remove some coins and try again. Use `/tbpa-remove` to remove coins.');
return;
}
else {
channel.send('Error: Your tbpa is too long to send! Please remove some coins and try again. Use `.tb pa` to see how to do this.');
console.log(chalk.magenta('Oversize tbpa notification sent to user above. Size overflow message: ') + chalk.cyan(message.length));
return;
}
}
if (message.length > 0) {
if (interaction) {
interaction.reply(messageHeader + message);
}
else {
if (message_part1.length > 0) {
channel.send(messageHeader + message_part1);
channel.send(message);
}
else {
channel.send(messageHeader + message);
}
}
}
}
//------------------------------------------
//------------------------------------------
// Function for Crypto Compare prices
function getPriceCC(coins, channel, author, ext = 'd') {
console.log(chalk.green('CryptoCompare price(s) requested by ' + chalk.yellow(author.username) + ' for ' + chalk.cyan(coins.toString())));
let query = coins.concat(['BTC']);
// Get the spot price of the pair and send it to general
cc.priceFull(query.map(function (c) { return c.toUpperCase(); }), ['USD', 'BTC'])
.then(prices => {
let message = '__CryptoCompare__ Price for:\n';
let bpchg = parseFloat(cmcArrayDict.BTC.percent_change_24h);
for (let i = 0; i < coins.length; i++) {
let bp, up;
// Attempt to use CC first, then pull from CMC if there's a failure
try {
bp = trimDecimalPlaces(prices[coins[i].toUpperCase()].BTC.PRICE.toFixed(8)) + ' BTC` (`' +
Math.round(prices[coins[i].toUpperCase()].BTC.CHANGEPCT24HOUR * 100) / 100 + '%`)';
up = trimDecimalPlaces(parseFloat(prices[coins[i].toUpperCase()].USD.PRICE).toFixed(6)) + ' USD` (`' +
Math.round((prices[coins[i].toUpperCase()].BTC.CHANGEPCT24HOUR + prices.BTC.USD.CHANGEPCT24HOUR) * 100) / 100 + '%`)';
} catch (e) {
if (cmcArrayDict[coins[i].toUpperCase()]) {
bp = trimDecimalPlaces(convertToBTCPrice(parseFloat(cmcArrayDict[coins[i].toUpperCase()].quote.USD.price))) + ' BTC` (`' +
Math.round(parseFloat(cmcArrayDict[coins[i].toUpperCase()].quote.USD.percent_change_24h - bpchg) * 100) / 100 + '%`)';
up = trimDecimalPlaces(parseFloat(cmcArrayDict[coins[i].toUpperCase()].quote.USD.price).toFixed(6)) + ' USD` (`' +
Math.round(parseFloat(cmcArrayDict[coins[i].toUpperCase()].quote.USD.percent_change_24h) * 100) / 100 + '%`)';
} else {
bp = 'unavailable`';
up = 'unavailable`';
}
}
coins[i] = (coins[i].length > 6) ? coins[i].substring(0, 6) : coins[i];
message += ('`• ' + coins[i].toUpperCase() + ' '.repeat(6 - coins[i].length) + ' ⇒` `' + (ext === 's' ? bp : up) + '\n');
}
channel.send(message);
})
.catch(console.log);
}
//------------------------------------------
//------------------------------------------
// Function for Bitfinex prices
async function getPriceBitfinex(author, coin1, coin2, channel, coin2Failover) {
let tickerJSON = '';
if (!coin2) {
coin2 = 'BTC';
}
if (!coin2Failover) {
if (coin2.toLowerCase() === 'usd' || coin1.toLowerCase() === 'btc' && (coin2.toLowerCase() !== 'gbp' && !coin2Failover &&
coin2.toLowerCase() !== 'eur' && coin2.toLowerCase() !== 'dai' && coin2.toLowerCase() !== 'jpy' && coin2.toLowerCase() !== 'eos')) {
coin2 = 'USDT';
}
}
console.log(chalk.green('Bitfinex price requested by ' + chalk.yellow(author.username) + ' for ' + chalk.cyan(coin1) + '/' + chalk.cyan(coin2)));
tickerJSON = await clientBitfinex.fetchTicker(coin1.toUpperCase() + '/' + coin2.toUpperCase()).catch(function () {
//if re-attempted call failed, exit due to error
if (coin2Failover) {
console.log(chalk.red.bold('Bitfinex error: Ticker ' + chalk.cyan(coin1.toUpperCase() + '/' + coin2.toUpperCase()) + ' not found!'));
channel.send('API Error: Bitfinex does not have market symbol __' + coin1.toUpperCase() + '/' + coin2.toUpperCase() + '__');
return;
}
//attempt re-calling with usd coin2 correction if failure occurs
getPriceBitfinex(author, coin1, 'USD', channel, true);
//Exit rest of loop for re-run
return;
});