-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.js
74 lines (59 loc) · 2.08 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
require('dotenv').config();
const { Bot, session, GrammyError, HttpError } = require("grammy");
const { run, sequentialize } = require("@grammyjs/runner");
// Create a bot
const bot = new Bot(process.env.BOT_TOKEN);
// Build a unique identifier for the `Context` object
function getSessionKey(ctx) {
return ctx.chat?.id.toString();
}
// Sequentialize before accessing session data
bot.use(sequentialize(getSessionKey));
bot.use(session({ getSessionKey }));
// Measure response time (optional)
async function responseTime(ctx, next) {
// take time before
const before = Date.now(); // milliseconds
// invoke downstream middleware
await next(); // make sure to `await`!
// take time after
const after = Date.now(); // milliseconds
// log difference
console.log(`Response time: ${after - before} ms`);
}
bot.use(responseTime);
// Commands
bot.command("start", (ctx) => {
ctx.reply("*Welcome!* ✨",{ parse_mode: "Markdown" } );
console.log("New user added:", ctx.from);
});
bot.command("help", (ctx) => ctx.reply("This is a template. By using you agree to ToS."));
// Messages
bot
.on("msg", async (ctx) => {
// Console
console.log('from:', ctx.from.first_name, ctx.from.last_name, '(@' + ctx.from.username + ')', 'ID:', ctx.from.id);
console.log("Message:", ctx.msg.text);
// Logic
await ctx.reply("Works!");
});
// Error Handling
bot.catch((err) => {
const ctx = err.ctx;
console.error(`Error while handling update ${ctx.update.update_id}:`);
console.error("Details:");
console.error("Query:", ctx.msg.text, "not found!");
ctx.reply("Query: " + ctx.msg.text + " " + "not found!");
const e = err.error;
if (e instanceof GrammyError) {
console.error("Error in request:", e.description);
} else if (e instanceof HttpError) {
console.error("Could not contact Telegram:", e);
} else {
console.error("Unknown error:", e);
}
});
// Run it concurrently
console.log('Bot running. Please keep this window open or use a startup manager like PM2 to setup persistent execution and store logs.');
console.log('CTRL+C to terminate.');
run(bot);