-
Notifications
You must be signed in to change notification settings - Fork 3
/
bot.js
817 lines (763 loc) · 25 KB
/
bot.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
require("dotenv").config();
const {
searchProtocolForSymbol,
searchProtocolForName,
compareProtocolAToProtocolB,
getFirstTVLProtocolsChart,
getTopPerformersChart,
getBestRatioChart,
fairPriceAtATHTVL,
} = require("./utils.js");
const { Bot, session, InputFile, Keyboard } = require("grammy");
const {
conversations,
createConversation,
} = require("@grammyjs/conversations");
const { MenuTemplate, MenuMiddleware } = require("grammy-inline-menu");
const { run } = require("@grammyjs/runner");
const { supabaseAdapter } = require("@grammyjs/storage-supabase");
const { createClient } = require("@supabase/supabase-js");
const bot = new Bot(process.env.TELEGRAM_API);
const supabase = createClient(
process.env.SUPABASE_URL,
process.env.SUPABASE_KEY
);
const storage = supabaseAdapter({
supabase,
table: "session",
});
const chartType = {
1: "bar",
2: "doughnut",
3: "pie",
};
function getSessionKey(ctx) {
return ctx.from?.id.toString();
}
// session variables value is wrapped into an object
// because of a conversation plugin bug
bot.use(
session({
getSessionKey,
storage,
initial: () => ({
commandHistory: { value: [] },
menuIstance: { value: "" },
timesCommandUsed: {
value: {
searchProtocol: 0,
compareProtocols: 0,
fairPrice: 0,
getFirstTVLChart: 0,
getPerformersChart: 0,
getRatioChart: 0,
showHistory: 0,
deleteHistory: 0,
},
},
}),
})
);
bot.use(conversations());
bot.use(createConversation(searchProtocol));
bot.use(createConversation(compareProtocols));
bot.use(createConversation(fairPrice));
bot.use(createConversation(getFirstTVLChart));
bot.use(createConversation(getPerformersChart));
bot.use(createConversation(getRatioChart));
bot.use(createConversation(showHistory));
bot.use(createConversation(deleteHistory));
function buildMenu() {
const menuHTML =
`Please chose an option from the menu:\n\n` +
`🔎 Search a DeFi protocol\n` +
`➗ Get price of protocol A with mcap/tvl ratio of protocol B\n` +
`🚀 Get price of protocol if mcap == TVL when TVL was at ATH\n` +
`🏆 Get top n protocols for TVL\n` +
`📈 Get top n performers/losers of last day/week\n` +
`💎 Get top n protocols with best mcap/tvl or fdv/tvl w/ mcap/fdv\n` +
"🕵️ See your previous commands and replicate them\n" +
"🗑️ Delete your command history\n";
const menu = new MenuTemplate(() => menuHTML);
function addMenuItem(text, command, joinLastRow = false) {
menu.interact(text, command, {
joinLastRow: joinLastRow,
do: async (ctx) => {
ctx.session.menuIstance.value = "";
await ctx.conversation.enter(command);
ctx.session.timesCommandUsed.value[command]++;
return false;
},
});
}
addMenuItem("🔎 Search", "searchProtocol");
addMenuItem("➗ Compare", "compareProtocols", true);
addMenuItem("🚀 FairPrice", "fairPrice", true);
addMenuItem("🏆 TVL", "getFirstTVLChart");
addMenuItem("📈 Performers", "getPerformersChart", true);
addMenuItem("💎 Ratio", "getRatioChart", true);
addMenuItem("🕵️ History", "showHistory");
addMenuItem("🗑️ Clean", "deleteHistory", true);
return new MenuMiddleware("/", menu);
}
const menuMiddleware = buildMenu();
bot.use(menuMiddleware);
async function getNewMenu(ctx) {
if (ctx.session.menuIstance.value) {
try {
await bot.api.deleteMessage(ctx.chat.id, ctx.session.menuIstance.value);
} catch (e) {
console.error(e);
}
}
let menuMessage = await menuMiddleware.replyToContext(ctx);
ctx.session.menuIstance.value = menuMessage.message_id;
}
let welcomeMsg = "🦙 Welcome to DefiLlamaBot!\n\nTo use the bot, press /menu";
let infoMsg1 = `
<b>Some general and maybe useful info: Tokenomics 101 and commands explanation</b>\n
Mcap = Market Cap = Price * Circulating Supply
FDV = Fully Diluted Valuation = Price * Total Supply
TVL = Total Value Locked = $ locked in protocol
Important: when considering Mcap / TVL, it is a good thing to also evaluate Mcap / FDV.
Mcap / FDV is a value between 0 and 1, where near 0 is the worst (very low circulating supply compared to the total supply)
and near 1 is the best;\n
Mcap (or FDV) / TVL is a value greater than 0. The lower it is, the more undervalued the protocol is;
if it's near to 1, in the case of FDV / TVL (and Mcap / FDV if Mcap / FDV is high), we can say the protocol is well
valued (something like a fair price), and greater than 1 it's overvalued.
Let's see now the most interesting commands:
For the command <b>compareProtocols</b>➗, DefiLlama uses Mcap / TVL ratio to compare protocols.\n
For the command <b>fairPrice</b>🚀, we look at the data of the protocol when its TVL was at all time high (ATH);
that point was when the protocol was most used. Than we put Mcap / TVL equal to 1, for what we said above.
Unfortunately, Mcap is not the perfect indicator in this case (FDV would be better, think about the case
Mcap / FDV = 0.01), but we're forced to use it cause we don't have past data about FDV.\n
For the command <b>getRatioChart</b>📈, look at the example below.
`;
let infoMsg2 = `
On the x-axis we have FDV/TVL (remember, the lower the better), on the y-axis Mcap/TVL (the higher the better).
Also you can see protocols have different radius: the smaller the radius, the lower the Mcap (this is because
I wanted to show the fact they have more growth space).
That said, we can say the best protocols are the ones in the top left corner and with the smallest radius (this
means low FDV/TVL, high Mcap/FDV and low Mcap). This is the way you should read this chart.
More questions? Feel free to send me a message on twitter (https://twitter.com/0xCaos) or visit the Github repository
(https://github.com/0xCaos/defillama-telegram-bot);
Also feel free to contribute, or add ideas making a new issue on Github!
Have fun and thank you for using the bot 👊
`;
let ratioExample = "./ratioExample.jpg";
bot.command("start", async (ctx) => {
await ctx.reply(welcomeMsg);
});
bot.command("menu", async (ctx) => {
await getNewMenu(ctx);
});
bot.command("searchProtocol", async (ctx) => await commandSearchProtocol(ctx));
bot.command(
"compareProtocols",
async (ctx) => await commandCompareProtocols(ctx)
);
bot.command("fairPrice", async (ctx) => await commandFairPrice(ctx));
bot.command("getFirstTVLChart", async (ctx) => await commandTvlChart(ctx));
bot.command(
"getPerformersChart",
async (ctx) => await commandPerformersChart(ctx)
);
bot.command("getRatioChart", async (ctx) => await commandRatioChart(ctx));
bot.command("tip", async (ctx) => await sendTip(ctx));
bot.command("info", async (ctx) => {
await ctx.reply(infoMsg1, { parse_mode: "HTML" });
await ctx.replyWithPhoto(new InputFile(ratioExample));
await ctx.reply(infoMsg2, {
parse_mode: "HTML",
disable_web_page_preview: true,
});
});
bot.api.setMyCommands([
{ command: "start", description: "Get a great welcome! 👋" },
{ command: "menu", description: "Show the main menu ⚙️" },
{ command: "info", description: "Some info about this bot 📖" },
{ command: "tip", description: "Send a tip if you enjoy the bot 😊" },
]);
async function commandSearchProtocol(ctx, values) {
let protocol = await searchWithRightFunction(values[0]);
if (protocol) {
await printInfoProtocol(ctx, protocol[0]);
}
}
async function commandCompareProtocols(ctx, values) {
let protocolA = await searchWithRightFunction(values[0]);
let protocolB = await searchWithRightFunction(values[1]);
if (protocolA && protocolB) {
let result = await compareProtocolAToProtocolB(protocolA[0], protocolB[0]);
await printCompareResults(ctx, protocolA, result);
}
}
async function commandFairPrice(ctx, values) {
let protocol = await searchWithRightFunction(values[0]);
if (protocol) {
let result = await fairPriceAtATHTVL(protocol[0].slug);
await printCompareResults(ctx, protocol[0], result);
}
}
async function commandTvlChart(ctx, values) {
let buffer = await getFirstTVLProtocolsChart(values[0], values[1]);
await ctx.replyWithPhoto(new InputFile(buffer));
}
async function commandPerformersChart(ctx, values) {
let buffer = await getTopPerformersChart(
values[0],
values[1],
values[2],
values[3],
values[4]
);
await ctx.replyWithPhoto(new InputFile(buffer));
}
async function commandRatioChart(ctx, values) {
let buffer = await getBestRatioChart(values[0], values[1], values[2]);
await ctx.replyWithPhoto(new InputFile(buffer));
}
async function decideCommandAndReplicate(command, ctx) {
let values = command.split(" ");
ctx.session.timesCommandUsed.value[values[0].replace("/", "")]++;
values.shift();
if (command.includes("searchProtocol")) {
await commandSearchProtocol(ctx, values);
} else if (command.includes("compareProtocols")) {
await commandCompareProtocols(ctx, values);
} else if (command.includes("fairPrice")) {
await commandFairPrice(ctx, values);
} else if (command.includes("getFirstTVLChart")) {
await commandTvlChart(ctx, values);
} else if (command.includes("getPerformersChart")) {
await commandPerformersChart(ctx, values);
} else if (command.includes("getRatioChart")) {
await commandRatioChart(ctx, values);
} else {
await ctx.reply("🥲 Whoops, something went wrong!.");
}
}
async function showHistory(conversation, ctx) {
await ctx.deleteMessage();
if (ctx.session.commandHistory.value.length) {
await ctx.reply(
`<b>Command history:</b>\n\n` +
ctx.session.commandHistory.value
.map((command, index) => `${index + 1}. ${command}`)
.join("\n"),
{ parse_mode: "HTML" }
);
await ctx.reply(
`<b>🔎 Which command do you want to replicate?</b>\n` +
`Type the number of the command you want to replicate.`,
{ parse_mode: "HTML" }
);
let commandIndex;
[ctx, commandIndex] = await getNumberOrCancel(
(number) =>
number > 0 && number <= ctx.session.commandHistory.value.length,
conversation,
ctx
);
if (commandIndex) {
await ctx.reply(`⚙️ Replicating command...`);
await decideCommandAndReplicate(
ctx.session.commandHistory.value[commandIndex - 1],
ctx
);
}
await ctx.reply("That's it! Press /menu to do something else");
} else {
await ctx.reply(
"No commands in history yet. Press /menu to do something else"
);
}
return;
}
async function deleteHistory(conversation, ctx) {
await ctx.deleteMessage();
if (ctx.session.commandHistory.value.length) {
await replyWithKeyboard(
ctx,
"Are you sure you want to delete the history?",
new Keyboard().text("Yes").text("No")
);
ctx = await conversation.wait();
if (ctx.message.text == "Yes") {
ctx.session.commandHistory.value = [];
await ctx.reply("History cleaned 🗑️. Press /menu to do something else");
} else {
await ctx.reply(
"History not cleaned 🏳️. Press /menu to do something else"
);
}
} else {
await ctx.reply(
"Your history is already empty. Press /menu to do something else"
);
}
return;
}
function addCommandToHistory(ctx, command, values) {
values = values.map((value) =>
typeof value == "string" ? value.replace(" ", "") : value
);
values = values.map((value) =>
value === true ? 1 : value === false ? 0 : value
);
let commandString = `${command} ${values.join(" ")}`;
if (!ctx.session.commandHistory.value.includes(commandString)) {
ctx.session.commandHistory.value.push(commandString);
}
}
function getSingleInfo(name, data, ratio) {
if (data) {
if (!ratio) {
return `<b>${name}</b>: ${parseInt(data).toLocaleString("en-US")}$\n`;
} else {
return `<b>${name}</b>: ${data.toFixed(2)}\n`;
}
} else {
return "";
}
}
async function printInfoProtocol(ctx, protocol) {
await ctx.reply(
`<a href="${protocol.logo}"><b>${protocol.name}</b> (${protocol.symbol})</a>\n\n` +
getSingleInfo("TVL", protocol.tvl, false) +
getSingleInfo("FDV", protocol.fdv, false) +
getSingleInfo("Mcap", protocol.mcap, false) +
getSingleInfo("\nMcap / TVL", protocol.mcap / protocol.tvl, true) +
getSingleInfo("FDV / TVL", protocol.fdv / protocol.tvl, true) +
getSingleInfo("Mcap / FDV", protocol.mcap / protocol.fdv, true) +
`\n<a href="${protocol.url}">Website link</a>\n` +
`<a href="https://www.coingecko.com/en/coins/${protocol.gecko_id}">CoinGecko link</a>`,
{ parse_mode: "HTML" }
);
}
async function searchWithRightFunction(msg) {
let result;
if (msg.startsWith("$")) {
result = await searchProtocolForSymbol(msg.substring(1));
} else {
result = await searchProtocolForName(msg);
}
if (result.length > 10) {
result = result.slice(0, 10);
}
return result;
}
async function checkIfProtocolFound(result, conversation, ctx) {
if (result.length > 1) {
await ctx.reply(
"❗ They found more than one result. Please reply with a number (1, 2, 69420, ...):"
);
const results = result.map((r, i) => `${i + 1} - ${r.name}`).join("\n");
const numbers = new Keyboard();
result.map((r, i) => {
numbers.text(`${i + 1}`);
if ((i + 1) % 4 == 0) numbers.row();
});
await ctx.reply(results, {
reply_markup: {
one_time_keyboard: true,
keyboard: numbers.build(),
},
});
let ok = true;
do {
ctx = await conversation.wait();
const index = parseInt(ctx.message.text) - 1;
if (index >= 0 && index < result.length) {
ok = true;
return [ctx, result[index]];
} else {
ok = false;
index + 1 == 69420
? await ctx.reply("😐 LOL that was a joke man, be serious please.")
: await ctx.reply("😡 Invalid number, try again.");
}
} while (!ok);
} else {
if (result.length > 0) {
return [ctx, result[0]];
}
}
return [ctx, undefined];
}
async function tryFindingProtocolOrCancel(conversation, ctx) {
let ok = true;
let protocol = undefined;
do {
ctx = await conversation.wait();
if (ctx.message.text == "/cancel") {
ok = true;
} else {
await ctx.reply("🦙 Asking to Llamas...");
let result = await searchWithRightFunction(ctx.message.text);
[ctx, protocol] = await checkIfProtocolFound(result, conversation, ctx);
if (protocol) {
ok = true;
} else {
await ctx.reply(
"🥲 Whoops! No results found. Try again or press /cancel to abort."
);
ok = false;
}
}
} while (!ok);
return [ctx, protocol];
}
async function searchProtocol(conversation, ctx) {
await ctx.deleteMessage();
await ctx.reply(
"📝 Send the name (ex: Trader Joe) or the symbol with dollar (ex: $JOE):"
);
let protocol;
[ctx, protocol] = await tryFindingProtocolOrCancel(conversation, ctx);
if (protocol) {
await printInfoProtocol(ctx, protocol);
addCommandToHistory(ctx, "/searchProtocol", [protocol.name]);
}
await ctx.reply("That's it! Press /menu to do something else");
return;
}
async function printCompareResults(ctx, protocolA, result) {
await ctx.reply(
`✅ TADAA!\n\n` +
`The new price of ${
protocolA.name
} is <b>$${result[0].toLocaleString()}</b>\n` +
`That's a <b>x${result[1].toFixed(4)}</b>! ${
result[1].toFixed(4) > 1 ? "GREAT!" : "SAD STORY..."
}`,
{ parse_mode: "HTML" }
);
}
async function compareProtocols(conversation, ctx) {
await ctx.deleteMessage();
await ctx.reply("📝 Send the name (or symbol) of the first protocol");
let protocolA, protocolB;
[ctx, protocolA] = await tryFindingProtocolOrCancel(conversation, ctx);
if (protocolA) {
await ctx.reply("📝 Send the name (or symbol) of the second protocol");
[ctx, protocolB] = await tryFindingProtocolOrCancel(conversation, ctx);
if (protocolB) {
await ctx.reply("🤯 Making big maths...");
let result = await compareProtocolAToProtocolB(protocolA, protocolB);
if (result[0] && result[1]) {
await printCompareResults(ctx, protocolA, result);
addCommandToHistory(ctx, "/compareProtocols", [
protocolA.name,
protocolB.name,
]);
} else {
await ctx.reply(
"🥲 Ooops, something went wrong. Probably we couldn't find the price of one of the protocols."
);
}
}
}
await ctx.reply("That's it! Press /menu to do something else");
return;
}
async function fairPrice(conversation, ctx) {
await ctx.deleteMessage();
await ctx.reply(
"📝 Send the name (ex: Trader Joe) or the symbol with dollar (ex: $JOE):"
);
let protocol;
[ctx, protocol] = await tryFindingProtocolOrCancel(conversation, ctx);
if (protocol) {
await ctx.reply("🤯 Making big maths...");
let result = await fairPriceAtATHTVL(protocol.slug);
if (result[0] && result[1]) {
await printCompareResults(ctx, protocol, result);
addCommandToHistory(ctx, "/fairPrice", [protocol.name]);
} else {
await ctx.reply(
"🥲 Ooops, something went wrong. Probably we couldn't find the price of the protocol."
);
}
}
await ctx.reply("That's it! Press /menu to do something else");
return;
}
async function getNumberOrCancel(
condition,
conversation,
ctx,
question,
keyboard
) {
let ok = true;
let number = undefined;
let canceled = false;
do {
ctx = await conversation.wait();
if (ctx.message.text == "/cancel") {
ok = true;
canceled = true;
} else {
number = parseInt(ctx.message.text);
if (condition(number)) {
ok = true;
} else {
await ctx.reply(
"🥲 Invalid number, try again or press /cancel to abort."
);
if (question && keyboard)
await replyWithKeyboard(ctx, question, keyboard);
ok = false;
}
}
} while (!ok);
if (!canceled) return [ctx, number];
else return [ctx, undefined];
}
async function replyWithKeyboard(ctx, question, keyboard) {
await ctx.reply(question, {
reply_markup: {
one_time_keyboard: true,
keyboard: keyboard.build(),
},
});
}
async function getFirstTVLChart(conversation, ctx) {
await ctx.deleteMessage();
const question =
"❓ How many protocols do you want in the chart?\n\n" +
"Send a number between 10 and 50.";
const numberKeyboard = new Keyboard()
.text("10")
.text("15")
.text("20")
.row()
.text("25")
.text("30")
.text("35")
.row()
.text("40")
.text("45")
.text("50");
await replyWithKeyboard(ctx, question, numberKeyboard);
let topN, type;
[ctx, topN] = await getNumberOrCancel(
(number) => number >= 10 && number <= 50,
conversation,
ctx,
question,
numberKeyboard
);
if (topN) {
const question =
"🥸 Chose the type of the chart:\n\n" +
"1 - 📊 Bar\n" +
"2 - 🍩 Doughnut\n" +
"3 - 🥧 Pie\n";
const numberKeyboard = new Keyboard().text("1").text("2").text("3");
await replyWithKeyboard(ctx, question, numberKeyboard);
[ctx, type] = await getNumberOrCancel(
(number) => number >= 1 && number <= 3,
conversation,
ctx,
question,
numberKeyboard
);
if (type) {
await ctx.reply("🖌️ Drawing your nice chart...");
let buffer = await getFirstTVLProtocolsChart(topN, chartType[type]);
await ctx.replyWithPhoto(new InputFile(buffer));
addCommandToHistory(ctx, "/getFirstTVLChart", [topN, chartType[type]]);
}
}
await ctx.reply("That's it! Press /menu to do something else");
return;
}
async function getPerformersChart(conversation, ctx) {
await ctx.deleteMessage();
const question =
"❓ Do you wanna consider top 50 or top 100 protools?\n\n" +
"Send 50 or 100.";
const numberKeyboard = new Keyboard().text("50").text("100");
await replyWithKeyboard(ctx, question, numberKeyboard);
let firstN, topN, best, day, type;
[ctx, firstN] = await getNumberOrCancel(
(number) => number == 50 || number == 100,
conversation,
ctx,
question,
numberKeyboard
);
if (firstN) {
const question =
"❓ How many protocols do you want in the chart?\n\n" +
"Send a number between 10 and 50.";
const numberKeyboard = new Keyboard()
.text("10")
.text("15")
.text("20")
.row()
.text("25")
.text("30")
.text("35")
.row()
.text("40")
.text("45")
.text("50");
await replyWithKeyboard(ctx, question, numberKeyboard);
[ctx, topN] = await getNumberOrCancel(
(number) => number >= 10 && number <= 50,
conversation,
ctx,
question,
numberKeyboard
);
if (topN) {
const question =
"❓ Do you want the best or the worst performers?\n\n" +
"Send 1 for best, 2 for worst.";
const numberKeyboard = new Keyboard().text("1 - Best").text("2 - Worst");
await replyWithKeyboard(ctx, question, numberKeyboard);
[ctx, best] = await getNumberOrCancel(
(number) => number == 1 || number == 2,
conversation,
ctx,
question,
numberKeyboard
);
if (best) {
best == 1 ? (best = true) : (best = false);
const question =
"❓ Do you wanna consider last day or week?\n\n" +
"Send 1 for day, 2 for week.";
const numberKeyboard = new Keyboard().text("1 - Day").text("2 - Week");
await replyWithKeyboard(ctx, question, numberKeyboard);
[ctx, day] = await getNumberOrCancel(
(number) => number == 1 || number == 2,
conversation,
ctx,
question,
numberKeyboard
);
if (day) {
day == 1 ? (day = true) : (day = false);
await ctx.reply("🖌️ Drawing your nice chart...");
let buffer = await getTopPerformersChart(
firstN,
topN,
best,
day,
"bar"
);
await ctx.replyWithPhoto(new InputFile(buffer));
addCommandToHistory(ctx, "/getPerformersChart", [
firstN,
topN,
best,
day,
"bar",
]);
}
}
}
}
await ctx.reply("That's it! Press /menu to do something else");
return;
}
async function getRatioChart(conversation, ctx) {
await ctx.deleteMessage();
const question =
"❓ Do you wanna consider top 50 or top 100 protools?\n\n" +
"Send 50 or 100.";
const numberKeyboard = new Keyboard().text("50").text("100");
await replyWithKeyboard(ctx, question, numberKeyboard);
let firstN, topN, mcap;
[ctx, firstN] = await getNumberOrCancel(
(number) => number == 50 || number == 100,
conversation,
ctx,
question,
numberKeyboard
);
if (firstN) {
const question =
"❓ How many protocols do you want in the chart?\n\n" +
"Send a number between 10 and 50.";
const numberKeyboard = new Keyboard()
.text("10")
.text("15")
.text("20")
.row()
.text("25")
.text("30")
.text("35")
.row()
.text("40")
.text("45")
.text("50");
await replyWithKeyboard(ctx, question, numberKeyboard);
[ctx, topN] = await getNumberOrCancel(
(number) => number >= 10 && number <= 50,
conversation,
ctx,
question,
numberKeyboard
);
if (topN) {
const question =
"❓ Do you wanna consider Mcap or FDV?\n\n" +
"Send 1 for Mcap, 2 for FDV.";
const numberKeyboard = new Keyboard().text("1 - Mcap").text("2 - FDV");
await replyWithKeyboard(ctx, question, numberKeyboard);
[ctx, mcap] = await getNumberOrCancel(
(number) => number == 1 || number == 2,
conversation,
ctx,
question,
numberKeyboard
);
if (mcap) {
mcap == 1 ? (mcap = true) : (mcap = false);
await ctx.reply("🖌️ Drawing your nice chart...");
let buffer = await getBestRatioChart(firstN, topN, mcap);
await ctx.replyWithPhoto(new InputFile(buffer));
addCommandToHistory(ctx, "/getRatioChart", [firstN, topN, mcap]);
}
}
}
await ctx.reply("That's it! Press /menu to do something else");
return;
}
async function sendTip(ctx) {
let id = ctx.from.id;
const invoice = {
chat_id: id,
title: "Nice tip for a nice bot",
description: "Send a tip if you enjoyed using this bot 😊",
provider_token: process.env.PAYMENT_TOKEN,
start_parameter: "get_access",
currency: "EUR",
prices: [{ label: "1", amount: 1 * 100 }],
payload: {
unique_id: `${id}_${Number(new Date())}`,
provider_token: process.env.PAYMENT_TOKEN,
},
max_tip_amount: 10000 * 100,
suggested_tip_amounts: [4 * 100, 9 * 100, 24 * 100, 49 * 100],
};
await bot.api.raw.sendInvoice(invoice);
}
bot.on("pre_checkout_query", (ctx) => ctx.answerPreCheckoutQuery(true));
bot.on(":successful_payment", async (ctx) => {
await ctx.reply(
`Thanks a lot for the tip! Hope you'll continue to have fun with the bot!`
);
});
bot.catch((err) => {
console.error(err);
err.ctx.reply(
"UPSY DAISY, something went wrong! Try pressing /menu or /cancel."
);
});
run(bot);