forked from LyoSU/quote-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.js
519 lines (453 loc) Β· 13.1 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
const fs = require('fs')
const path = require('path')
const Telegraf = require('telegraf')
const Composer = require('telegraf/composer')
const session = require('telegraf/session')
const rateLimit = require('telegraf-ratelimit')
const I18n = require('telegraf-i18n')
const io = require('@pm2/io')
const { db } = require('./database')
const { stats, onlyGroup, onlyAdmin } = require('./middlewares')
const {
handleHelp,
handleAdv,
handleModerateAdv,
handleQuote,
handleGetQuote,
handleTopQuote,
handleRandomQuote,
handleColorQuote,
handleEmojiBrandQuote,
handleSettingsHidden,
handleGabSettings,
handleSave,
handleDelete,
handleRate,
handleEmoji,
handleSettingsRate,
handlePrivacy,
handleLanguage,
handleFstik,
handleSticker,
handleDonate,
handlePing,
handleChatMember,
handleInlineQuery,
handleDeleteRandom
} = require('./handlers')
const { getUser, getGroup } = require('./helpers')
const rpsIO = io.meter({
name: 'req/sec',
unit: 'update'
})
const messageCountIO = io.meter({
name: 'message count',
unit: 'message'
})
const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
const bot = new Telegraf(process.env.BOT_TOKEN, {
telegram: { webhookReply: false },
handlerTimeout: 1
});
(async () => {
console.log(await bot.telegram.getMe())
})()
bot.use((ctx, next) => {
const timeoutPromise = new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('timeout'))
}, 100)
})
const nextPromise = next()
return Promise.race([timeoutPromise, nextPromise])
.catch((error) => {
if (error.message === 'timeout') {
return false
}
console.log('Oops', error)
if (
ctx?.chat?.type === 'private'
|| (ctx.state.emptyRequest === false && ctx?.message?.entities?.[0].type === 'bot_command')
) {
ctx.replyWithHTML('Oops, something went wrong!', {
reply_to_message_id: ctx?.message?.message_id,
allow_sending_without_reply: true
})
}
return true
})
})
// bot.use(require('./middlewares/metrics'))
bot.use(stats)
bot.use((ctx, next) => {
const config = JSON.parse(fs.readFileSync('./config.json', 'utf8'))
ctx.config = config
ctx.db = db
return next()
})
bot.use((ctx, next) => {
rpsIO.mark()
ctx.telegram.oCallApi = ctx.telegram.callApi
ctx.telegram.callApi = (method, data = {}) => {
// console.log(`send method ${method}`)
const startMs = new Date()
return ctx.telegram.oCallApi(method, data).then((result) => {
console.log(`end method ${method}:`, new Date() - startMs)
return result
})
}
// if (ctx.update.message) {
// const dif = Math.round(new Date().getTime() / 1000) - ctx.update.message.date
// if (dif > 2) console.log('π¨ delay ', dif)
// }
return next()
})
bot.command('json', ({ replyWithHTML, message }) =>
replyWithHTML('<code>' + JSON.stringify(message, null, 2) + '</code>')
)
bot.use(handleChatMember)
bot.use(
Composer.groupChat(
Composer.command(
rateLimit({
window: 1000 * 5,
limit: 2,
keyGenerator: (ctx) => ctx.chat.id,
onLimitExceeded: ({ deleteMessage }) => deleteMessage().catch(() => {})
})
)
)
)
bot.use(
Composer.mount(
'callback_query',
rateLimit({
window: 2000,
limit: 1,
keyGenerator: (ctx) => ctx.from.id,
onLimitExceeded: ({ answerCbQuery }) => answerCbQuery('too fast', true)
})
)
)
bot.on(['channel_post', 'edited_channel_post'], () => {})
const i18n = new I18n({
directory: path.resolve(__dirname, 'locales'),
defaultLanguage: 'en',
defaultLanguageOnMissing: true,
})
bot.use(i18n.middleware())
bot.use(
session({
getSessionKey: (ctx) => {
if (ctx.from && ctx.chat) {
return `${ctx.from.id}:${ctx.chat.id}`
} else if (ctx.from) {
return `user:${ctx.from.id}`
} else if (ctx.update?.business_message) {
return `user:${ctx.update.business_message.from.id}`
}
return null
}
})
)
bot.use(async (ctx, next) => {
ctx.state.emptyRequest = false
return next().then(() => {
if (ctx.state.emptyRequest === false) messageCountIO.mark()
})
})
bot.use(
Composer.groupChat(
session({
property: 'group',
getSessionKey: (ctx) => {
if (
ctx.from &&
ctx.chat &&
['supergroup', 'group'].includes(ctx.chat.type)
) {
return `${ctx.chat.id}`
}
return null
},
ttl: 60 * 5
})
)
)
const updateGroupAndUser = async (ctx, next) => {
await getUser(ctx)
await getGroup(ctx)
return next(ctx).then(async () => {
if (ctx.state.emptyRequest === false) {
ctx.session.userInfo.save().catch(() => {})
const memberCount = await ctx.telegram.getChatMembersCount(ctx.chat.id)
if (memberCount) ctx.group.info.memberCount = memberCount
await ctx.group.info.save().catch(() => {})
}
})
}
bot.use(async (ctx, next) => {
if (ctx.inlineQuery) {
await getUser(ctx)
ctx.state.answerIQ = []
}
if (ctx.callbackQuery) {
await getUser(ctx)
ctx.state.answerCbQuery = []
}
return next(ctx).then(() => {
if (ctx.inlineQuery) return ctx.answerInlineQuery(...ctx.state.answerIQ)
if (ctx.callbackQuery) return ctx.answerCbQuery(...ctx.state.answerCbQuery)
})
})
bot.use(Composer.groupChat(Composer.command(updateGroupAndUser)))
bot.use(
Composer.privateChat(async (ctx, next) => {
await getUser(ctx)
await next(ctx).then(() => {
ctx.session.userInfo.save().catch(() => {})
})
})
)
bot.start(async (ctx, next) => {
const arg = ctx.message.text.split(' ')
if (arg[1] && ctx.config.logChatId) {
await ctx.tg.sendMessage(
ctx.config.logChatId,
`#${arg[1]}\n<code>${JSON.stringify(ctx.message, null, 2)}</code>`,
{
parse_mode: 'HTML'
}
)
}
return next()
})
bot.hears(/\/q(.*)\*(.*)/, rateLimit({
window: 1000 * 25,
limit: 1,
keyGenerator: (ctx) => ctx.from.id,
onLimitExceeded: (ctx) => {
return ctx.replyWithHTML(ctx.i18n.t('rate_limit', {
seconds: 25
}), {
reply_to_message_id: ctx.message.message_id
}).then((msg) => {
setTimeout(() => {
ctx.deleteMessage().catch(() => {})
ctx.deleteMessage(msg.message_id).catch(() => {})
}, 5000)
})
}
}))
bot.command('donate', handleDonate)
bot.command('ping', handlePing)
bot.action(/(donate):(.*)/, handleDonate)
bot.on('pre_checkout_query', ({ answerPreCheckoutQuery }) =>
answerPreCheckoutQuery(true)
)
bot.on('successful_payment', handleDonate)
bot.hears(/\/refund (.*)/, async (ctx) => {
if (ctx.config.adminId !== ctx.from.id) return
const [_, paymentId] = ctx.match
const userId = paymentId.match(/U(\d+)/)[1]
try {
await ctx.telegram.callApi('refundStarPayment', {
user_id: userId,
telegram_payment_charge_id: paymentId
})
await ctx.replyWithHTML(`Refund success: ${userId} ${paymentId}`)
} catch (error) {
await ctx.replyWithHTML(`Refund error: ${error.description}`)
}
})
bot.command('qtop', onlyGroup, handleTopQuote)
bot.command(
'qrand',
onlyGroup,
rateLimit({
window: 1000 * 50,
limit: 2,
keyGenerator: (ctx) => {
return ctx.chat.id
},
onLimitExceeded: ({ deleteMessage }) => deleteMessage().catch(() => {})
}),
handleRandomQuote
)
// business_message
bot.use((ctx, next) => {
if (!ctx.update?.business_message) {
return next()
}
if (ctx.update.business_message.text) {
ctx.update.message = ctx.update.business_message
if (ctx.update.business_message.text.startsWith('/q')) {
ctx.update.message.text = ctx.update.business_message.text
return handleQuote(ctx, next)
}
}
return next()
})
bot.command('q', handleQuote)
bot.hears(/\/q_(.*)/, handleGetQuote)
bot.hears(/^\/qs(?:\s([^\s]+)|)/, handleFstik)
bot.hears(/^\/qs(?:\s([^\s]+)|)/, onlyGroup, onlyAdmin, handleSave)
bot.command('qd', onlyGroup, onlyAdmin, handleDelete)
bot.command('qdrand', onlyGroup, onlyAdmin, handleDeleteRandom)
bot.hears(/^\/qcolor(?:(?:\s(?:(#?))([^\s]+))?)/, onlyAdmin, handleColorQuote)
bot.command('qb', onlyAdmin, handleEmojiBrandQuote)
bot.hears(/^\/(hidden)/, onlyAdmin, handleSettingsHidden)
bot.command('qemoji', onlyAdmin, handleEmoji)
bot.hears(/^\/(qgab) (\d+)/, onlyGroup, onlyAdmin, handleGabSettings)
bot.hears(/^\/(qrate)/, onlyGroup, onlyAdmin, handleSettingsRate)
bot.action(/^(rate):(π|π)/, handleRate)
bot.action(/^(irate):(.*):(π|π)/, handleRate)
bot.on('new_chat_members', (ctx, next) => {
if (ctx.message.new_chat_member.id === ctx.botInfo.id) return handleHelp(ctx)
else return next()
})
bot.start(handleHelp)
bot.command('help', handleHelp)
bot.use(handleAdv)
bot.use(handleModerateAdv)
bot.use(handleInlineQuery)
bot.command('privacy', onlyAdmin, handlePrivacy)
bot.command('lang', handleLanguage)
bot.action(/set_language:(.*)/, handleLanguage)
bot.on('sticker', rateLimit({
window: 1000 * 60,
limit: 1,
keyGenerator: (ctx) => ctx.from.id,
onLimitExceeded: (ctx, next) => {
return next()
}
}), handleSticker)
bot.on('text', rateLimit({
window: 1000 * 60,
limit: 1,
keyGenerator: (ctx) => ctx.from.id,
onLimitExceeded: (ctx, next) => {
return next()
}
}), handleSticker)
bot.on('message', Composer.privateChat(handleQuote))
bot.on(
'message',
Composer.groupChat(
rateLimit({
window: 1000 * 5,
limit: 1,
keyGenerator: (ctx) => ctx.chat.id,
onLimitExceeded: (ctx, next) => {
ctx.state.skip = true
return next()
}
}),
async (ctx, next) => {
if (ctx.state.skip) return next()
await getGroup(ctx)
const gab = ctx.group.info.settings.randomQuoteGab
if (gab > 0) {
const random = randomIntegerInRange(1, gab)
if (
random === gab &&
ctx.group.info.lastRandomQuote.getTime() / 1000 <
Date.now() / 1000 - 60
) {
ctx.group.info.lastRandomQuote = Date()
ctx.state.randomQuote = true
return handleRandomQuote(ctx)
}
}
return next()
}
)
)
bot.use((ctx, next) => {
ctx.state.emptyRequest = true
return next()
})
db.connection.once('open', async () => {
console.log('Connected to MongoDB')
if (process.env.BOT_DOMAIN) {
bot
.launch({
webhook: {
domain: process.env.BOT_DOMAIN,
hookPath: `/QuoteBot:${process.env.BOT_TOKEN}`,
port: process.env.WEBHOOK_PORT || 2200
}
})
.then(() => {
console.log('bot start webhook')
})
} else {
await bot.launch({
polling: {
allowedUpdates: [
"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",
"chat_join_request",
"business_message"
],
}
}).then(() => {
console.log('bot start polling')
})
const locales = fs.readdirSync(path.resolve(__dirname, 'locales'));
const enDescriptionLong = i18n.t('en', 'description.long');
const enDescriptionShort = i18n.t('en', 'description.short');
for (const locale of locales) {
const localeName = locale.split('.')[0];
const myDescription = await bot.telegram.callApi('getMyDescription', {
language_code: localeName,
});
const descriptionLong = i18n.t(localeName, 'description.long');
const newDescriptionLong = localeName === 'en' || descriptionLong !== enDescriptionLong
? descriptionLong.replace(/[\r\n]/gm, '')
: '';
if (newDescriptionLong !== myDescription.description.replace(/[\r\n]/gm, '')) {
try {
const description = newDescriptionLong ? i18n.t(localeName, 'description.long') : '';
const response = await bot.telegram.callApi('setMyDescription', {
description,
language_code: localeName,
});
console.log('setMyDescription', localeName, response);
} catch (error) {
console.error('setMyDescription', localeName, error.description);
}
}
const myShortDescription = await bot.telegram.callApi('getMyShortDescription', {
language_code: localeName,
});
const descriptionShort = i18n.t(localeName, 'description.short');
const newDescriptionShort = localeName === 'en' || descriptionShort !== enDescriptionShort
? descriptionShort.replace(/[\r\n]/gm, '')
: '';
if (newDescriptionShort !== myShortDescription.short_description.replace(/[\r\n]/gm, '')) {
try {
const shortDescription = newDescriptionShort ? i18n.t(localeName, 'description.short') : '';
const response = await bot.telegram.callApi('setMyShortDescription', {
short_description: shortDescription,
language_code: localeName,
});
console.log('setMyShortDescription', localeName, response);
} catch (error) {
console.error('setMyShortDescription', localeName, error.description);
}
}
}
}
})