-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
393 lines (333 loc) · 15.1 KB
/
server.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
const request = require('request');
const path = require('path');
const compression = require('compression');
const cors = require('cors');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const serverLink = process.env.SERVER_URL;
app.use(express.static(__dirname + '/static'));
app.use(bodyParser.json());
app.use(cors());
const users = [];
const chats = [];
const defaultOnlineState = true;
// handle admin Telegram messages
app.post('/hook', function (req, res) {
try {
if (!req.body.callback_query) {
const message = req.body.message || req.body.channel_post;
const chatId = message.chat.id;
const name = message.from.first_name || message.chat.title || 'admin';
const text = message.text || '';
const reply = message.reply_to_message;
console.log('< ' + text);
if (text.startsWith('/start')) {
console.log('/start chatId ' + chatId);
sendTelegramMessage(chatId,
'*Бот запущен*\n' +
'Уникальный *id* чата: `' + chatId + '`\n\n' +
'*Команды:*\n' +
'`/start` - Запуск бота\n' +
'`/all [any_text]` - Сообщение всем online пользователям\n' +
'`/who` - Список online пользователей\n' +
'`/online` - Установить online статус (Открыть виджет)\n' +
'`/offline` - Установить offline статус (Закрыть виджет)\n' +
'`/ban [name]` - Забанить пользователя\n' +
'`/unban [name]` - Разбанить пользователя\n' +
'`/user [name]` - Посмотреть информацию о пользователе\n'
,
'Markdown');
}
if (text.startsWith('/who')) {
console.log('/who');
const usersOnline = users.filter(user => user.chatId === chatId && user.online);
if (usersOnline.length) {
sendTelegramMessage(chatId,
'**Online пользователи**\n' +
usersOnline.map(user => '- `' + user.userId + '`').join('\n'),
'Markdown');
} else {
sendTelegramMessage(chatId, '**Нет online пользователей** 🌵');
}
}
if (text.startsWith('/online')) {
console.log('/online chatId ' + chatId);
const chatIndex = chats.findIndex(chat => chat.chatId === chatId);
if (chats[chatIndex]) {
chats[chatIndex].online = true;
} else {
chats.push({
chatId: chatId,
online: true,
});
}
sendTelegramMessage(chatId, 'Статус чата установлен на *online* 🟢, теперь он будет виден всем пользователям сайта', 'Markdown');
}
if (text.startsWith('/offline')) {
console.log('/offline chatId ' + chatId);
const chatIndex = chats.findIndex(chat => chat.chatId === chatId);
if (chats[chatIndex]) {
chats[chatIndex].online = false;
} else {
chats.push({
chatId: chatId,
online: false,
});
}
sendTelegramMessage(chatId, 'Статус чата установлен на *offline* 🔴', 'Markdown');
}
if (text.startsWith('/all')) {
const message = text.replace(/^\/all(@?\w+)? /, '');
console.log('/all ' + message);
io.emit(chatId, {
name: name,
text: message,
from: 'admin',
});
}
if (text.startsWith('/ban')) {
const userId = text.replace(/^\/ban(@?\w+)? /, '');
if (userId === '') {
sendTelegramMessage(chatId, 'Введите имя пользователя, например:`/ban guest-user-01`', 'Markdown');
}
const userIndex = users.findIndex(user => user.userId === userId && user.chatId === chatId);
if (users[userIndex]) {
users[userIndex].banned = true;
sendTelegramMessage(chatId, 'Пользователь с ником *' + userId + '* помещен в бан ⛔', 'Markdown');
} else {
sendTelegramMessage(chatId, 'Пользователь не найден или не удалось поместить его в бан.', 'Markdown');
}
}
if (text.startsWith('/unban')) {
const userId = text.replace(/^\/unban(@?\w+)? /, '').trim();
const userIndex = users.findIndex(user => user.userId === userId && user.chatId === chatId);
if (userIndex !== -1) {
users[userIndex].banned = false;
sendTelegramMessage(chatId, 'Пользователь с ником *' + userId + '* снова может общаться в чате.', 'Markdown');
} else {
sendTelegramMessage(chatId, 'Пользователь не найден или не удалось его разбанить.', 'Markdown');
}
}
if (text.startsWith('/user')) {
const userId = text.replace(/^\/user(@?\w+)? /, '');
const user = users.find(user => user.userId === userId && user.chatId === chatId);
if (user) {
const CustomData = user.CustomData || {};
const username = user.CustomData.username || userId;
const CustomMsg = `\`${username}\`\n\n${Object.entries(CustomData).map(([label, value]) => `${label.trim()} : \`${value.trim()}\``).join('\n')}`;
sendTelegramMessage(chatId, CustomMsg, 'Markdown');
} else {
sendTelegramMessage(chatId, 'Пользователь не найден', 'Markdown');
}
}
if (text.startsWith('/test')) {
const inlineKeyboard = [
[
{text: 'Button 1', callback_data: 'button_1'},
{text: 'Button 2', callback_data: 'button_2'},
],
[
{text: 'Button 3', callback_data: 'button_3'},
{text: 'Button 4', callback_data: 'button_4'},
],
[
{text: 'Button 5', callback_data: 'button_5'},
],
];
sendTelegramMessage(
chatId,
'What todo with the user?🔥\n\n',
'Markdown',
false,
inlineKeyboard,
);
}
if (reply && text) {
const replyText = reply.text || '';
const userId = replyText.split(':')[0];
const userIndex = users.findIndex(user => user.userId === userId && user.chatId === chatId);
console.log(userId);
if (users[userIndex]) {
if (users[userIndex].online) {
io.emit(chatId + '-' + userId, {name, text, from: 'admin'});
} else {
users[userIndex].messages.push({
name: name,
text: text,
time: new Date,
from: 'admin',
});
}
}
}
} else {
const callbackQuery = req.body.callback_query;
console.log(callbackQuery);
const chatId = callbackQuery.message.chat.id;
const data = callbackQuery.data;
switch (data) {
case 'button_1':
sendTelegramMessage(chatId, 'You clicked Button 1!');
break;
case 'button_2':
sendTelegramMessage(chatId, 'You clicked Button 2!');
break;
default:
break;
}
// Respond to the callback query to acknowledge receipt
request.post('https://api.telegram.org/bot' + process.env.TELEGRAM_TOKEN + '/answerCallbackQuery')
.form({
callback_query_id: callbackQuery.id,
})
.on('response', function (response) {
console.log('telegram callback response:', response.statusCode);
});
}
} catch (e) {
console.error('hook error', e, req.body);
}
res.statusCode = 200;
res.end();
});
// handle chat visitors websocket messages
io.on('connection', function (client) {
client.on('register', function (registerMsg) {
const userId = registerMsg.userId;
const chatId = parseInt(registerMsg.chatId);
const CustomData = registerMsg.CustomData;
console.log('useId ' + userId + ' connected to chatId ' + chatId);
const CustomMsg = `\`${userId}\`: *присоединился*\n\n`;
let CustomMsgData = '';
if (CustomData) {
CustomMsgData = `${Object.entries(CustomData).map(([label, value]) => `${label}: ${value}`).join('\n')}`;
}
sendTelegramMessage(chatId, `${CustomMsg}${CustomMsgData}`, 'Markdown', true);
const userIndex = users.findIndex(user => user.userId === userId && user.chatId === chatId);
if (users[userIndex]) {
if (users[userIndex].banned) {
client.disconnect();
return;
}
users[userIndex].online = true;
users[userIndex].messages.forEach(message => io.emit(chatId + '-' + userId, message));
users[userIndex].messages = [];
if (users[userIndex].active) {
sendTelegramMessage(chatId, '`' + userId + '` *вернулся*', 'Markdown', true);
}
}
client.on('message', function (msg) {
const userIndex = users.findIndex(user => user.userId === userId && user.chatId === chatId);
if (users[userIndex] && users[userIndex].banned) {
client.disconnect();
return;
}
io.emit(chatId + '-' + userId, msg);
console.log('> ' + msg.text);
if (msg.text === '/help') {
io.emit(chatId + '-' + userId, {
text: registerMsg.helpMsg || 'help is coming😭',
from: 'admin',
});
return;
}
let visitorName = msg.visitorName ? '[' + msg.visitorName + ']: ' : '';
sendTelegramMessage(chatId, '`' + userId + '`:' + visitorName + ' ' + msg.text, 'Markdown');
if (users[userIndex]) {
users[userIndex].active = true;
if (users[userIndex].unactiveTimeout) {
clearTimeout(users[userIndex].unactiveTimeout);
}
} else {
users.push({
userId: userId,
chatId: chatId,
online: true,
active: true,
banned: false,
messages: [],
CustomData: CustomData || {},
});
}
});
client.on('disconnect', function () {
const userIndex = users.findIndex(user => user.userId === userId && user.chatId === chatId);
if (users[userIndex]) {
users[userIndex].online = false;
if (users[userIndex].active) {
users[userIndex].unactiveTimeout = setTimeout(() => {
users[userIndex].active = false;
}, 60000);
if (!users[userIndex].banned) {
sendTelegramMessage(chatId, '`' + userId + '` *покинул чат*', 'Markdown', true);
}
}
}
});
});
});
function sendTelegramMessage(chatId, text, parseMode, disableNotification, inlineKeyboard) {
const options = {
'chat_id': chatId,
'text': text,
'parse_mode': parseMode,
'disable_notification': !!disableNotification,
};
if (inlineKeyboard) {
options.reply_markup = JSON.stringify({
inline_keyboard: inlineKeyboard,
});
}
request
.post('https://api.telegram.org/bot' + process.env.TELEGRAM_TOKEN + '/sendMessage')
.form(options)
.on('response', function (response) {
console.log('telegram status code:', response.statusCode);
});
}
app.post('/usage-start', function (req, res) {
const chatId = parseInt(req.body.chatId);
const host = req.body.host;
let chat = chats.find(chat => chat.chatId === chatId);
if (!chat) {
chat = {
chatId: chatId,
online: defaultOnlineState,
};
chats.push(chat);
}
console.log('usage chat ' + chatId + ' (' + (chat.online ? 'online' : 'offline') + ') from ' + host);
res.statusCode = 200;
res.json({
online: chat.online,
});
});
// left here until the cache expires
app.post('/usage-end', function (req, res) {
res.statusCode = 200;
res.end();
});
app.get('/status', function (req, res) {
const currentTime = new Date().toISOString();
res.statusCode = 200;
res.send({
status: 'ok',
pingTime: currentTime,
});
console.log({
status: 'ok',
pingTime: currentTime,
});
});
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname.concat('/index.html')))
});
http.listen(process.env.PORT || 3000, function () {
console.log('listening on port:' + (process.env.PORT || 3000));
});
app.get('/.well-known/acme-challenge/:content', (req, res) => {
res.send(process.env.CERTBOT_RESPONSE);
});