· 6 years ago · Aug 13, 2019, 01:40 PM
1const mysql = require('mysql2');
2const telegraf = require('telegraf')
3const SocksAgent = require('socks5-https-client/lib/Agent');
4
5const tables = {
6 users: "CREATE TABLE users " +
7 " (user_id INT not null," +
8 " username VARCHAR(64)," +
9 " first_name VARCHAR(64)," +
10 " last_name VARCHAR(64)," +
11 " PRIMARY KEY (user_id) )",
12
13 likes: "CREATE TABLE likes " +
14 " (id INT not null AUTO_INCREMENT, " +
15 " from_id INT," +
16 " recipient_id INT," +
17 " reputation_value INT," +
18 " time INT," +
19 " chat_id INT," +
20 " PRIMARY KEY (id) )"
21};
22
23const rep_change_timeout = 3600;
24const bot_token = '748452422:AAHQwNdhaMcLT1FF0EIlzrUs63eT5_p2-7g';
25
26const conn = mysql.createConnection({
27 database: 'tgbot', host: "localhost",
28 user: "root", password: ""
29});
30
31for (let tbl in tables) {
32 conn.query(`DROP TABLE IF EXISTS ${tbl}`);
33 conn.query(tables[tbl]);
34}
35
36const is_loise = text => text.startsWith("лойс") ? 1 : 0;
37
38const bot = new telegraf(bot_token, {
39 telegram: {
40 agent: new SocksAgent({socksHost: "127.0.0.1", socksPort: 9155})
41 }
42});
43
44bot.on('message', (ctx) => {
45 ctx.getChat().then(chat => {
46 if (chat.type !== 'group') return
47 let user_id = ctx.message.from.id;
48 conn.execute(`SELECT * FROM users WHERE user_id = ${user_id}`, (err, result) => {
49 if (typeof result === 'undefined' || result.length == 0) {
50 conn.query(`INSERT INTO users SET ?`, {
51 user_id: user_id,
52 first_name: ctx.message.from.first_name,
53 last_name: ctx.message.from.last_name,
54 username: ctx.message.from.username
55 });
56 }
57 });
58
59 if (typeof ctx.message.reply_to_message !== 'undefined') {
60 let text = ctx.message.text;
61 if (text.startsWith("лойс") || text.startsWith("зашкв")) {
62 let to_id = ctx.message.reply_to_message.from.id;
63 let rep_label = is_loise(text) ? 'лойс' : 'зашквор';
64 conn.execute(`SELECT * FROM users WHERE user_id = ${to_id}`, (err, result) => {
65 if (result.length == 0) {
66 return ctx.reply('Пользователь не найден');
67 }
68 conn.execute(`SELECT * FROM likes WHERE recipient_id = ${to_id} AND from_id = ${user_id}`, (err, result) => {
69 let times = [];
70 for (let line of result) {
71 times.push(line.time);
72 }
73 let last_time = Math.max(...times);
74 let current = new Date().getTime() / 1000;
75 if (current > last_time + rep_change_timeout) {
76 conn.query(`INSERT INTO likes SET ?`, {
77 recipient_id: to_id,
78 reputation_value: is_loise(text) ? 1 : -1,
79 time: new Date().getTime() / 1000,
80 chat_id: chat.id, from_id: user_id
81 });
82 ctx.reply(`${rep_label} поставлен`);
83 } else {
84 let next = Math.round((last_time + rep_change_timeout - current) / 60);
85 ctx.reply(`Следующий ${rep_label} можно поставить через ${next} минут`);
86 }
87 })
88 })
89 }
90 }
91 })
92})
93
94bot.launch();