-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbot.js
167 lines (134 loc) · 5.79 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
process.env.NTBA_FIX_319 = 1;
const TelegramBot = require('node-telegram-bot-api');
const urlRegex = require('url-regex-safe');
const token = process.env.BOT_TOKEN || '';
const MINUTE_IN_MS = 60000;
const waitTime = process.env.KICK_WAIT || 30 * MINUTE_IN_MS;
// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, {polling: true});
const PhraseStorage = {
getGreetingText: (username) => `Мы рады видеть Вас, ${username}, в этом чате.\n` +
'Пожалуйста, представьтесь и поздоровайтесь с сообществом.\n' +
'Это сообщество очень трепетно относится к составу и вежливости участников.\n' +
'В случае, если я не увижу приветствия с вашей стороны, я буду вынужден удалить вас из чата через 30 минут.\n\n' +
'Любые ссылки в приветственном сообщении будут расценены как спам и неуважение к сообществу.\n\n' +
'Спасибо, что присоединились!',
getSuccessText: () => 'Спасибо! Вы приняты в сообщество!',
}
class CheckTable {
constructor () {
this.checks = {};
}
addCheck (chatId, userId, name, fake, customTimeout) {
let self = this;
let key = this.getCheckKey(chatId, userId);
let kickAfter = customTimeout || waitTime;
if (this.checks[key]) {
console.log(key + ' already watched');
return ;
}
setTimeout(() => {
self.kick(key)
}, kickAfter);
this.checks[key] = {
userId : userId,
chatId : chatId,
name : name || userId,
timeout : kickAfter,
fake : fake || false
};
}
getCheckKey (chatId, userId) {
return chatId + ':' + userId
}
checkFirstMessage (chatId, userId, messageId, text) {
let key = this.getCheckKey(chatId, userId);
if (!this.checks[key]) {
return;
}
if (urlRegex({strict: false}).test(text)) {
this.kickForBadMessage(chatId, userId, messageId)
} else {
this.approve(chatId, userId, messageId)
}
}
kickForBadMessage (chatId, userId, messageId) {
let key = this.getCheckKey(chatId, userId);
table.removeMessage(chatId, messageId);
table.kick(table.getCheckKey(chatId, userId));
console.log(key + ' was removed due to link in hello message');
}
approve (chatId, userId, messageId) {
let key = this.getCheckKey(chatId, userId);
if (!this.checks[key]) {
return;
}
delete this.checks[key];
bot.sendMessage(chatId, PhraseStorage.getSuccessText() , {
reply_to_message_id: messageId
}).then(() => {
console.log('Approve sent');
})
}
kick (checkKey) {
let check = this.checks[checkKey];
if (!check) {
console.log(checkKey + ' check not found for kicking');
return ;
}
delete this.checks[checkKey];
if (check.fake) {
bot.sendMessage(check.chatId, 'А вас ' + check.name + ' я бы сейчас выкинул');
return;
}
bot.kickChatMember(check.chatId, check.userId).then(function () {
console.log(check.userId + ' was kicked from ' + check.chatId);
bot.unbanChatMember(check.chatId, check.userId).catch(function () {
console.error('Error unbanning ' + check.userId + ' from ' + check.chatId);
});
}).catch(function () {
bot.sendMessage(check.chatId, 'Ай не получилось выкинуть ' + check.name + ' за дверь!\nСделайте меня уже админом!');
console.warn('Error on kicking ' + check.userId + ' from ' + check.chatId);
});
}
removeMessage(chatId, messageId) {
bot.deleteMessage(chatId, messageId).catch(function () {
bot.sendMessage(chatId, 'А почему это я сообщения не могу удалять?!\nСделайте меня уже админом!');
console.warn('Error on removing message ' + messageId + ' from ' + chatId);
})
}
}
let table = new CheckTable();
bot.on('text', (msg) => {
console.log('Has text', [msg.chat.id, msg.from.id, msg.message_id]);
table.checkFirstMessage(msg.chat.id, msg.from.id, msg.message_id, msg.text);
});
// Matches '/echo [whatever]'
bot.onText(/\/checkme (\d+)/, (msg, match) => {
const chatId = msg.chat.id;
console.log(match);
let customTimeout = parseInt(match[1].trim());
table.addCheck(chatId, msg.from.id, '@' + msg.from.username, true, customTimeout);
bot.sendMessage(chatId, 'Сейчас пробуем!');
});
// Listen for any kind of message. There are different kinds of
// messages.
bot.on('new_chat_members', (msg) => {
const chatId = msg.chat.id;
console.log(msg);
let members = msg.new_chat_members || [];
// let members = msg.new_chat_members || [msg.from] || [];
for (let id in members) {
let member = members[id];
if (member.is_bot === true) {
continue;
}
//bot.unbanChatMember(chatId, member.id).catch(function () {});
let name = member.username ? '@' + member.username : (member.first_name + ' ' + (member.last_name || '')).trim();
let greet = PhraseStorage.getGreetingText(name);
table.addCheck(chatId, member.id, name);
bot.sendMessage(chatId, greet, {
reply_to_message_id: msg.message_id
});
}
});