forked from clemensgg/ion-statbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
703 lines (677 loc) · 26.8 KB
/
app.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
// whitelist bot to receive all tg update types
// https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates?allowed_updates=["update_id","message","edited_message","channel_post","edited_channel_post","inline_query","chosen_inline_result","callback_query","shipping_query","pre_checkout_query","poll","poll_answer","my_chat_member","chat_member"]
// init config, cache, errors, helperfunctions
import config from './config.js'
import { cacheGet, cacheSet } from './src/cache.js';
import { throwError } from './src/errors.js';
import { isAdmin, isChartParam, isActiveCommand, isAssetCommand, isMe, keyboardGlobalbanYesNo } from './src/helperfunctions.js';
// init updater
import { intervalCacheData } from './src/update.js';
// init telegram bot
import { bot, tgOptions } from './src/bot.js';
// init textGenerator
import {
generateBotCommandAnswer,
generateAssetCommandAnswer,
generateSupportCommandAnswer,
generateBlacklistAnswer
} from './src/text_generator.js';
// init gobal blacklist
import {
checkBlacklist,
newGlobalBan,
newGlobalUnban,
blacklistSaveNewChat,
blacklistCounter,
blacklistRemoveChat
} from './src/blacklist.js';
// init joincontrol
import {
joincontrolActive,
authA,
authB,
solveAuth
} from './src/joincontrol.js';
var users = [];
// init autodelete message watchdog
import { watchdogAutodelete } from './src/watchdog_autodelete.js';
import { watchdogBlacklist } from './src/watchdog_blacklist.js';
// init chartbuilder
import { generateChart } from './src/chart_generator.js';
import { fetchImperator } from './src/clients.js';
// init chart types & timeframes
const tf = {
"5m": {
"value": 5
},
"15m": {
"value": 15
},
"30m": {
"value": 30
},
"1h": {
"value": 60
},
"2h": {
"value": 120
},
"4h": {
"value": 240
},
"12h": {
"value": 720
},
"1d": {
"value": 1440
},
"1w": {
"value": 10080
},
"1M": {
"value": 43800
}
}
const chartTypes = [
'price', 'p',
'volume', 'v',
'liquidity', 'l',
]
// respond to all the chat member updates...
bot.on('chat_member', async (msg) => {
if (msg.hasOwnProperty('new_chat_members')) {
msg.new_chat_members.forEach(async (newMember) => {
let botNewChat = await isMe(newMember);
if (botNewChat) {
await blacklistSaveNewChat(msg);
}
else {
if (joincontrolActive(msg)) {
enterAuthA(msg, newMember);
}
}
});
}
else {
if (msg.hasOwnProperty('new_chat_member')) {
if (msg.new_chat_member.status == 'member') {
let botNewChat = await isMe(msg.new_chat_member.user);
if (botNewChat) {
await blacklistSaveNewChat(msg);
}
else {
if (joincontrolActive(msg)) {
enterAuthA(msg, msg.new_chat_member.user);
}
}
}
if (msg.new_chat_member.status == 'left' || msg.new_chat_member.status == 'kicked') {
let botLeftChat = await isMe(msg.new_chat_member.user);
if (botLeftChat) {
await blacklistRemoveChat(msg);
}
await userExit(msg, msg.new_chat_member.user);
}
}
}
return;
})
// respond to all messages
bot.on('message', async (msg) => {
if (msg.chat.type == 'private') {
if (msg.hasOwnProperty('forward_from')) {
let adm = await isAdmin(msg.from.id, config.blacklistSourceChat);
if (adm) {
let text = 'global_ban <a href="tg://user?id=' + msg.forward_from.id + '">' + msg.forward_from.id + '</a>?';
tgOptions.reply_to_message_id = msg.message_id;
let keyboard = keyboardGlobalbanYesNo(msg.from.id, msg.forward_from);
tgOptions.reply_markup = keyboard;
await bot.sendMessage(msg.from.id, text, tgOptions);
delete tgOptions.reply_to_message_id;
delete tgOptions.reply_markup;
return;
}
}
}
if (msg.hasOwnProperty('left_chat_member')) {
let botLeftChat = await isMe(msg.left_chat_member);
if (botLeftChat) {
await blacklistRemoveChat(msg);
}
if (joincontrolActive(msg)) {
try {
await bot.deleteMessage(msg.chat.id, msg.message_id);
}
catch (e) {
throwError(e);
}
return;
}
}
if (msg.hasOwnProperty('new_chat_member')) {
let botNewChat = await isMe(msg.new_chat_member);
if (botNewChat) {
await blacklistSaveNewChat(msg);
return;
}
else {
if (joincontrolActive(msg)) {
try {
await bot.deleteMessage(msg.chat.id, msg.message_id);
}
catch (e) {
throwError(e);
}
}
}
}
if (!msg.hasOwnProperty('entities')) {
// Joincontrol authstep B
users.forEach(async (user) => {
if (user.id == msg.from.id && user.chatid == msg.chat.id) {
try {
await bot.deleteMessage(msg.chat.id, msg.message_id);
}
catch (e) {
throwError(e);
}
// solved auth A (delete captcha)
if (msg.text == user.res) {
try {
await bot.deleteMessage(msg.chat.id, user.msgid);
}
catch (e) {
throwError(e);
}
user.auth++;
user = await authB(msg, user);
}
// delete wrong answer or any other message from newUser
else {
try {
await bot.deleteMessage(msg.chat.id, msg.message_id);
}
catch (e) {
throwError(e);
}
}
}
});
}
// respond to botcommands
else if (msg.hasOwnProperty('entities')) {
tgOptions.reply_to_message_id = msg.message_id;
msg.text = msg.text.toLowerCase();
if (msg.entities[0].type == 'bot_command' && msg.text.slice(0, 1) == '/') {
if (msg.text.includes('@')) {
msg.text = msg.text.split('@')[0];
}
let text = "";
let answer = null;
let isActCmd = await isActiveCommand(msg.text);
if (isActCmd) {
let osmoData = await cacheGet('osmosis');
let stakingData = await cacheGet('staking');
if (osmoData && stakingData) {
text = generateBotCommandAnswer(msg, osmoData, stakingData);
}
else text = '<i>database not synced, please try again in a few minutes..</i>';
answer = await bot.sendMessage(msg.chat.id, text, tgOptions);
}
let isAssCmd = await isAssetCommand(msg.text.toLowerCase())
if (isAssCmd) {
let osmoData = await cacheGet('osmosis');
if (osmoData) {
text = generateAssetCommandAnswer(msg, osmoData);
}
else text = '<i>database not synced, please try again in a few minutes..</i>';
answer = await bot.sendMessage(msg.chat.id, text, tgOptions);
}
// entrypoint charts
if (msg.text.slice(0, 6).toLowerCase() == '/chart') {
let text = "";
let pic = null;
let command = msg.text.split(' ')
let valid = false;
let err = false;
if (command.length >= 3) {
let type = command[1].toLowerCase();
let symbol = command[2].toLowerCase();
if (chartTypes.indexOf(type) > -1) {
if (await isChartParam(symbol)) {
if (symbol.includes('_')) {
symbol = symbol.replace('_', '.')
}
await bot.sendChatAction(msg.chat.id, 'typing');
if (type == 'price' || type == 'p') {
if (command.length >= 4) {
let tfval = 0;
let timeframe = command[3];
if (Object.keys(tf).indexOf(timeframe) > -1) {
tfval = tf[timeframe].value;
if (symbol != 'overview' && symbol != 'o' && symbol != 'osmosis') {
let data = await fetchImperator('tokens/historical/chart', { "symbol": symbol, "timeframe": tfval });
if (data) {
pic = await generateChart(data, type, symbol);
if (pic) {
valid = true;
}
else err = true;
}
else err = true;
}
else {
let data = await fetchImperator('tokens/historical/chart', { "symbol": 'osmo', "timeframe": tfval });
if (data) {
pic = await generateChart(data, type, symbol);
if (pic) {
valid = true;
}
else err = true;
}
else err = true;
}
}
else {
let tfs = Object.keys(tf);
let allTfs = ""
tfs.forEach((timeframe) => {
allTfs = allTfs + timeframe + ', ';
});
allTfs = allTfs.slice(0, -2);
text = "don't know timeframe: " + command[3] + "\n\nAvailable timeframes:\n<code>" + allTfs + '</code>\n\nuse "/chart type symbol timeframe"';
}
}
else {
text = 'wrong number of arguments.\n\nuse "/chart type symbol timeframe"';
}
}
if (type == 'liquidity' || type == 'l') {
if (symbol != 'overview' && symbol != 'o' && symbol != 'osmosis') {
let data = await fetchImperator('tokens/liquidity/chart', { "symbol": symbol });
if (data) {
pic = await generateChart(data, type, symbol);
if (pic) {
valid = true;
}
else err = true;
}
else err = true;
}
else {
let data = await fetchImperator('liquidity/historical/chart', { "symbol": symbol });
if (data) {
pic = await generateChart(data, type, symbol);
if (pic) {
valid = true;
}
else err = true;
}
else err = true;
}
}
else if (type == 'volume' || type == 'v') {
if (symbol != 'overview' && symbol != 'o' && symbol != 'osmosis') {
let data = await fetchImperator('tokens/volume/chart', { "symbol": symbol });
if (data) {
pic = await generateChart(data, type, symbol);
if (pic) {
valid = true;
}
else err = true;
}
else err = true;
}
else {
let data = await fetchImperator('volume/historical/chart', { "symbol": symbol });
if (data) {
pic = await generateChart(data, type, symbol);
if (pic) {
valid = true;
}
else err = true;
}
else err = true;
}
}
}
else {
let assetcommands = await cacheGet('assetcommands');
let allSymbols = "";
if (assetcommands) {
assetcommands.forEach((asset) => {
allSymbols = allSymbols + asset.replace('/', '') + ', ';
});
allSymbols = allSymbols.slice(0, -2);
text = "cannot find symbol: " + command[2] + "\n\nAvailable symbols:\n<code>" + allSymbols + '</code>\n\nuse "/chart type symbol timeframe"';
}
else {
text = '<i>database not synced, please try again in a few minutes..</i>';
}
}
}
else {
let allChartTypes = "";
chartTypes.forEach((type) => {
allChartTypes = allChartTypes + type + ', ';
});
allChartTypes = allChartTypes.slice(0, -2);
text = "don't know chart type: " + command[1] + "\n\nAvailable chart types:\n<code>" + allChartTypes + '</code>\n\nuse "/chart type symbol timeframe"';
}
}
else {
text = 'wrong number of arguments.\n\nuse "/chart type symbol timeframe"';
}
if (err) {
text = '<i>there was an error loading the chart data, please try again later</i>';
}
if (valid) {
answer = await bot.sendPhoto(msg.chat.id, pic, tgOptions);
}
else {
answer = await bot.sendMessage(msg.chat.id, text, tgOptions);
}
}
// mark for autodelete if public group
if (answer) {
if (msg.chat.type != 'private') {
let del = await cacheGet('del');
if (!del) {
del = [];
}
del.push(new Date().getTime() + "_" + msg.chat.id + "_" + answer.message_id + "_" + msg.message_id)
await cacheSet('del', del);
}
}
}
if (tgOptions.hasOwnProperty('reply_to_message_id')) {
delete tgOptions.reply_to_message_id;
}
}
return;
});
// Joincontrol solve Auth & globalban admin callback entrypoint
bot.on('callback_query', async (cb) => {
if (cb.message.chat.type == 'private') {
let adm = await isAdmin(cb.from.id, config.blacklistSourceChat);
if (adm) {
let cbdata = cb.data.split('_');
let user = {
id: parseInt(cbdata[2]),
username: cbdata[3],
first_name: cbdata[4],
last_name: cbdata[5],
}
if (cbdata[0] == 'bany') {
if (parseInt(cbdata[1]) == cb.from.id) {
let msg = {
reply_to_message: {
from: user
},
from: {
id: cb.from.id
},
chat: {
id: 'priv'
}
}
await newGlobalBan(msg);
let text = 'global_banned <a href="tg://user?id=' + msg.reply_to_message.from.id + '">' + msg.reply_to_message.from.id + '</a>\n\nuser will be removed from all administrated groups within 1min!';
await bot.sendMessage(cb.message.chat.id, text, tgOptions);
try {
await bot.deleteMessage(cb.message.chat.id, cb.message.message_id);
}
catch (e) {
throwError(e);
}
}
}
if (cbdata[0] == 'bann') {
if (parseInt(cbdata[1]) == cb.from.id) {
try {
await bot.deleteMessage(cb.message.chat.id, cb.message.message_id);
}
catch (e) {
throwError(e);
}
}
}
}
}
else {
if (cb.data.split('_')[1] == cb.from.id) {
await solveAuth(cb, users);
}
}
return;
});
// ban user and add to global blacklist
bot.onText(/\!globalban/, async (msg) => {
if (msg.hasOwnProperty('reply_to_message')) {
let text = "";
if (config.blacklistSourceChat == msg.chat.id) {
let adm = await isAdmin(msg.from.id, msg.chat.id);
let userToBlacklistIsAdmin = await isAdmin(msg.reply_to_message.from.id, msg.chat.id);
if (!userToBlacklistIsAdmin) {
if (adm) {
await newGlobalBan(msg);
// ban and delete all messages by user from this group
let banned = await bot.banChatMember(msg.chat.id, msg.reply_to_message.from.id, 0, true);
if (banned) {
tgOptions.reply_to_message_id = msg.message_id;
text = 'global_banned <a href="tg://user?id=' + msg.reply_to_message.from.id + '">' + msg.reply_to_message.from.id + '</a>';
}
else text = 'there was a problem trying to ban user <a href="tg://user?id=' + msg.reply_to_message.from.id + '">' + msg.reply_to_message.from.id + '</a>'
}
else {
text = "<i>admin only!</i>";
}
}
else {
text = "<i>cannot restrict other admins!</i>";
}
}
else {
text = "<i>the global ban function is an attempt to conquer scammers and can only be triggered by osmosis admins in the osmosis main group</i>";
}
await bot.sendMessage(msg.chat.id, text, tgOptions);
}
if (tgOptions.hasOwnProperty('reply_to_message_id')) {
delete tgOptions.reply_to_message_id;
}
return;
});
// blacklist backend (osmo admins only)
bot.onText(/\!blacklist|!unban/, async (msg) => {
if (msg.chat.type == 'private') {
let adm = await isAdmin(msg.from.id, config.blacklistSourceChat);
if (adm) {
let text = "";
tgOptions.reply_to_message_id = msg.message_id;
if (msg.text == '!blacklist') {
text = await generateBlacklistAnswer();
}
if (msg.text.includes('!unban')) {
if (msg.text.includes(' ')) {
let userid = msg.text.split(' ')[1];
let unbanned = await newGlobalUnban(userid);
if (unbanned) {
text = 'success! unbanned <a href="tg://user?id=' + userid + '">' + userid + '</a> from all chats.\n\nblacklist updated.';
}
else {
text = `sorry, can't find user ${userid} on the global blacklist or there was another error`;
}
}
else {
text = 'no user_id specified. please use <code>"!unban $id"</code>';
}
}
await bot.sendMessage(msg.chat.id, text, tgOptions);
}
if (tgOptions.hasOwnProperty('reply_to_message_id')) {
delete tgOptions.reply_to_message_id;
}
}
return;
});
// supportcommands (admin only)
bot.onText(/\#/, async (msg) => {
let res = {
"text": "",
"pic": "",
"tgOptions": {
"disable_web_page_preview": true,
"parse_mode": "HTML"
}
}
if (msg.hasOwnProperty('entities') && config.supportCommandsActive) {
if (msg.entities[0].type == 'hashtag') {
msg.text = '#' + msg.text.split('#')[1];
if (msg.text.includes(' ')) {
msg.text = msg.text.split(' ')[0];
}
let supportCommands = await cacheGet("sp");
if (supportCommands) {
let cmds = [];
supportCommands.forEach((command) => {
cmds.push(command.command);
});
if (cmds.indexOf(msg.text.toLowerCase()) > -1) {
if (msg.chat.type != 'private') {
res.text = "<i>tutorial commands are restricted to admins</i>";
let adm = await isAdmin(msg.from.id, msg.chat.id);
if (adm) {
res = await generateSupportCommandAnswer(msg, supportCommands);
}
}
else {
res = await generateSupportCommandAnswer(msg, supportCommands);
}
res.tgOptions.reply_to_message_id = msg.message_id;
if (res.pic) {
await bot.sendPhoto(msg.chat.id, res.pic, res.tgOptions);
}
else {
if (res.text) {
await bot.sendMessage(msg.chat.id, res.text, res.tgOptions);
}
}
}
}
}
}
return;
});
// log polling errors
bot.on('polling_error', (e) => {
throwError(e);
return;
});
//// userExit must be in main scope
async function userExit(msg, user) {
users.forEach(async (cacheduser, index, arr) => {
if (cacheduser.id == user.id) {
if (cacheduser.hasOwnProperty('msgid')) {
try {
await bot.deleteMessage(cacheduser.chatid, cacheduser.msgid);
}
catch (e) {
throwError(e);
}
}
if (user.hasOwnProperty('sticker')) {
try {
await bot.deleteMessage(cacheduser.chatid, cacheduser.sticker);
}
catch (e) {
throwError(e);
}
}
arr.splice(index, 1);
}
});
console.log('> user exited ID: ' + user.id + ', chat: ' + msg.chat.id);
return true;
}
// authA must be in main scope
async function enterAuthA(msg, newMember) {
// Joincontrol authstep A
if (msg.hasOwnProperty('message_id')) {
try {
await bot.deleteMessage(msg.chat.id, msg.message_id);
}
catch (e) {
throwError(e);
}
}
// compare golbal blacklist & ban
let blacklisted = await checkBlacklist(newMember.id);
if (blacklisted) {
await bot.banChatMember(msg.chat.id, newMember.id);
await blacklistCounter(msg.chat.id, 'inc');
}
else {
let user = await authA(newMember, msg.chat.id);
users.push(user);
}
return true;
}
// watchdog Joincontrol must be in main scope
async function watchdogJoincontrol() {
if (!users) {
return;
}
users.forEach(async (user, index, arr) => {
if ((((new Date().getTime() - new Date(user.joinTime).getTime()) / 1000) >= config.joinControl.timeout)) {
if (user.hasOwnProperty('msgid')) {
try {
await bot.deleteMessage(user.chatid, user.msgid);
}
catch (e) {
throwError(e);
}
}
if (user.hasOwnProperty('sticker')) {
try {
await bot.deleteMessage(user.chatid, user.sticker);
}
catch (e) {
throwError(e);
}
}
try {
await bot.banChatMember(user.chatid, user.id);
}
catch (e) {
throwError(e);
}
try {
await bot.unbanChatMember(user.chatid, user.id);
}
catch (e) {
throwError(e);
}
console.log('> kicked user ' + user.id + ' from chat ' + user.chatid + ' (timeout ' + config.joinControl.timeout + ')');
arr.splice(index, 1);
}
});
return;
}
async function main() {
let initBot = await bot.getMe();
if (initBot) {
await cacheSet('bot', initBot);
console.log(initBot);
setInterval(watchdogAutodelete, 20000);
setInterval(watchdogJoincontrol, 20000);
setInterval(watchdogBlacklist, 20000);
watchdogAutodelete();
watchdogJoincontrol();
watchdogBlacklist(),
setInterval(intervalCacheData, config.pollInterval * 1000);
intervalCacheData();
return;
}
return
}
main();