-
Notifications
You must be signed in to change notification settings - Fork 12
/
index2.js
3565 lines (3052 loc) · 132 KB
/
index2.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
require("dotenv").config()
const {ChainId, Fetcher, Route, Trade, TokenAmount, TradeType, WETH, Token} = require('@uniswap/sdk');
var yaxis = null;
var pair = null;
const Discord = require("discord.js")
const client = new Discord.Client();
const clientFaqPrice = new Discord.Client();
clientFaqPrice.login(process.env.BOT_TOKEN_SNX);
const clientPegPrice = new Discord.Client();
clientPegPrice.login(process.env.BOT_TOKEN_PEG);
const clientTknPrice = new Discord.Client();
clientTknPrice.login(process.env.BOT_TOKEN_TKN);
const clientEthPrice = new Discord.Client();
clientEthPrice.login(process.env.BOT_TOKEN_ETH);
const clientCRVPrice = new Discord.Client();
clientCRVPrice.login(process.env.BOT_TOKEN_CRV);
const clientSWTHPrice = new Discord.Client();
clientSWTHPrice.login(process.env.BOT_TOKEN_SWTH);
const clientPicklePrice = new Discord.Client();
clientPicklePrice.login(process.env.BOT_TOKEN_PICKLE);
const clientMetaPrice = new Discord.Client();
clientMetaPrice.login(process.env.BOT_TOKEN_META);
const clientYUSDPrice = new Discord.Client();
clientYUSDPrice.login(process.env.BOT_TOKEN_YUSD);
const clientVIDYAPrice = new Discord.Client();
clientVIDYAPrice.login(process.env.BOT_TOKEN_VIDYA);
const clientYFVPrice = new Discord.Client();
clientYFVPrice.login(process.env.BOT_TOKEN_YFV);
const clientYFVOldPrice = new Discord.Client();
clientYFVOldPrice.login(process.env.BOT_TOKEN_YFV_OLD);
const clientYaxisPrice = new Discord.Client();
clientYaxisPrice.login(process.env.BOT_TOKEN_YAXIS);
const clientYaxisSupply = new Discord.Client();
clientYaxisSupply.login(process.env.BOT_TOKEN_YAXIS_SUPPLY);
const clientSwervePrice = new Discord.Client();
clientSwervePrice.login(process.env.BOT_TOKEN_SWERVE);
const clientHegicPrice = new Discord.Client();
clientHegicPrice.login(process.env.BOT_TOKEN_HEGIC);
const clientDodoPrice = new Discord.Client();
clientDodoPrice.login(process.env.BOT_TOKEN_DODO);
const clientDrcPrice = new Discord.Client();
clientDrcPrice.login(process.env.BOT_TOKEN_DRC);
const clientPerpPrice = new Discord.Client();
clientPerpPrice.login(process.env.BOT_TOKEN_PERP);
const clientNecPrice = new Discord.Client();
clientNecPrice.login(process.env.BOT_TOKEN_NEC);
const replaceString = require('replace-string');
const https = require('https');
const http = require('http');
const redis = require("redis");
let redisClient = null;
var fs = require('fs');
var snxRewardsPerMinterUsd = 0.013;
var snxToMintUsd = 1.933;
var snxRewardsThisPeriod = "940,415 SNX";
var totalDebt = "$71,589,622";
var gasPrice = 240;
var fastGasPrice = 300;
var lowGasPrice = 200;
var instantGasPrice = 350;
var ethPrice = 360;
var tknPrice = 0.77;
var tknMarketCap = 19161119;
var swthPrice = 0.063;
var swthMarketCap = 35196236;
var picklePrice = 53;
var pickleEthPrice = 0.14334229;
var crvPrice = 3.84;
var swervePrice = 0.668;
var swerveMarketcap = 5242720;
var necPrice = 0.159;
var necMarketcap = 25318817;
var dodoPrice = 0.53;
var dodoMarketcap = 6384478;
var perpPrice = 0.89;
var perpMarketcap = 13626611;
var drcPrice = 0.052;
var drcMarketcap = 501271;
var hegicPrice = 0.122;
var hegicMarketcap = 25416960;
var yaxisCircSupply = 246040.59;
var yaxisTotalSuuply = 445188.84;
var yusdPrice = 1.14;
var yusdMarketCap = 257668486;
var yfvPrice = 7.95;
var yfvMarketCap = 29341110;
var yfvOldPrice = 7.95;
var yfvOldMarketCap = 29341110;
var vidyaPrice = 0.0298;
var vidyaEthPrice = 0.00008887;
var metaPrice = 3.90;
var metaMarketCap = 0.0105;
var yaxisPrice = 4.72;
var yaxisEth = 0.006;
var yaxisMarketCap = 860000;
var snxPrice = 6.9;
var mintGas = 415000;
var claimGas = 380000;
var burnGas = 420000;
var periodVolume = "$33,026,800";
var currentFees = "$159,604";
var unclaimedFees = "$40,808";
var poolDistribution = ["sUSD (51.1%)", "sETH (16.6%)", "sBTC (14.9%)", "iETH (8.1%)", "Others (9.2%)"];
var usdtPeg = 1;
var usdcPeg = 1;
var coingeckoUsd = 3.74;
var coingeckoEth = 0.01051993;
var coingeckoBtc = 0.000351;
var binanceUsd = 3.74;
var kucoinUsd = 3.74;
var payday = new Date('2020-08-12 13:00');
const Synth = class {
constructor(name, price, gain) {
this.name = name;
this.price = price;
this.gain = gain;
}
name;
price;
gain;
description = '';
};
var synths = new Array();
var synthsMap = new Map();
let gasSubscribersMap = new Map();
let gasSubscribersLastPushMap = new Map();
let votesMapNew = new Map();
console.log("Redis URL:" + process.env.REDIS_URL);
if (process.env.REDIS_URL) {
redisClient = redis.createClient(process.env.REDIS_URL);
redisClient.on("error", function (error) {
console.error(error);
});
redisClient.get("gasSubscribersMap", function (err, obj) {
gasSubscribersMapRaw = obj;
console.log("gasSubscribersMapRaw:" + gasSubscribersMapRaw);
if (gasSubscribersMapRaw) {
gasSubscribersMap = new Map(JSON.parse(gasSubscribersMapRaw));
console.log("gasSubscribersMap:" + gasSubscribersMap);
}
});
redisClient.get("gasSubscribersLastPushMap", function (err, obj) {
gasSubscribersLastPushMapRaw = obj;
console.log("gasSubscribersLastPushMapRaw:" + gasSubscribersLastPushMapRaw);
if (gasSubscribersLastPushMapRaw) {
gasSubscribersLastPushMap = new Map(JSON.parse(gasSubscribersLastPushMapRaw));
console.log("gasSubscribersLastPushMap:" + gasSubscribersLastPushMap);
}
});
redisClient.get("votesMapNew", function (err, obj) {
votesMapRaw = obj;
console.log("votesMapRaw:" + votesMapRaw);
if (votesMapRaw) {
votesMapNew = new Map(JSON.parse(votesMapRaw));
console.log("votesMapNew:" + votesMapNew);
}
});
}
let channel = null;
let trades = null;
let trades100 = null;
let trades1000 = null;
let general = null;
let councilChannel = null;
let fundChannel = null;
let testChannel = null;
let guild = null;
async function checkMessages() {
let countsUsers = new Map();
client.channels.fetch('413890591840272398').then(async c => {
//+ textChannel.messages.fetch({ limit: 10 });
const fetchAll = require('discord-fetch-all');
const allMessages = await fetchAll.messages(c, {
reverseArray: true, // Reverse the returned array
userOnly: true, // Only return messages by users
botOnly: false, // Only return messages by bots
pinnedOnly: false, // Only returned pinned messages
});
// Will return an array of all messages in the channel
// If the channel has no messages it will return an empty array
console.log(allMessages);
allMessages.forEach(mes => {
var created = mes.createdTimestamp;
let joinedMinsAgo = Date.now() - created;
joinedMinsAgo = (((joinedMinsAgo / 1000) / 60));
joinedMinsAgo = Math.round(((joinedMinsAgo) + Number.EPSILON) * 100) / 100;
if (joinedMinsAgo < 2880) {
var username = mes.author.username;
if (countsUsers.has(username)) {
countsUsers.set(username, (countsUsers.get(username) + 1))
} else {
countsUsers.set(username, 1)
}
}
})
countsUsers[Symbol.iterator] = function* () {
yield* [...this.entries()].sort((a, b) => a[1] - b[1]);
}
for (let [key, value] of countsUsers) { // get data sorted
console.log(key + ' ' + value);
}
})
}
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
client.channels.fetch('785320922278133800').then(c => {
trades = c
});
client.channels.fetch('785321056197935124').then(c => {
trades100 = c
});
client.channels.fetch('790349176289624084').then(c => {
trades1000 = c
});
client.channels.fetch('413890591840272398').then(c => {
general = c;
});
client.channels.fetch('794935827436011531').then(c => {
councilChannel = c;
});
client.channels.fetch('791459254862086155').then(c => {
fundChannel = c;
});
client.channels.fetch('705191770903806022').then(c => {
testChannel = c;
});
checkMessages();
client.guilds.cache.forEach(function (value, key) {
if (value.name.toLowerCase().includes('synthetix')) {
guild = value;
}
});
})
client.on("guildMemberAdd", function (member) {
member.send("Hi and welcome to Synthetix! I am Synthetix FAQ bot. I will be very happy to assist you, just ask me for **help**.");
});
client.on('messageReactionAdd', (reaction, user) => {
let msg = reaction.message, emoji = reaction.emoji;
if (emoji.name == '❌') {
if (msg.author.username.includes("FAQ")) {
if (!user.username.includes("FAQ")) {
msg.delete({timeout: 300 /*time unitl delete in milliseconds*/});
}
}
}
});
function doInnerQuestion(command, doReply, msg) {
try {
let rawdata = fs.readFileSync('answers/' + command + '.json');
let answer = JSON.parse(rawdata);
const exampleEmbed = new Discord.MessageEmbed();
exampleEmbed.setColor(answer.color);
exampleEmbed.setTitle(answer.title);
exampleEmbed.setDescription(answer.description);
exampleEmbed.setURL(answer.url);
if (command == "7") {
exampleEmbed.addField("Safe low gas price:", lowGasPrice + ' gwei', false);
exampleEmbed.addField("Standard gas price:", gasPrice + ' gwei', false);
exampleEmbed.addField("Fast gas price:", fastGasPrice + ' gwei', false);
exampleEmbed.addField("Instant gas price:", instantGasPrice + ' gwei', false);
if (doReply) {
msg.reply(exampleEmbed);
} else {
msg.channel.send(exampleEmbed).then(function (message) {
message.react("❌");
}).catch(function () {
//Something
});
}
} else if (command == "9") {
exampleEmbed.addField("USD (binance)", binanceUsd, false);
exampleEmbed.addField("USD (kucoin)", kucoinUsd, false);
exampleEmbed.addField("USD (coingecko)", coingeckoUsd, false);
exampleEmbed.addField("ETH (coingecko):", coingeckoEth, false);
exampleEmbed.addField("BTC (coingecko):", coingeckoBtc, false);
if (doReply) {
msg.reply(exampleEmbed);
} else {
msg.channel.send(exampleEmbed).then(function (message) {
message.react("❌");
}).catch(function () {
//Something
});
}
} else if (command == "61") {
https.get('https://api.coingecko.com/api/v3/coins/ethereum', (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
let result = JSON.parse(data);
exampleEmbed.addField("USD", result.market_data.current_price.usd, false);
exampleEmbed.addField("BTC:", result.market_data.current_price.btc, false);
if (doReply) {
msg.reply(exampleEmbed);
} else {
msg.channel.send(exampleEmbed).then(function (message) {
message.react("❌");
}).catch(function () {
//Something
});
}
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
} else if (command == "8") {
https.get('https://api.coingecko.com/api/v3/coins/nusd', (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
let result = JSON.parse(data);
exampleEmbed.addField("USD (coingecko)", result.market_data.current_price.usd, false);
exampleEmbed.addField("USDC (1inch)", usdcPeg, false);
exampleEmbed.addField("USDT (1inch)", usdtPeg, false);
if (result.market_data.current_price.usd == 1 && usdcPeg == 1 && usdtPeg == 1) {
exampleEmbed.attachFiles(['images/perfect.jpg'])
.setImage('attachment://perfect.jpg');
}
if (doReply) {
msg.reply(exampleEmbed);
} else {
msg.channel.send(exampleEmbed).then(function (message) {
message.react("❌");
}).catch(function () {
//Something
});
}
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
} else if (command == "13") {
var today = new Date();
while (today > payday) {
payday.setDate(payday.getDate() + 7);
}
var difference = payday.getTime() - today.getTime();
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
exampleEmbed.addField("Countdown:", days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds ", false);
if (doReply) {
msg.reply(exampleEmbed);
} else {
msg.channel.send(exampleEmbed).then(function (message) {
message.react("❌");
}).catch(function () {
//Something
});
}
} else if (command == "62") {
exampleEmbed.addField("Volume in this period:", periodVolume, false);
if (doReply) {
msg.reply(exampleEmbed);
} else {
msg.channel.send(exampleEmbed).then(function (message) {
message.react("❌");
}).catch(function () {
//Something
});
}
} else if (command == "66") {
var synthsGainers = "";
var synthsBreakEven = "";
var synthsLosers = "";
synths.forEach(function (s) {
let arrow = (s.gain.replace(/%/g, "") * 1.0 == 0) ? " - " : (s.gain.replace(/%/g, "") * 1.0 > 0) ? " ⤤ " : " ⤥ ";
if (arrow.includes("⤤")) {
synthsGainers += s.name + " " + s.price + " " + s.gain + arrow + "\n";
}
if (arrow.includes("⤥")) {
synthsLosers += s.name + " " + s.price + " " + s.gain + arrow + "\n";
}
if (arrow.includes("-")) {
synthsBreakEven += s.name + " " + s.price + " " + s.gain + arrow + "\n";
}
});
exampleEmbed.addField("Synth gainers:", synthsGainers, false);
exampleEmbed.addField("Synth no change:", synthsBreakEven, false);
exampleEmbed.addField("Synth losers:", synthsLosers, false);
if (doReply) {
msg.reply(exampleEmbed);
} else {
msg.channel.send(exampleEmbed).then(function (message) {
message.react("❌");
}).catch(function () {
//Something
});
}
} else if (command == "74") {
var synthsPrices = "";
for (var i = 0; i < 10; i++) {
synthsPrices += synths[i].name + " " + synths[i].price + " " + synths[i].gain + " ⤤\n";
}
exampleEmbed.addField("Biggest gainers:", synthsPrices, false);
if (doReply) {
msg.reply(exampleEmbed);
} else {
msg.channel.send(exampleEmbed).then(function (message) {
message.react("❌");
}).catch(function () {
//Something
});
}
} else if (command == "75") {
var synthsPrices = "";
for (var i = 1; i < 11; i++) {
synthsPrices += synths[synths.length - i].name + " " + synths[synths.length - i].price + " " + synths[synths.length - i].gain + " ⤥\n";
}
exampleEmbed.addField("Biggest losers:", synthsPrices, false);
if (doReply) {
msg.reply(exampleEmbed);
} else {
msg.channel.send(exampleEmbed).then(function (message) {
message.react("❌");
}).catch(function () {
//Something
});
}
} else if (command == "82") {
for (var i = 0; i < (walletsToReturn.length > 20 ? 20 : walletsToReturn.length); i++) {
exampleEmbed.addField(walletsToReturn[i].address,
"[etherscan](https://etherscan.io/address/" + walletsToReturn[i].address + "): " + walletsToReturn[i].cRatio + "%, snxBalance:" + walletsToReturn[i].snxCount
+ " escrowedSnxCount:" + walletsToReturn[i].escrowedSnxCount
, false);
}
if (doReply) {
msg.reply(exampleEmbed);
} else {
msg.channel.send(exampleEmbed).then(function (message) {
message.react("❌");
}).catch(function () {
//Something
});
}
} else if (command == "92") {
for (const [key, value] of flaggedAccountsMap.entries()) {
exampleEmbed.addField(key,
"[etherscan](https://etherscan.io/address/" + key + "): " + value.cRatio + "%, snxBalance:" + value.snxCount
+ " escrowedSnxCount:" + value.escrowedSnxCount + " flaggedTime:" + value.flaggedTime +
"\nETA to liquidation:" + value.etaToLiquidation
, false);
}
if (doReply) {
msg.reply(exampleEmbed);
} else {
msg.channel.send(exampleEmbed).then(function (message) {
message.react("❌");
}).catch(function () {
//Something
});
}
} else if (command == "100") {
let counter = 1;
for (c of council) {
exampleEmbed.addField(counter++, c, false);
}
var today = new Date();
var difference = voteDay.getTime() - today.getTime();
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
exampleEmbed.addField("Countdown:", days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds ", false);
if (doReply) {
msg.reply(exampleEmbed);
} else {
msg.channel.send(exampleEmbed).then(function (message) {
message.react("❌");
}).catch(function () {
//Something
});
}
} else {
answer.fields.forEach(function (field) {
exampleEmbed.addField(field.title, field.value, field.inline);
});
if (answer.footer.title) {
exampleEmbed.setFooter(answer.footer.title, answer.footer.value);
}
if (answer.image) {
exampleEmbed.attachFiles(['images/' + answer.image])
.setImage('attachment://' + answer.image);
}
if (answer.thumbnail) {
exampleEmbed.attachFiles(['images/' + answer.thumbnail])
.setThumbnail('attachment://' + answer.thumbnail);
}
if (doReply) {
msg.reply(exampleEmbed);
} else {
msg.channel.send(exampleEmbed).then(function (message) {
message.react("❌");
}).catch(function () {
//Something
});
}
}
} catch (e) {
if (doReply) {
msg.reply("Oops, there seems to be something wrong there. \nChoose your question with ***question questionNumber***, e.g. **question 1**\nYou can get the question number via **list**");
} else {
msg.reply("Oops, there seems to be something wrong there. \nChoose your question with ***!FAQ question questionNumber***, e.g. **question 1**\nYou can get the question number if you send me **list** in DM");
}
}
}
client.on("message", msg => {
if (!msg.author.username.includes("FAQ")) {
if (!(msg.channel.type == "dm")) {
// this is logic for channels
if (msg.content.toLowerCase().trim() == "!faq") {
msg.reply("Hi, I am Synthetix FAQ bot. I will be very happy to assist you, just ask me for **help** in DM.");
}
// else if (msg.content.toLowerCase().includes("<@!513707101730897921>")) {
// msg.reply("I've called for master, he will be with you shortly.");
// }
else if (msg.content.toLowerCase().trim() == "!faq soonthetix") {
msg.channel.send('It will be:', {
files: [
"images/soonthetix.gif"
]
}).then(function (message) {
message.react("❌");
}).catch(function () {
//Something
});
} else if (msg.content.toLowerCase().trim() == "!faq help") {
msg.reply("I can only answer a predefined question by its number or by alias in a channel, e.g. **question 1**, or **gas price**. \n For more commands and options send me **help** in DM");
} else if (msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').startsWith("!faq question")) {
doQuestion(msg, "!faq question", false);
} else if (msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').startsWith("!faq q ")) {
doQuestion(msg, "!faq q", false);
} else if (msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').startsWith("!faq q")) {
const args = msg.content.slice('!faq q'.length);
if (!isNaN(args)) {
doInnerQuestion(args, false, msg);
}
} else if (msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').startsWith("!faq calculate rewards")) {
let content = msg.content.toLowerCase().trim().replace(/ +(?= )/g, '');
const args = content.slice("faq calculate rewards".length).split(' ');
args.shift();
const command = args.shift().trim();
if (command && !isNaN(command)) {
var gas = false;
if (content.includes("with")) {
var argsSecondPart = content.slice(content.indexOf("with") + "with".length).split(' ');
argsSecondPart.shift();
gas = argsSecondPart.shift().trim();
}
doCalculate(command, msg, gas, false);
}
} else if (msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').startsWith("!faq calculate susd rewards")) {
const args = msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').slice("!faq calculate susd rewards".length).split(' ');
args.shift();
const command = args.shift().trim();
if (command && !isNaN(command)) {
doCalculateSusd(command, msg, false);
}
} else if (msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').startsWith("!faq show wallet")) {
const args = msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').slice("!faq show wallet".length).split(' ');
args.shift();
const command = args.shift().trim();
getMintrData(msg, command, false);
} else if (msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').startsWith("!faq synth ")) {
const args = msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').slice("!faq synth".length).split(' ');
args.shift();
const command = args.shift().trim();
if (command) {
doShowSynth(command, msg, false);
}
} else if (msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').startsWith("!faq show chart")) {
msg.reply("No longer supported. Use $ticker snx");
} else if (msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').startsWith("!faq ")) {
let found = checkAliasMatching(false);
if (!found) {
let notFoundMessage = "Oops, I don't know that one. You can check out my user guide: https://www.notion.so/Synthetix-Discord-FAQ-Bot-bb9f93cd2d1148ba86c0abbc58b06da0";
msg.channel.send(notFoundMessage).then(function (message) {
message.react("❌");
}).catch(function () {
//Something
});
}
}
} else {
try {
// this is the logic for DM
console.log("I got sent a DM:" + msg.content);
let found = checkAliasMatching(true);
// if alias is found, just reply to it, otherwise continue
if (!found) {
let encodedForm = Buffer.from(msg.content.toLowerCase()).toString('base64');
if (checkIfUltimateQuestion(encodedForm)) {
answerUltimateQuestion();
} else if (msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').startsWith("unsubscribe")) {
gasSubscribersMap.delete(msg.author.id);
gasSubscribersLastPushMap.delete(msg.author.id);
if (process.env.REDIS_URL) {
redisClient.set("gasSubscribersMap", JSON.stringify([...gasSubscribersMap]), function () {
});
redisClient.set("gasSubscribersLastPushMap", JSON.stringify([...gasSubscribersLastPushMap]), function () {
});
}
msg.reply("You are now unsubscribed from gas updates");
} else if (msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').startsWith("subscribe gas")) {
const args = msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').slice("subscribe gas".length).split(' ');
args.shift();
const command = args.shift().trim();
if (command && !isNaN(command)) {
gasSubscribersMap.set(msg.author.id, command);
gasSubscribersLastPushMap.delete(msg.author.id);
if (process.env.REDIS_URL) {
redisClient.set("gasSubscribersMap", JSON.stringify([...gasSubscribersMap]), function () {
});
redisClient.set("gasSubscribersLastPushMap", JSON.stringify([...gasSubscribersLastPushMap]), function () {
});
}
msg.reply(" I will send you a message once safe gas price is below " + command + " gwei , and every hour after that that it remains below that level. \nTo change the threshold level for gas price, send me a new subscribe message with the new amount.\n" +
"To unsubscribe, send me another DM **unsubscribe**.");
} else {
msg.reply(command + " is not a proper integer number.");
}
} else if (msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').startsWith("show wallet")) {
const args = msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').slice("show wallet".length).split(' ');
args.shift();
const command = args.shift().trim();
getMintrData(msg, command, true);
} else if (msg.content.toLowerCase().trim() == "aliases") {
showAllAliases(true);
} else if (msg.content.toLowerCase().trim() == "help") {
doFaqHelp();
} else if (msg.content.startsWith("help ")) {
const args = msg.content.slice("help".length).split(' ');
args.shift();
const command = args.shift().trim();
if (command == "question") {
msg.reply("Choose your question with ***question questionNumber***, e.g. ***question 1***\nYou can get the question number via **list** command");
} else if (command == "category") {
msg.reply("Choose your category with ***category categoryName***, e.g. ***category SNX-Rewards***\nCategory name is fetched from **categories** command");
} else if (command == "search") {
msg.reply("Search for questions with ***search searchTerm***, e.g. ***search failing transactions***");
} else {
msg.reply("I don't know that one. Try just **help** for known commands");
}
} else if (msg.content.toLowerCase().trim() == "list" || msg.content.toLowerCase().trim() == "questions") {
listQuestions();
} else if (msg.content.toLowerCase().startsWith("question ")) {
console.log("question asked:" + msg.content);
doQuestion(msg, "question", true);
} else if (msg.content.toLowerCase().startsWith("q ")) {
console.log("question asked:" + msg.content);
doQuestion(msg, "q", true);
} else if (msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').startsWith("q")) {
const args = msg.content.slice('q'.length);
if (!isNaN(args)) {
doInnerQuestion(args, true, msg);
}
} else if (msg.content == "categories") {
listCategories();
} else if (msg.content.toLowerCase().startsWith("category")) {
const args = msg.content.slice("category".length).split(' ');
args.shift();
const command = args.shift();
let rawdata = fs.readFileSync('categories/categories.json');
let categories = JSON.parse(rawdata);
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('Questions in category ' + command + ':');
let found = false;
categories.forEach(function (category) {
if (category.name == command) {
found = true;
category.questions.forEach(function (question) {
rawdata = fs.readFileSync('questions/' + question + ".txt", "utf8");
exampleEmbed.addField(question, rawdata, false);
});
}
});
if (!found) {
exampleEmbed.addField('\u200b', "That doesn't look like a known category. Use a category name from **categories** command, e.g. **category Staking&Minting**");
} else {
exampleEmbed.addField('\u200b', 'Choose your question with e.g. **question 1**');
}
msg.reply(exampleEmbed);
} else if (msg.content.toLowerCase().startsWith("search ")) {
const args = msg.content.slice("search".length).split(' ').slice(1);
const searchWord = msg.content.substring("search".length + 1);
doSearch(searchWord, args);
} else if (msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').startsWith("calculate rewards")) {
let content = msg.content.toLowerCase().trim().replace(/ +(?= )/g, '');
const args = content.slice("calculate rewards".length).split(' ');
args.shift();
const command = args.shift().trim();
if (command && !isNaN(command)) {
var gas = false;
if (content.includes("with")) {
var argsSecondPart = content.slice(content.indexOf("with") + "with".length).split(' ');
argsSecondPart.shift();
gas = argsSecondPart.shift().trim();
}
doCalculate(command, msg, gas, true);
}
} else if (msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').startsWith("calculate susd rewards")) {
let content = msg.content.toLowerCase().trim().replace(/ +(?= )/g, '');
const args = content.slice("calculate susd rewards".length).split(' ');
args.shift();
const command = args.shift().trim();
if (command && !isNaN(command)) {
var gas = false;
if (content.includes("with")) {
var argsSecondPart = content.slice(content.indexOf("with") + "with".length).split(' ');
argsSecondPart.shift();
gas = argsSecondPart.shift().trim();
}
doCalculateSusd(command, msg, true);
}
} else if (msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').startsWith("synth ")) {
const args = msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').slice("synth".length).split(' ');
args.shift();
const command = args.shift().trim();
if (command) {
doShowSynth(command, msg, true);
}
} else if (msg.content.toLowerCase().trim().replace(/ +(?= )/g, '').startsWith("show chart")) {
msg.reply("No longer supported. Use $ticker snx")
} else {
if (!msg.author.username.toLowerCase().includes("faq")) {
if (msg.content.endsWith("?")) {
const args = msg.content.substring(0, msg.content.length - 1).split(' ');
const searchWord = msg.content;
doCustomQuestion(searchWord, args);
} else {
msg.reply("Oops, I don't know that one. Try **help** to see what I do know, or if you want to ask a custom question, make sure it ends with a question mark **?**");
}
}
}
}
} catch (e) {
msg.reply("Unknown error ocurred. Try **help** to see what I do know, or if you want to ask a custom question, make sure it ends with a question mark **?**");
}
}
}
function showAllAliases(isDM) {
let rawdata = fs.readFileSync('categories/aliases.json');
let aliases = JSON.parse(rawdata);
let questionMap = new Map();
aliases.forEach(function (alias) {
let aliasQuestion = questionMap.get(alias.number);
if (aliasQuestion) {
aliasQuestion.push(alias.alias);
questionMap.set(alias.number, aliasQuestion);
} else {
let aliasQuestion = new Array();
aliasQuestion.push(alias.alias);
questionMap.set(alias.number, aliasQuestion);
}
});
let exampleEmbed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('Known aliases')
.setURL('https://github.com/dgornjakovic/synthetix-faq-bot');
exampleEmbed.setDescription('Hello, here are the aliases I know:');
let counter = 0;
let pagenumber = 2;
for (let [questionNumber, questions] of questionMap) {
let questionsString = "";
questions.forEach(function (q) {
questionsString += (isDM ? "" : "!faq ") + q + "\n";
})
let rawdata = fs.readFileSync('answers/' + questionNumber + '.json');
let answer = JSON.parse(rawdata);
exampleEmbed.addField(answer.title + ' ' + answer.description, questionsString);
counter++;
if (counter == 10) {
if (isDM) {
msg.reply(exampleEmbed);
} else {
msg.channel.send(exampleEmbed).then(function (message) {
message.react("❌");
}).catch(function () {
//Something
});
}
exampleEmbed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('Known aliases page ' + pagenumber)
.setURL('https://github.com/dgornjakovic/synthetix-faq-bot');
exampleEmbed.setDescription('Hello, here are the aliases I know:');
pagenumber++;
counter = 0;
}
}
if (isDM) {
msg.reply(exampleEmbed);
} else {
msg.channel.send(exampleEmbed).then(function (message) {
message.react("❌");
}).catch(function () {
//Something
});
}
}
function answerUltimateQuestion() {
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('Bravo, you found the ultimate question!');
exampleEmbed.setDescription(Buffer.from("d2hhdCBpcyB0aGUgYW5zd2VyIHRvIGxpZmUgdGhlIHVuaXZlcnNlIGFuZCBldmVyeXRoaW5nPw==", 'base64').toString('utf-8'));
exampleEmbed.addField("The answer is:", Buffer.from("NDI=", 'base64').toString('utf-8'));
msg.reply(exampleEmbed);
}
function checkIfUltimateQuestion(encodedForm) {
return encodedForm == "d2hhdCBpcyB0aGUgYW5zd2VyIHRvIGxpZmUgdGhlIHVuaXZlcnNlIGFuZCBldmVyeXRoaW5nPw==" ||
encodedForm == "d2hhdCdzIHRoZSBhbnN3ZXIgdG8gbGlmZSB0aGUgdW5pdmVyc2UgYW5kIGV2ZXJ5dGhpbmc/" ||
encodedForm == "dGhlIGFuc3dlciB0byBsaWZlIHRoZSB1bml2ZXJzZSBhbmQgZXZlcnl0aGluZw==" ||
encodedForm == "d2hhdCBpcyB0aGUgYW5zd2VyIHRvIGxpZmUgdGhlIHVuaXZlcnNlIGFuZCBldmVyeXRoaW5nPw==";
}
function checkAliasMatching(doReply) {
let potentialAlias = msg.content.toLowerCase().replace("!faq", "").trim();
let rawdata = fs.readFileSync('categories/aliases.json');
let aliases = JSON.parse(rawdata);
let found = false;
aliases.forEach(function (alias) {
if (alias.alias.toLowerCase().trim() == potentialAlias) {
found = true;
msg.content = "!faq question " + alias.number;
doQuestion(msg, "!faq question", doReply);
}
});
return found;
}
function doFaqHelp() {
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('Synthetix Frequently Asked Questions')
.setURL('https://help.synthetix.io/hc/en-us');
exampleEmbed.setDescription('Hello, here is list of commands I know:');
exampleEmbed.addField("list", "Lists all known questions");
exampleEmbed.addField("categories", "Lists all categories of known questions");
exampleEmbed.addField("category categoryName", "Lists all known questions for a given category name, e.g. ** category *Staking&Minting* **");
exampleEmbed.addField("question questionNumber", "Shows the answer to the question defined by its number, e.g. ** question *7* **");
exampleEmbed.addField("search searchTerm", "Search all known questions by given search term, e.g. ** search *SNX price* **");
exampleEmbed.addField("aliases", "List all known aliases");