Telegram 机器人玩法全攻略:从入门到进阶
Telegram 机器人玩法全攻略:从入门到进阶
前言
Telegram 是全球最受欢迎的即时通讯应用之一,其开放的机器人(Bot)API 为开发者提供了强大的自动化能力。与 Discord 机器人相比,Telegram 机器人更加轻量,部署更简单,同时也支持丰富的交互形式。本文将全面介绍 Telegram 机器人的各种玩法。
什么是 Telegram 机器人?
Telegram 机器人是运行在 Telegram 平台上的自动化程序,可以通过 Bot API 与用户进行交互。机器人可以:
- 发送和接收消息
- 处理按钮、键盘交互
- 创建和管理群组
- 处理支付
- 集成各种外部服务
- 提供 AI 对话能力
Telegram 机器人的特点
| 特点 | 说明 |
|---|---|
| 轻量级 | 无需复杂配置,快速上手 |
| 跨平台 | iOS/Android/Desktop/Web 全平台支持 |
| 免费 | Bot API 完全免费 |
| 丰富的 UI | 支持内联按钮、键盘、菜单等 |
| 隐私优先 | 用户信息保护较好 |
| 群组功能 | 支持超级群组和频道 |
创建 Telegram 机器人
步骤 1:与 BotFather 对话
- 在 Telegram 搜索 @BotFather
- 点击 Start 开始对话
- 发送
/newbot创建新机器人 - 按照提示设置机器人名称和用户名
- 用户名必须以
bot结尾(如my_ai_bot) - 获取 HTTP API Token(请妥善保存!)
步骤 2:配置机器人
BotFather 支持多种配置:
/setname - 设置机器人名称
/setdescription - 设置描述
/setabout - 设置关于信息
/setuserpic - 设置头像
/setcommands - 设置命令列表
步骤 3:开始开发
你可以选择以下方式开发:
- Node.js:使用
node-telegram-bot-api或gram.js - Python:使用
python-telegram-bot或aiogram - 其他语言:官方提供多种 SDK
Python 开发教程
环境准备
# 安装 Python(3.8+)
# 创建虚拟环境
python -m venv venv
source venv/bin/activate # Linux/Mac
# 或
venv\Scripts\activate # Windows
# 安装库
pip install python-telegram-bot requests
基础示例:Echo Bot
from telegram import Update
from telegram.ext import ApplicationBuilder, ContextTypes, MessageHandler, filters
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
await context.bot.send_message(
chat_id=update.effective_chat.id,
text=update.message.text
)
app = ApplicationBuilder().token("YOUR_TOKEN").build()
echo_handler = MessageHandler(filters.TEXT & (~filters.COMMAND), echo)
app.add_handler(echo_handler)
print("🤖 机器人启动中...")
app.run_polling()
进阶示例:AI 对话机器人
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ApplicationBuilder, ContextTypes, MessageHandler, filters, CommandHandler
import requests
# 配置
OPENAI_API_KEY = "your-openai-api-key"
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await context.bot.send_message(
chat_id=update.effective_chat.id,
text="👋 你好!我是 AI 对话机器人。直接发送消息开始聊天!\n\n使用 /clear 清除对话历史"
)
async def chat(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_message = update.message.text
# 调用 OpenAI API
try:
response = requests.post(
"https://api.openai.com/v1/chat/completions",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {OPENAI_API_KEY}"
},
json={
"model": "gpt-3.5-turbo",
"messages": [
{"role": "system", "content": "你是一个友好的AI助手。"},
{"role": "user", "content": user_message}
]
}
)
data = response.json()
ai_reply = data["choices"][0]["message"]["content"]
await context.bot.send_message(
chat_id=update.effective_chat.id,
text=ai_reply
)
except Exception as e:
await context.bot.send_message(
chat_id=update.effective_chat.id,
text=f"❌ 出错了: {str(e)}"
)
async def clear(update: Update, context: ContextTypes.DEFAULT_TYPE):
await context.bot.send_message(
chat_id=update.effective_chat.id,
text="✅ 对话历史已清除"
)
# 构建应用
app = ApplicationBuilder().token("YOUR_TOKEN").build()
# 添加处理器
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("clear", clear))
app.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), chat))
print("🤖 AI 机器人启动中...")
app.run_polling()
完整示例:多功能机器人
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ApplicationBuilder, ContextTypes, MessageHandler, filters, CommandHandler, CallbackQueryHandler
import requests
import json
# 配置
BOT_TOKEN = "YOUR_TOKEN"
WEATHER_API_KEY = "your-weather-api"
# 状态管理
user_states = {}
# ========== 命令处理器 ==========
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
keyboard = [
[InlineKeyboardButton("🌤️ 天气查询", callback_data="weather")],
[InlineKeyboardButton("📢 广播消息", callback_data="broadcast")],
[InlineKeyboardButton("ℹ️ 帮助", callback_data="help")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(
"👋 欢迎使用多功能机器人!\n\n请选择功能:",
reply_markup=reply_markup
)
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
help_text = """
📚 可用命令:
/start - 启动机器人
/help - 显示帮助
/weather <城市> - 查询天气
/echo <文本> - 回显消息
/meme - 获取随机表情包
"""
await update.message.reply_text(help_text)
# ========== 回调处理器 ==========
async def button_click(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
await query.answer()
if query.data == "weather":
await query.edit_message_text("请发送您要查询的城市名称:")
user_states[query.from_user.id] = "waiting_weather"
elif query.data == "help":
await query.edit_message_text(help_text)
# ========== 消息处理器 ==========
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
text = update.message.text
# 天气查询状态
if user_id in user_states and user_states[user_id] == "waiting_weather":
city = text
# 调用天气 API
try:
response = requests.get(
f"http://api.weatherapi.com/v1/current.json",
params={"key": WEATHER_API_KEY, "q": city}
)
data = response.json()
weather_text = f"""
🌤️ {data['location']['name']} 天气
🌡️ 温度: {data['current']['temp_c']}°C
💧 湿度: {data['current']['humidity']}%
🌬️ 风速: {data['current']['wind_kph']} km/h
☁️ 天气: {data['current']['condition']['text']}
"""
await update.message.reply_text(weather_text)
except:
await update.message.reply_text("❌ 查询失败,请检查城市名称")
del user_states[user_id]
return
# 普通消息处理
if text.startswith("/echo "):
await update.message.reply_text(text[6:])
elif text == "/meme":
# 随机表情包图
await update.message.reply_photo(
"https://placeholder.com/meme.jpg",
caption="🎭 随机表情包"
)
else:
await update.message.reply_text(f"收到: {text}\n\n输入 /help 查看所有命令")
# ========== 主程序 ==========
app = ApplicationBuilder().token(BOT_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("help", help_command))
app.add_handler(CallbackQueryHandler(button_click))
app.add_handler(MessageHandler(filters.TEXT, handle_message))
print("🤖 多功能机器人启动中...")
app.run_polling()
Node.js 开发教程
环境准备
# 安装 Node.js(18+)
# 创建项目
mkdir tg-bot
cd tg-bot
npm init -y
# 安装 telegram-bot-api
npm install node-telegram-bot-api
基础示例
const TelegramBot = require('node-telegram-bot-api');
// 替换为你的 Token
const token = 'YOUR_BOT_TOKEN';
// 创建机器人
const bot = new TelegramBot(token, { polling: true });
// 监听消息
bot.on('message', (msg) => {
const chatId = msg.chat.id;
const text = msg.text;
// 忽略命令
if (text.startsWith('/')) return;
// Echo
bot.sendMessage(chatId, `你发送了: ${text}`);
});
// 命令
bot.onText(/\/start/, (msg) => {
bot.sendMessage(msg.chat.id, '欢迎使用!');
});
bot.onText(/\/help/, (msg) => {
bot.sendMessage(msg.chat.id, `
可用命令:
/start - 启动
/help - 帮助
/echo <文本> - 回显
`);
});
console.log('🤖 机器人已启动');
AI 对话示例
const TelegramBot = require('node-telegram-bot-api');
const axios = require('axios');
const bot = new TelegramBot('YOUR_TOKEN', { polling: true });
const conversations = new Map();
// 处理用户消息
bot.on('message', async (msg) => {
const chatId = msg.chat.id;
const text = msg.text;
if (text.startsWith('/')) return; // 跳过命令
// 初始化对话历史
if (!conversations.has(chatId)) {
conversations.set(chatId, []);
}
const history = conversations.get(chatId);
// 添加用户消息
history.push({ role: 'user', content: text });
// 调用 OpenAI
try {
const response = await axios.post(
'https://api.openai.com/v1/chat/completions',
{
model: 'gpt-3.5-turbo',
messages: [
{ role: 'system', content: '你是一个友好的AI助手。' },
...history.slice(-10)
]
},
{
headers: {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
'Content-Type': 'application/json'
}
}
);
const reply = response.data.choices[0].message.content;
// 添加AI回复
history.push({ role: 'assistant', content: reply });
bot.sendMessage(chatId, reply);
} catch (error) {
bot.sendMessage(chatId, '❌ 出错了,请稍后重试');
}
});
// 清除历史
bot.onText(/\/clear/, (msg) => {
conversations.delete(msg.chat.id);
bot.sendMessage(msg.chat.id, '✅ 对话历史已清除');
});
高级功能
1. 内联键盘(Inline Keyboard)
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
keyboard = [
[
InlineKeyboardButton("🔗 链接", url="https://example.com"),
InlineKeyboardButton("🔙 回退", callback_data="back")
],
[InlineKeyboardButton("❌ 关闭", callback_data="close")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text("选择操作:", reply_markup=reply_markup)
2. 自定义键盘(Custom Keyboard)
from telegram import KeyboardButton, ReplyKeyboardMarkup
keyboard = [
[KeyboardButton("📷 拍照"), KeyboardButton("📍 位置")],
[KeyboardButton("👤 我的资料")]
]
reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)
await update.message.reply_text("选择:", reply_markup=reply_markup)
3. 群组管理
# 监听新成员
async def new_member(update: Update, context: ContextTypes.DEFAULT_TYPE):
for member in update.message.new_chat_members:
await context.bot.send_message(
chat_id=update.effective_chat.id,
text=f"👋 欢迎 {member.first_name}!"
)
# 监听离开
async def left_member(update: Update, context: ContextTypes.DEFAULT_TYPE):
await context.bot.send_message(
chat_id=update.effective_chat.id,
text="👋 有成员离开了"
)
app.add_handler(MessageHandler(filters.StatusUpdate.NEW_CHAT_MEMBERS, new_member))
app.add_handler(MessageHandler(filters.StatusUpdate.LEFT_CHAT_MEMBER, left_member))
4. 定时任务
from telegram.ext import ApplicationHandlerComplete, ContextTypes
import datetime
async def daily_reminder(context: ContextTypes.DEFAULT_TYPE):
await context.bot.send_message(
chat_id=CHAT_ID,
text="☀️ 早安!新的一天开始了"
)
# 添加定时任务
job_queue = app.job_queue
job_queue.run_daily(daily_reminder, time=datetime.time(hour=8, minute=0))
部署上线
1. Railway 部署
# requirements.txt
python-telegram-bot==20.3
requests==2.31.0
Railway 会自动识别 Python 项目并部署。
2. VPS 部署
# 使用 systemd
sudo nano /etc/systemd/system/tgbot.service
[Unit]
Description=Telegram Bot
After=network.target
[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/tg-bot
ExecStart=/home/ubuntu/tg-bot/venv/bin/python main.py
Restart=always
[Install]
WantedBy=multi-user.target
sudo systemctl enable tgbot
sudo systemctl start tgbot
3. Docker 部署
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "main.py"]
docker build -t tg-bot .
docker run -d --name tg-bot --env TOKEN=xxx tg-bot
实用机器人推荐
开源项目
- Telegram Bot SDK - 官方 PHP SDK
- NadekoBot - 多功能音乐 bot
- Rose - 功能强大的管理 bot
实用机器人
- @BotListBot - 发现更多机器人
- @GIF - 表情包搜索
- @VoteBot - 投票工具
- @ControllerBot - 频道管理
最佳实践
1. 安全配置
# 验证用户
async def restricted(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
allowed_users = [123456789, 987654321] # 白名单
if user_id not in allowed_users:
await update.message.reply_text("❌ 权限不足")
return
# 执行命令
await process_command(update, context)
2. 错误处理
import logging
logging.basicConfig(level=logging.INFO)
async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
logging.error(f"Update {update} caused error {context.error}")
3. 速率限制
from telegram.ext import AIORateLimiter
rate_limiter = AIORateLimiter(max_retries=3)
app = ApplicationBuilder()
.token(BOT_TOKEN)
.rate_limiter(rate_limiter)
.build()
结语
Telegram 机器人是构建自动化服务和 AI 应用的最佳选择之一。相比 Discord,Telegram 机器人的配置更加简单,交互形式更加丰富,同时也更加轻量。
本文从创建机器人、基础开发、进阶功能到部署上线,提供了完整的指南。无论你是想构建一个简单的 Echo Bot,还是复杂的 AI 对话机器人,Telegram 都是值得尝试的平台。
现在就开始创建你的第一个 Telegram 机器人吧!
相关推荐: - Discord 机器人怎么玩 - AI 自动化工具推荐 - Telegram 机器人案例