-
Notifications
You must be signed in to change notification settings - Fork 3
/
telegram.js
77 lines (70 loc) · 2.26 KB
/
telegram.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
//https://github.com/yagop/node-telegram-bot-api/issues/540
process.env.NTBA_FIX_319 = 1;
const EMAIL_REGEX =
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const TelegramBot = require("node-telegram-bot-api");
const ApprovedEmail = require("./models/ApprovedEmail.schema");
module.exports = async () => {
const token = process.env.TELEGRAM_BOT_TOKEN;
if (!token) {
console.log("TELEGRAM_BOT_TOKEN environment variable not set.");
return;
}
let admins = [];
try {
admins = JSON.parse(process.env.TELEGRAM_ADMINS);
} catch (err) {
console.log(err);
return;
}
const bot = new TelegramBot(token, { polling: { interval: 500 } });
bot.onText(/id/, async (msg, match) => {
bot.sendMessage(
msg.chat.id,
`User ID: ${msg.from.id}\nChat ID: ${msg.chat.id}`
);
});
bot.onText(/\/approve (.+)(?:,\s*|$)/, async (msg, match) => {
if (admins.includes(msg.from.id)) {
const emails = match[1].split(",");
for (let email of emails) {
email = email.trim();
if (EMAIL_REGEX.test(email)) {
const approvedEmail = await ApprovedEmail.findOne({ email });
if (approvedEmail) {
bot.sendMessage(msg.chat.id, "Already approved: " + email);
} else {
await ApprovedEmail.updateOne(
{ email },
{ email },
{ upsert: true }
);
bot.sendMessage(msg.chat.id, "Approved email: " + email);
}
} else {
bot.sendMessage(msg.chat.id, "Invalid email.", {
reply_to_message_id: msg.message_id,
});
}
}
} else {
bot.sendMessage(msg.chat.id, "You are not an admin.", {
reply_to_message_id: msg.message_id,
});
}
});
bot.onText(/\/approve/, (msg, match) => {
if (admins.includes(msg.from.id)) {
if (msg.text.replace(/\/approve /g, "").length === 0) {
bot.sendMessage(
msg.chat.id,
"Invalid usage. Usage: /approve [email protected]"
);
}
} else {
bot.sendMessage(msg.chat.id, "You are not an admin.", {
reply_to_message_id: msg.message_id,
});
}
});
};