This repository has been archived by the owner on Aug 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
169 lines (146 loc) · 4.35 KB
/
index.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
const path = require("path");
const { Telegraf } = require("telegraf");
const TelegrafI18n = require("telegraf-i18n");
const TelegrafLocalSession = require("telegraf-session-local");
const express = require("express");
const apiMetrics = require("prometheus-api-metrics");
const Prometheus = require("prom-client");
const metrics = {
updatesTotal: new Prometheus.Counter({
name: "telegram_bot_updates_received_total",
help: "Total number of updates received from the Telegram Bot API",
labelNames: ["update_type"],
}),
startTotal: new Prometheus.Counter({
name: "telegram_bot_started_total",
help: "Total number of /start command received from the Telegram Bot API",
labelNames: ["chat_type"],
}),
keyboardsRemovedTotal: new Prometheus.Counter({
name: "telegram_bot_keyboards_removed_total",
help: "Total times added to group chat to remove a stuck keyboard",
labelNames: [],
}),
};
// Prepare i18n
const i18n = new TelegrafI18n({
defaultLanguage: "en",
allowMissing: true,
directory: path.resolve(__dirname, "locales"),
});
// Prepare sessions
const LocalSession = new TelegrafLocalSession({
storage: TelegrafLocalSession.storageMemory,
});
// Create bot and load middlewares
const botToken = process.env.BOT_TOKEN;
const bot = new Telegraf(botToken);
bot.context.botID = parseInt(botToken.split(":")[0]);
bot.use(i18n.middleware());
bot.use(LocalSession.middleware());
// Count the updates
bot.use(async (ctx, next) => {
metrics.updatesTotal.inc({
update_type: ctx.updateType,
});
return next();
});
bot.start((ctx) => {
// 1-1 CHAT HANDLING
if (ctx.update.message.chat.type === "private") {
ctx.replyWithHTML(ctx.i18n.t("start") + ctx.i18n.t("help"));
}
// GROUP CHAT HANDLING
else {
// TODO
// console.debug(ctx.update.message.chat);
}
metrics.startTotal.inc({
chat_type: ctx.update.message.chat.type ?? "unknown",
});
});
bot.on("new_chat_members", (ctx) => {
// Only proceed if the bot itself is one of the added chat members
const newMembers = ctx.update.message.new_chat_members;
if (newMembers.find((e) => e.id === ctx.botID) === undefined) {
console.warn(
"Received new_chat_members update, but did not find this bot in the list of added members."
);
return;
}
console.log(
`Was added to group#${ctx.chat.id}. Attempting to delete stuck inline buttons`
);
// Purge all the inline buttons
deleteInlineButtons(ctx);
//console.debug(ctx.botID, newMembers);
});
bot.command("deletekeyboard", (ctx) => {
deleteInlineButtons(ctx);
});
bot.help((ctx) => ctx.replyWithHTML(ctx.i18n.t("help")));
/*
-----------------------------------------------------------
Helper Functions
-----------------------------------------------------------
*/
async function deleteInlineButtons(ctx, leaveAfterDeleting = true) {
try {
// Send a new message with an inline keyboard to overwrite any current keyboards
const mockKeyboardMsg = await ctx.reply(
ctx.i18n.t("start_removing_keyboard"),
{
reply_markup: {
resize_keyboard: true,
keyboard: [
[
{
text: ctx.i18n.t("removing_keyboard_btn_placeholder"),
},
],
],
},
}
);
// attempt to delete it again
await ctx.deleteMessage(mockKeyboardMsg.message_id);
// send a new message to delete the just sent keyboard
await ctx.reply(ctx.i18n.t("done_removing_keyboard"), {
reply_markup: {
remove_keyboard: true,
},
});
// Log metric
metrics.keyboardsRemovedTotal.inc();
} catch (error) {
console.error(
Date.now(),
" Failed to remove a keyboard in chat ",
ctx.update.message.chat.id,
". Error:\n",
error
);
}
try {
if (leaveAfterDeleting) await ctx.leaveChat();
} catch (error) {
/* Whatever, screw it.*/
}
}
// Start the bot
console.log(
`Starting longPolling (chat_id of bot: ${
process.env.BOT_TOKEN.split(":")[0]
})...`
);
bot.launch();
// If enabled, start to expose metrics via http server
if (["true", "1"].includes(process.env.EXPOSE_METRICS?.trim()?.toLowerCase())) {
const app = express();
app.use(apiMetrics());
const port = process.env.PORT ?? 3000;
const host = process.env.HOST ?? "0.0.0.0";
app.listen(port, host, () => {
console.log(`Exposing metrics on port ${port}`);
});
}