如何通过Webhooks(如Telegram Bot的Getupdates方法)获取消息?Express+Telegraf实现
用Express + Telegraf通过Webhook接收Telegram消息的正确配置
原代码的问题点
webhookCallback参数错误:应该传入本地路由路径(如/webhook),而非完整的ngrok URLsetWebhook调用格式错误:无需手动拼接Telegram API地址,直接传入完整的Webhook目标URL即可
修正后的完整代码
const { Telegraf } = require('telegraf'); const express = require('express'); // 从配置读取Bot Token,确保配置项正确 const BOT_TOKEN = config.get('Customer.BOT_CONFIG.TOKEN'); const bot = new Telegraf(BOT_TOKEN); const app = express(); // 配置Webhook的本地接收路由 app.use(bot.webhookCallback('/webhook')); // 设置Telegram Webhook:ngrok地址 + 本地路由 bot.telegram.setWebhook('https://c2b4-5-237-204-80.eu.ngrok.io/webhook'); // 服务器根路径测试接口 app.get('/', (req, res) => { res.send('Bot服务已启动'); }); // 添加消息处理逻辑:响应文本消息 bot.on('text', (ctx) => { ctx.reply(`收到你的消息:${ctx.message.text}`); }); // 启动Express服务 app.listen(3000, () => { console.log('服务器运行在3000端口'); });
操作步骤
- 确保依赖已安装:
npm install telegraf express
- 启动ngrok映射本地3000端口:
ngrok http 3000
- 替换代码中的ngrok URL为你当前生成的地址
- 启动Node服务:
node your-bot-file.js
- 给Bot发送消息,验证是否收到回复
Webhook与getUpdates的区别
- Webhook:Telegram服务器主动将消息POST到你的公网地址,适合生产环境,无需持续轮询
- getUpdates:Bot主动轮询Telegram服务器拉取消息,适合开发调试,只需调用
bot.launch()即可,无需配置Express
内容的提问来源于stack exchange,提问作者EhsanKey_
相关产品推荐
相关产品推荐

