-
安装必要的软件:
- 安装Node.js和npm。
- 使用命令安装Telegraf和Express:
npm install telegraf express dotenv
-
创建项目结构:
-
创建目录
my-telegram-bot。 -
在目录中创建
package.json,添加依赖:{ "name": "my-telegram-bot", "version": "1..", "description": "Telegram bot using Telegraf and Express", "main": "index.js", "scripts": { "start": "node index.js" }, "dependencies": { "express": "^4.18.2", "telegraf": "^3.3.2", "dotenv": "^16.3.1" } } -
创建
index.js,初始化bot:const express = require('express'); const telegraf = require('telegraf'); const app = express(); const bot = telegraf('你的API密钥'); app.use('/webhook', telegraf.webhook('你的botusername', { port: 300, path: '/webhook' })); app.get('/webhook', (req, res) => { const updating = req.telegram.update; const message = updating.message || updating.edited_message; if (message.text) { res.json({ text: '你好!' }); } else { res.json({ error: '消息为空' }); } }); app.listen(300, () => { console.log('Telegram bot started on port 300'); });
-
-
获取Telegram API密钥:
- 在Telegram官网注册一个bot,使用
botfather获取bot username和API密钥。
- 在Telegram官网注册一个bot,使用
-
配置环境变量:
- 在项目根目录创建
.env文件,填写API密钥:TELEGRAM_API_KEY=你的API密钥 TELEGRAM_BOT_USERNAME=你的botusername
- 在项目根目录创建
-
运行代码:
- 使用
npm start运行项目。 - 在Telegram中添加该bot作为成员,以管理员身份加入同一组聊天。
- 使用
-
测试功能:
在聊天中发送消息到bot,检查是否能正常接收和响应。
通过以上步骤,你可以成功配置一个处理Telegram消息的节点,实现自动化功能。




