Skip to content

Instantly share code, notes, and snippets.

@IvanAdmaers
Created March 3, 2023 20:10
Show Gist options
  • Save IvanAdmaers/7dcca0793f8c4611e27d61f11b29a18d to your computer and use it in GitHub Desktop.
Save IvanAdmaers/7dcca0793f8c4611e27d61f11b29a18d to your computer and use it in GitHub Desktop.
Telegraf 4 + Express + Webhook
const express = require('express');
const { Telegraf } = require('telegraf');
const app = express();
const port = process.env.PORT || 3000;
// Set up the webhook URL
const webhookUrl = `https://your-webhook-url.com/telegraf-bot`;
// Create a new instance of the Telegraf class
const bot = new Telegraf(process.env.BOT_TOKEN);
// Set up middleware to parse incoming requests
app.use(express.json());
// Set up a route to handle incoming webhook requests
app.post(`/telegraf-bot`, (req, res) => {
bot.handleUpdate(req.body, res);
});
// Start the webhook
bot.telegram.setWebhook(webhookUrl);
// Start the Express app
app.listen(port, () => {
console.log(`Express server listening on port ${port}`);
});
// Set up the Telegraf bot commands
bot.start((ctx) => ctx.reply('Welcome!'));
bot.help((ctx) => ctx.reply('Send me a message and I will echo it back.'));
// Handle incoming messages
bot.on('message', (ctx) => {
ctx.reply(`You said: ${ctx.message.text}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment