-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
438 lines (393 loc) · 13.8 KB
/
server.js
File metadata and controls
438 lines (393 loc) · 13.8 KB
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
const _ = require('lodash');
const Telegraf = require('telegraf');
const sharp = require('sharp');
const captcha = require('svg-captcha');
const md5 = require('md5');
const dayjs = require('dayjs');
const Markup = require('telegraf/markup');
const genfun = require('generate-function');
const telegrafCommandParts = require('telegraf-command-parts');
const redis = require('./redis');
const { d } = genfun.formats;
const bot = new Telegraf(process.env.BOT_TOKEN);
const cache = {};
const DELAYED_SECONDS = 180;
const handleDeleteMessage = (message) => {
const chatId = _.get(message, 'chat.id');
const messageId = _.get(message, 'message_id');
const key = `${chatId}:${messageId}`;
if (cache[key]) {
clearTimeout(cache[key]);
}
cache[key] = setTimeout(
async (chatMessage) => {
await bot.telegram.deleteMessage(
..._
.chain(chatMessage)
.pick(['chat.id', 'message_id'])
.values()
.value(),
);
},
30000,
message,
);
};
bot
.use(telegrafCommandParts())
.on('new_chat_members', async (ctx) => {
const newChatMember = _.get(ctx, 'message.new_chat_member');
const newChatMemberId = _.get(newChatMember, 'id');
const firstName = _.get(newChatMember, 'first_name', '');
const lastName = _.get(newChatMember, 'last_name', '');
const userId = _.get(ctx, 'from.id');
const chatId = _.get(ctx, 'chat.id');
const title = _.get(ctx, 'chat.title');
const name = `${firstName} ${lastName}`.trim();
if (userId === newChatMemberId) {
await ctx.telegram.callApi(
'restrictChatMember',
{
chat_id: chatId,
user_id: newChatMemberId,
permissions: {
can_send_messages: false,
can_send_media_messages: false,
can_send_polls: false,
can_send_other_messages: false,
can_add_web_page_previews: false,
can_change_info: false,
can_invite_users: false,
can_pin_messages: false,
},
},
);
const formula = (
[
numberA,
operatorA,
numberB,
operatorB,
numberC,
],
) => {
const gen = genfun();
gen(`
function () {
return ${d(numberA)} ${operatorA} ${d(numberB)} ${operatorB} ${d(numberC)};
}
`);
return gen.toFunction();
};
const calculateTotalCache = [];
const questions = Array(3)
.fill()
.map(() => {
const getRandomNumber = () => {
const randomNumber = Array(5)
.fill()
.reduce((current, value, index) => {
const operators = ['+', '-', '*'];
if (index % 2 === 0) {
current.push(_.random(0, 99));
} else {
current.push(operators[_.random(0, operators.length - 1)]);
}
return current;
}, []);
const total = formula(randomNumber)();
if (calculateTotalCache.includes(total)) {
return getRandomNumber();
}
calculateTotalCache.push(total);
return {
total,
formula: randomNumber,
};
};
const hash = md5(`${dayjs().valueOf()}${_.random(0, 100)}`);
return {
hash,
randomNumber: getRandomNumber(),
};
});
const answer = questions[_.random(0, questions.length - 1)];
const messages = await redis.smembers(`app:tg-captcha:chat:${chatId}:user:${newChatMemberId}:messages`);
await Promise.all(
[
redis.setex(`app:tg-captcha:chat:${chatId}:user:${newChatMemberId}`, DELAYED_SECONDS, answer.hash),
...messages
.map(
(message) => ctx
.deleteMessage(message)
.catch(console.log),
),
],
);
const image = Buffer.from(captcha(answer.randomNumber.formula.join(' ')));
const replyPhoto = await ctx.replyWithPhoto(
{
source: await sharp(image)
.flatten({ background: '#ffffff' })
.resize(800)
.toFormat('jpg')
.toBuffer(),
},
{
reply_markup: {
inline_keyboard: [
questions.map(
(question) => {
const button = Markup.callbackButton(question.randomNumber.total, `question|${answer.hash}`);
return button;
},
),
[
Markup.urlButton('💗 捐款給牧羊犬 💗', 'http://bit.ly/31POewi'),
],
[
Markup.callbackButton('💢 這個是spam 💢', `kick|${userId}`),
],
],
},
caption: `👏 歡迎新使用者${name}加入${title},請在${DELAYED_SECONDS}秒內回答圖片的問題,否則牧羊犬會把你吃了喔`,
reply_to_message_id: ctx.message.message_id,
},
);
await redis.setex(`app:tg-captcha:chat:${chatId}:message:${replyPhoto.message_id}`, DELAYED_SECONDS, userId);
setTimeout(
(context) => async () => {
const requestUserId = _.get(context, 'message.new_chat_member.id');
const requestChatId = _.get(context, 'chat.id');
const hash = await redis.get(`app:tg-captcha:chat:${requestChatId}:user:${requestUserId}`);
if (hash) {
await Promise.all(
[
context.kickChatMember(requestUserId).catch(console.log),
context.reply(`❌ 因為超過${DELAYED_SECONDS}秒回答,所以牧羊犬把你吃掉了`),
redis.del(`app:tg-captcha:chat:${requestChatId}:user:${requestUserId}`),
],
);
}
},
DELAYED_SECONDS * 1000,
ctx,
);
}
})
.action(/question\|.+/, async (ctx) => {
const userId = _.get(ctx, 'from.id');
const chatId = _.get(ctx, 'chat.id');
const callback = _.get(ctx, 'update.callback_query.message');
const messageId = _.get(callback, 'message_id');
const inlineButton = _.get(ctx, 'match.0', '');
const [, inlineAnswer] = inlineButton.split('|');
const storedChallengeId = await redis.get(`app:tg-captcha:chat:${chatId}:message:${messageId}`);
const replyMessage = _.get(callback, 'reply_to_message');
const challengeId = _.get(replyMessage, 'new_chat_member.id', _.toNumber(storedChallengeId));
const challengeKey = `app:tg-captcha:chat:${ctx.chat.id}:user:${userId}`;
const answerKey = `app:tg-captcha:chat:${chatId}:user:${userId}`;
const captchaAnswer = await redis.get(challengeKey);
if (userId !== challengeId) {
await ctx.answerCbQuery('這不是你的按鈕,請不要亂點 😠');
} else if (captchaAnswer === inlineAnswer) {
await Promise.all(
[
redis.del(challengeKey),
redis.del(answerKey),
ctx.deleteMessage(messageId).catch(console.log),
ctx.reply(
'⭕️ 恭喜回答正確,牧羊犬歡迎你的加入~',
{
reply_markup: {
inline_keyboard: [
[
Markup.callbackButton('💢 這個是spam 💢', `kick|${userId}}`),
],
],
},
reply_to_message_id: ctx.reply_to_message.message_id,
},
).then(handleDeleteMessage),
ctx.telegram.callApi(
'restrictChatMember',
{
chat_id: chatId,
user_id: userId,
permissions: {
can_send_messages: true,
can_send_media_messages: true,
can_send_polls: true,
can_send_other_messages: true,
can_add_web_page_previews: true,
can_change_info: true,
can_invite_users: true,
can_pin_messages: true,
},
},
),
],
);
} else {
await Promise.all(
[
redis.del(challengeKey),
redis.del(answerKey),
ctx.deleteMessage(messageId).catch(console.log),
ctx.reply(
'❌ 回答失敗,所以牧羊犬把你吃掉了',
{
reply_markup: {
inline_keyboard: [
[
Markup.callbackButton('🥺 不小心誤殺了 🥺', `unban|${userId}`),
],
],
},
reply_to_message_id: ctx.reply_to_message.message_id,
},
).then(handleDeleteMessage),
ctx.kickChatMember(userId),
],
);
}
})
.command('admin', async (ctx) => {
const group = _.get(ctx, 'state.command.splitArgs.0', ctx.chat.id);
const admins = await ctx.telegram.getChatAdministrators(group);
const groupAdmins = admins
.filter((admin) => !admin.user.is_bot)
.map((admin) => {
if (admin.user.username) {
return `@${admin.user.username}`;
}
return `[${admin.user.first_name} ${admin.user.last_name}](tg://user?id=${admin.user.id})`;
});
await ctx.replyWithMarkdown(groupAdmins.join('\n'));
})
.command('about', async (ctx) => {
await ctx.reply(`牧羊犬是一個免費的防spam的bot,本身沒有任何贊助以及金援,全部的成本都是由開發者自行吸收。
從一開始的百人小群起家,到現在活躍在140個以上的群組,都感謝有各位的支持才能到現在。
但是,現在由於主機價格上漲,機器人的負擔也越來越加重,甚至未來可能會出現一年250 - 260美金以上的帳單... 作為業餘項目來說,這已經是個不小的負擔。
如果你希望牧羊犬能走的更久,可以的話請多多支持我能再把機器開下去,感謝 🙏
歡迎樂捐,所有捐款人會在這裡留下您的名字
贊助名單:
@Lunamiou 🐑
@tfnight 二十四夜
Chung Wu`);
})
.on('message', async (ctx, next) => {
const userId = _.get(ctx, 'message.from.id');
const text = _.get(ctx, 'message.text');
const messageId = _.get(ctx, 'message.message_id');
const chatId = _.get(ctx, 'chat.id');
if (text) {
const key = `app:tg-captcha:chat:${chatId}:user:${userId}:messages`;
await redis
.pipeline()
.sadd(key, messageId)
.expire(key, 60)
.exec();
}
await next();
})
.on('message', async (ctx, next) => {
const admins = await ctx.getChatAdministrators();
const adminId = _.map(admins, 'user.id');
if (adminId.includes(ctx.from.id)) {
await next();
}
})
.command('ban', async (ctx) => {
const muteMinutes = _.get(ctx, 'state.command.splitArgs.0', 0);
const userId = _.get(ctx, 'message.reply_to_message.from.id');
const minutes = _.toInteger(muteMinutes);
if (userId) {
const firstName = _.get(ctx, 'message.reply_to_message.from.first_name', '');
const lastName = _.get(ctx, 'message.reply_to_message.from.last_name', '');
await Promise.all(
[
ctx.kickChatMember(userId, Math.round(dayjs().add(minutes, 'minute').valueOf() / 1000)),
ctx.reply(
`已經將${firstName} ${lastName}${minutes === 0 ? '封鎖' : `封鎖${minutes}分鐘`}`,
{
reply_to_message_id: ctx.message.reply_to_message.message_id,
},
),
],
);
} else {
await ctx.reply(
'請利用回覆的方式指定要封鎖的人',
{
reply_to_message_id: ctx.message.reply_to_message.message_id,
},
);
}
})
.command('mute', async (ctx) => {
const muteMinutes = _.get(ctx, 'state.command.splitArgs.0', 5);
const userId = _.get(ctx, 'message.reply_to_message.from.id');
const minutes = _.toInteger(muteMinutes);
if (userId) {
const firstName = _.get(ctx, 'message.reply_to_message.from.first_name', '');
const lastName = _.get(ctx, 'message.reply_to_message.from.last_name', '');
await Promise.all(
[
ctx.telegram.callApi(
'restrictChatMember',
{
chat_id: ctx.chat.id,
user_id: userId,
permissions: {
can_send_messages: false,
can_send_media_messages: false,
can_send_polls: false,
can_send_other_messages: false,
can_add_web_page_previews: false,
can_change_info: false,
can_invite_users: false,
can_pin_messages: false,
},
until_date: Math.round(dayjs().add(minutes, 'minute').valueOf() / 1000),
},
),
ctx.reply(
`已經將${firstName} ${lastName}${minutes === 0 ? '禁言' : `禁言${minutes}分鐘`}`,
{
reply_to_message_id: ctx.message.reply_to_message.message_id,
},
),
],
);
} else {
await ctx.reply(
'請利用回覆的方式指定要禁言的人',
{
reply_to_message_id: ctx.message.reply_to_message.message_id,
},
);
}
})
.action(/unban\|.+/, async (ctx) => {
const inlineButton = _.get(ctx, 'match.0', '');
const [, userId] = inlineButton.split('|');
await Promise.all(
[
ctx.editMessageText('牧羊犬已經解除他的封鎖了喔 🐶').then(handleDeleteMessage),
ctx.unbanChatMember(userId),
],
);
})
.action(/kick\|.+/, async (ctx) => {
const inlineButton = _.get(ctx, 'match.0', '');
const [, userId] = inlineButton.split('|');
await Promise.all(
[
ctx.editMessageText('牧羊犬已經把他趕走了哦 🐶').then(handleDeleteMessage),
ctx.kickChatMember(userId),
],
);
})
.catch(console.log)
.launch();