-
Notifications
You must be signed in to change notification settings - Fork 4
/
captcha.ts
400 lines (379 loc) · 18 KB
/
captcha.ts
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
import type { ExtendedContext } from "../typings/context";
import type { User } from "telegraf/typings/telegram-types";
import Telegraf = require("telegraf");
import HtmlUtils = require("../utils/html");
import TgUtils = require("../utils/tg");
import Log = require("../utils/log");
import UserStore = require('../stores/user');
import Files = require('fs');
let settings = {
active: true, // If True, Bot will issue Captcha Challenges for new Members.
challengeTimeout: 1800, // Time before Bot kicks the user for not answer, 30 minutes (1800 seconds) by default.
kickCooldown: 300, // Time before a kicked user can attempt to join the chat again in 5 minutes (300 seconds) by default.
strict: true, // If True, deletes all messages by unverified users that aren't answers.
maxAttempts: 3, // Max number of attempts before kicking the unverified user.
exclude: [] // List of chats to exclude from this plugin's actions.
}
// Permissions for the new user when they join the chat.
const unverifiedOptions = {
can_send_messages: true,
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
}
// Permissions for the new user after they Complete the Captcha. Check
const verifiedOptions = {
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: false,
can_invite_users: false,
can_pin_messages: false
}
// Arithmetic Captcha Question Parameters
const numbers = [0, 1, 2, 3, 4, 5];
const calc = {
"+": (a: number, b: number) => a + b,
"-": (a: number, b: number) => a - b,
//"*": (a: number, b: number) => a * b,
};
const { Composer: C } = Telegraf;
const { html } = HtmlUtils;
const { link } = TgUtils;
const { logError } = Log;
const { getAdmins } = UserStore;
const fs = Files;
const pick = <T>(list: T[]) => list[Math.floor(Math.random() * list.length)];
type Challenge = {
user: User;
chat: string;
kickTimeout: number;
math: [string, number];
messageId: number;
deleteList: number[];
attempts: number;
};
const challenge = (
challenges: Challenge[],
ctx: ExtendedContext,
x: User,
): Challenge => {
let a: number, b: number, op: keyof typeof calc, result: number;
do {
a = pick(numbers);
b = pick(numbers);
op = pick(Object.keys(calc)) as keyof typeof calc;
result = calc[op](a, b);
} while (result === 0);
const c = {
user: x,
chat: "",
kickTimeout: (setTimeout(() => {
ctx
.kickChatMember(x.id, Math.floor((Date.now() / 1000) + settings.kickCooldown))
.catch((err) => logError("[captcha] " + err.message))
.then(() => {
challenges.splice(challenges.indexOf(c), 1);
return ctx.deleteMessage(c.messageId);
})
.catch((err) => logError("[captcha] " + err.message));
}, settings.challengeTimeout * 1000) as unknown) as number,
math: [`${a} ${op} ${b}`, result] as [string, number],
messageId: 0,
deleteList: [],
attempts: settings.maxAttempts,
};
return c;
};
const activeChallenges: Challenge[] = [];
const adminList: number[] = [];
const settingsFile = "./plugins/captcha.json";
// If a settings file exists, read it and update our settings with it.
fs.access(settingsFile, fs.F_OK, (err) => {
if (err) {
logError("[captcha] " + err.message);
updateSettings();
logError("[captcha] Creating new settings file.");
return;
}
fs.readFile(settingsFile, "utf-8", (err, data) => {
if (err) {
logError("[captcha] " + err.message);
return;
}
settings = JSON.parse(data.toString());
});
});
// Update the settings file with our current settings object.
function updateSettings() {
const data = JSON.stringify(settings);
fs.writeFile(settingsFile, data, (err) => {
if (err) {
logError("[captcha] " + err.message);
return;
}
});
}
function updateExclusion(e) {
if (settings.exclude.indexOf(e) < 0) {
settings.exclude.push(e);
return 0;
} else {
settings.exclude.splice(settings.exclude.indexOf(e), 1);
return 1;
}
}
export = C.mount("message", async (ctx: ExtendedContext, next) => {
// Populate the list of Admins
if (adminList.length < 1) {
const admins = await getAdmins();
//logError(admins);
for (let i = 0; i < admins.length; i++) {
adminList.push(admins[i].id);
}
//logError(adminList);
}
//Plugin Commands
if (ctx.message?.entities?.[0].type === "bot_command") {
const text = ctx.message?.text;
const match = text.match(/^\/([^\s]+)\s?(.+)?/);
let args = [];
let command = "";
if (match !== null) {
if (match[1]) {
command = match[1];
}
if (match[2]) {
args = match[2].split(' ');
}
}
// Command arguments (/captcha).
if (command === "captcha") {
if (adminList.indexOf(ctx.from?.id) >= 0) {
if (args !== null) {
if (args[0] === "on") { // Enable Captcha (/captcha on).
settings.active = true;
updateSettings();
ctx.replyWithHTML(
html`Captcha is now On.`
);
} else if (args[0] === "off") { // Disable Captcha (/captcha off).
settings.active = false;
updateSettings();
ctx.replyWithHTML(
html`Captcha is now Off.`
);
} else if (args[0] === "timeout") { // Change challenge timeout. (/captcha timeout <integer bigger or equal to 300>).
if (parseInt(args[1]) >= 300) {
settings.challengeTimeout = parseInt(args[1]);
updateSettings();
ctx.replyWithHTML(
html`Captcha cooldown kick time is now ${settings.challengeTimeout}.`
);
} else if (parseInt(args[1]) < 300) {
ctx.replyWithHTML(
html`Captcha cooldown kick time cannot be lower than 300 seconds (5 minutes).`
);
} else {
ctx.replyWithHTML(
html`Captcha cooldown kick time value is invalid.`
);
}
} else if (args[0] === "cooldown") { // Change kick cooldown. (/captcha cooldown <integer bigger or equal to 300>).
if (parseInt(args[1]) >= 300) {
settings.kickCooldown = parseInt(args[1]);
updateSettings();
ctx.replyWithHTML(
html`Captcha cooldown kick time is now ${settings.kickCooldown}.`
);
} else if (parseInt(args[1]) < 300) {
ctx.replyWithHTML(
html`Captcha cooldown kick time cannot be lower than 300 seconds (5 minutes).`
);
} else {
ctx.replyWithHTML(
html`Captcha cooldown kick time value is invalid.`
);
}
} else if (args[0] === "strict") { // Change Captcha strict (/captcha strict <true or false>).
if (args[1] == "true") {
settings.strict = true;
updateSettings();
ctx.replyWithHTML(
html`Captcha strict is enabled.`
);
} else if (args[1] == "false") {
settings.strict = false;
updateSettings();
ctx.replyWithHTML(
html`Captcha strict is disabled.`
);
}
} else if (args[0] === "attempts") { // Change max attempts (/captcha attempts <integer bigger or equal to 1>).
if (parseInt(args[1]) >= 1) {
settings.maxAttempts = parseInt(args[1]);
updateSettings();
ctx.replyWithHTML(
html`Captcha max attempts is now ${settings.maxAttempts}.`
);
} else if (parseInt(args[1]) < 1) {
ctx.replyWithHTML(
html`Captcha max attempts cannot be lower than 1 attempt.`
);
} else {
ctx.replyWithHTML(
html`Captcha max attempts value is invalid.`
);
}
} else if (args[0] === "exclude") { // Changes if the plugin will work on this chat or not (/captcha exclude).
let exclusionResult = updateExclusion(String(ctx.chat?.id));
updateSettings();
if (exclusionResult === 0) {
ctx.replyWithHTML(
html`Captcha will stop working in this chat.`
);
} else if (exclusionResult === 1) {
ctx.replyWithHTML(
html`Captcha will resume working in this chat.`
);
}
} else if (args[0] === "settings") { // Print plugin settings (/captcha settings).
ctx.replyWithHTML(
html`Captcha settings:
<code>
active: ${settings.active}
challengeTimeout: ${settings.challengeTimeout}
kickCooldown: ${settings.kickCooldown}
strict: ${settings.strict}
maxAttempts: ${settings.maxAttempts}
exclude: ${settings.exclude}
</code>`
);
} else { // Invalid arguments, show Captcha commands.
ctx.replyWithHTML(
html`Captcha usage:
<code>/captcha argument value</code>\n
Captcha arguments:\n
<code>on</code> - Enables Captcha.
<code>off</code> - Disables Captcha.
<code>timeout</code> - Changes the challenge timeout, in seconds, cannot be lower than 300 seconds (5 minutes).
<code>cooldown</code> - Changes the kick cooldown, in seconds, cannot be lower than 300 seconds (5 minutes).
<code>strict</code> - Switches message deletion on challenge ending on and off, boolean, only accepts true or false.
<code>attempts</code> - Changes the max number of attempts, cannot be lower than 1.
<code>exclude</code> - Changes if the plugin will work on this chat or not.
<code>settings</code> - Shows the current settings for Captcha.`
);
}
}
}
ctx.deleteMessage(ctx.message?.message_id);
}
}
if (settings.active && settings.exclude.indexOf(String(ctx.chat?.id)) < 0) {
const members = ctx.message?.new_chat_members?.filter(
(x) => x.username !== ctx.me
);
const memberLeft = ctx.message?.left_chat_member;
if (!members || members.length === 0) {
const foundChallenge = activeChallenges.find(
(x) => (x.user.id === ctx.from?.id && x.chat === String(ctx.chat?.id))
);
if (!foundChallenge) {
return next();
}
if (memberLeft) {
if (memberLeft.id === foundChallenge.user.id) {
clearTimeout(foundChallenge.kickTimeout);
activeChallenges.splice(activeChallenges.indexOf(foundChallenge), 1);
return Promise.all([
ctx.message?.message_id
? ctx.deleteMessage(ctx.message?.message_id)
: Promise.resolve(true),
ctx.deleteMessage(foundChallenge.messageId),
foundChallenge.deleteList.forEach(number => {
ctx.deleteMessage(number);
}),
]).catch((err) => logError("[captcha] " + err.message));
}
}
if (Number(ctx.message?.text) === foundChallenge.math[1]) {
//logError("Correct Answer: \n" + ctx.message?.text + " " + foundChallenge.math[1] + "\n" + ctx.chat?.id + " " + foundChallenge.chat);
clearTimeout(foundChallenge.kickTimeout);
activeChallenges.splice(activeChallenges.indexOf(foundChallenge), 1);
return Promise.all([
ctx.message?.message_id
? ctx.deleteMessage(ctx.message?.message_id)
: Promise.resolve(true),
ctx.deleteMessage(foundChallenge.messageId),
foundChallenge.deleteList.forEach(number => {
ctx.deleteMessage(number);
}),
ctx.replyWithHTML(html`Thank you, ${link(ctx.from)}, please read the rules in our pinned message and enjoy the chat!`),
ctx.telegram.restrictChatMember(ctx.chat?.id, ctx.from?.id, verifiedOptions),
]).catch((err) => logError("[captcha] " + err.message));
}
if (Number(ctx.message?.text) !== foundChallenge.math[1]) {
//logError("Wrong Answer: \n" + ctx.message?.text + " " + foundChallenge.math[1] + "\n" + ctx.chat?.id + " " + foundChallenge.chat);
if (foundChallenge.attempts >= 1) {
let msg;
let replyMessage;
foundChallenge.attempts = foundChallenge.attempts - 1;
if (foundChallenge.attempts > 1) {
replyMessage = html`Sorry, ${link(ctx.from)}, that answer is incorrect, you have ${foundChallenge.attempts} attempts left, try again!`;
} else if (foundChallenge.attempts === 1) {
replyMessage = html`Sorry, ${link(ctx.from)}, that answer is incorrect, you have ${foundChallenge.attempts} attempt left, try again!`;
} else {
replyMessage = html`Sorry, ${link(ctx.from)}, that answer is incorrect, this is your last attempt, try again!`;;
}
return Promise.all([
foundChallenge.deleteList.push(ctx.message?.message_id),
msg = await ctx.replyWithHTML(replyMessage),
foundChallenge.deleteList.push(msg?.message_id),
]).catch((err) => logError("[captcha] " + err.message));
} else {
clearTimeout(foundChallenge.kickTimeout);
activeChallenges.splice(activeChallenges.indexOf(foundChallenge), 1);
return Promise.all([
ctx.message?.message_id
? ctx.deleteMessage(ctx.message?.message_id)
: Promise.resolve(true),
ctx.deleteMessage(foundChallenge.messageId),
foundChallenge.deleteList.forEach(number => {
ctx.deleteMessage(number);
}),
ctx.kickChatMember(ctx.from?.id, Math.floor((Date.now() / 1000) + settings.kickCooldown)),
]).catch((err) => logError("[captcha] " + err.message));
}
}
return settings.strict
? ctx.message?.message_id
? ctx.deleteMessage(ctx.message?.message_id)
: Promise.resolve(true)
: next();
}
return Promise.all(
members.map(async (x) => {
if (!x.is_bot) {
const c = challenge(activeChallenges, ctx, x);
activeChallenges.push(c);
const msg = await ctx.replyWithHTML(
html`Welcome ${link(x)}, please solve the following arithmetic operation in ${(settings.challengeTimeout / 60)} minutes: \n\n
<code>${c.math[0]} = ?</code> \n\n
Note: Results can be negative, don't forget the (-) sign if so`
);
c.chat = String(ctx.chat?.id);
c.messageId = msg.message_id;
ctx.telegram.restrictChatMember(ctx.chat?.id, ctx.from?.id, unverifiedOptions);
}
})
);
} else {
return next();
}
});