| name | telegram-dev |
| description | Telegram 生态开发全栈指南 - 涵盖 Bot API、Mini Apps (Web Apps)、MTProto 客户端开发。包括消息处理、支付、内联模式、Webhook、认证、存储、传感器 API 等完整开发资源。。 |
Telegram 生态开发技能
全面的 Telegram 开发指南,涵盖 Bot 开发、Mini Apps (Web Apps)、客户端开发的完整技术栈。
📖 目录
快速导航
🤖 Bot API 开发
🌐 Mini Apps (Web Apps) 开发
👥 客户端开发 (TDLib)
🔧 实战指南
🏗️ 项目架构
📚 实战案例
何时使用此技能
当需要以下帮助时使用此技能:
- 开发 Telegram Bot(消息机器人)
- 创建 Telegram Mini Apps(小程序)
- 构建自定义 Telegram 客户端
- 集成 Telegram 支付和业务功能
- 实现 Webhook 和长轮询
- 使用 Telegram 认证和存储
- 处理消息、媒体和文件
- 实现内联模式和键盘
Telegram 开发生态概览
三大核心 API
-
Bot API - 创建机器人程序
- HTTP 接口,简单易用
- 自动处理加密和通信
- 适合:聊天机器人、自动化工具
-
Mini Apps API (Web Apps) - 创建 Web 应用
- JavaScript 接口
- 在 Telegram 内运行
- 适合:小程序、游戏、电商
-
Telegram API & TDLib - 创建客户端
- 完整的 Telegram 协议实现
- 支持所有平台
- 适合:自定义客户端、企业应用
Bot API 开发
快速开始
Bot 菜单按钮 (Menu Button)
Bot 菜单按钮是 Telegram 在聊天界面提供的简化入口,让用户可以快速启动 Mini App。
设置菜单按钮(Bot Father):
1. 与 @BotFather 对话
2. 发送 /setmenubutton
3. 选择你的 Bot
4. 提供菜单按钮类型和 URL
菜单按钮类型:
await bot.set_chat_menu_button(
menu_button={
'type': 'web_app',
'text': '打开应用',
'web_app': {'url': 'https://your-mini-app.com'}
}
)
await bot.set_chat_menu_button(menu_button={'type': 'default'})
await bot.set_chat_menu_button(
menu_button={
'type': 'commands',
'text': '命令列表'
}
)
menu_button_info = await bot.get_chat_menu_button()
print(menu_button_info)
深度链接 (Deep Links)
深度链接允许用户通过点击链接直接与 Bot 交互,并传递参数。
创建深度链接:
invite_link = f"https://t.me/{bot_username}?start=user_12345"
group_link = await bot.create_chat_invite_link(
chat_id=group_chat_id,
name='加入我们的群组',
creates_join_request=True
)
print(group_link.invite_link)
处理深度链接:
内联深度链接:
@bot.command('start')
async def start_with_app(update: Update, context: ContextTypes.DEFAULT_TYPE):
if context.args and context.args[0].startswith('app_'):
app_parameter = context.args[0][4:]
keyboard = {
'inline_keyboard': [[
{
'text': '打开应用',
'web_app': {
'url': f'https://your-mini-app.com?param={app_parameter}'
}
}
]]
}
await update.message.reply_text(
'点击按钮打开应用',
reply_markup=keyboard
)
Telegram Stars 支付
Telegram Stars 是 Telegram 的虚拟货币系统,支持小额支付。
创建 Stars 发票:
from telegram import LabeledPrice
await bot.send_invoice(
chat_id=chat_id,
title='高级订阅',
description='1 个月的高级功能访问',
payload='premium_subscription',
provider_token='',
currency='XTR',
prices=[
LabeledPrice('1 个月', 100),
LabeledPrice('3 个月', 250),
],
start_parameter='premium_start',
photo_url='https://example.com/premium.jpg',
photo_size=800,
photo_width=800,
photo_height=800,
is_flexible=False
)
处理预结账查询:
from telegram import PreCheckoutQuery
@bot.pre_checkout_query_handler
async def pre_checkout_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.pre_checkout_query
if await validate_order(query.invoice_payload, query.from_user.id):
await query.answer(ok=True)
else:
await query.answer(
ok=False,
error_message='订单验证失败,请联系客服'
)
async def validate_order(payload: str, user_id: int) -> bool:
"""验证订单有效性"""
return True
处理支付成功:
@bot.message_handler(content_types=['successful_payment'])
async def successful_payment_handler(message: Message):
payment = message.successful_payment
user_id = message.chat.id
payload = payment.invoice_payload
currency = payment.currency
total_amount = payment.total_amount
await process_payment(user_id, payload, total_amount)
await message.reply_text(
f'✅ 支付成功!\n'
f'支付: {total_amount} {currency}\n'
f'订单: {payload}'
)
async def process_payment(user_id: int, payload: str, amount: int):
"""处理支付后的业务逻辑"""
if payload == 'premium_subscription':
await activate_premium(user_id, duration_days=30)
elif payload == 'credits':
await add_credits(user_id, amount)
在 Mini App 中发起支付:
const tg = window.Telegram.WebApp;
tg.openInvoice("https://t.me/$invoice_link", (status) => {
if (status === "paid") {
console.log("支付成功");
tg.sendData(
JSON.stringify({
action: "payment_completed",
invoice_id: "...",
})
);
} else if (status === "cancelled") {
console.log("支付取消");
} else if (status === "pending") {
console.log("支付处理中");
} else if (status === "failed") {
console.log("支付失败");
}
});
消息编辑限制
Telegram 允许编辑消息,但有 48 小时的限制。
import datetime
from telegram.error import BadRequest
async def edit_message_safely(chat_id: int, message_id: int, new_text: str):
"""安全编辑消息,处理时间限制"""
try:
await bot.edit_message_text(
chat_id=chat_id,
message_id=message_id,
text=new_text
)
return True
except BadRequest as e:
error_msg = str(e)
if 'message is not modified' in error_msg:
print('消息内容未修改')
return True
elif 'message to edit not found' in error_msg:
print('消息不存在')
return False
elif "message can't be edited" in error_msg:
print('消息超过 48 小时,无法编辑')
await bot.send_message(
chat_id=chat_id,
text=f"(更新){new_text}"
)
return False
else:
print(f"编辑失败: {e}")
return False
获取消息信息:
message = await bot.send_message(chat_id, "测试消息")
message_time = message.date
now = datetime.datetime.now()
can_edit = (now - message_time).total_seconds() < 48 * 3600
if can_edit:
await message.edit_text("更新后的文本")
else:
await bot.send_message(chat_id, "新消息(原消息已过期无法编辑)")
API 端点:
https://api.telegram.org/bot<TOKEN>/METHOD_NAME
获取 Bot Token:
- 与 @BotFather 对话
- 发送
/newbot
- 按提示设置名称
- 获取 token
第一个 Bot (Python):
import requests
BOT_TOKEN = "your_bot_token_here"
API_URL = f"https://api.telegram.org/bot{BOT_TOKEN}"
def send_message(chat_id, text):
url = f"{API_URL}/sendMessage"
data = {"chat_id": chat_id, "text": text}
return requests.post(url, json=data)
def get_updates(offset=None):
url = f"{API_URL}/getUpdates"
params = {"offset": offset, "timeout": 30}
return requests.get(url, params=params).json()
offset = None
while True:
updates = get_updates(offset)
for update in updates.get("result", []):
chat_id = update["message"]["chat"]["id"]
text = update["message"]["text"]
send_message(chat_id, f"你说了:{text}")
offset = update["update_id"] + 1
核心 API 方法
更新管理:
getUpdates - 长轮询获取更新
setWebhook - 设置 Webhook
deleteWebhook - 删除 Webhook
getWebhookInfo - 查询 Webhook 状态
消息操作:
sendMessage - 发送文本消息
sendPhoto / sendVideo / sendDocument - 发送媒体
sendAudio / sendVoice - 发送音频
sendLocation / sendVenue - 发送位置
editMessageText - 编辑消息
deleteMessage - 删除消息
forwardMessage / copyMessage - 转发/复制消息
交互元素:
sendPoll - 发送投票(最多 12 个选项)
- 内联键盘 (InlineKeyboardMarkup)
- 回复键盘 (ReplyKeyboardMarkup)
answerCallbackQuery - 响应回调查询
文件操作:
getFile - 获取文件信息
downloadFile - 下载文件
- 支持最大 2GB 文件(本地 Bot API 模式)
支付功能:
sendInvoice - 发送发票
answerPreCheckoutQuery - 处理支付
- Telegram Stars 支付(最高 10,000 Stars)
Webhook 配置
设置 Webhook:
import requests
BOT_TOKEN = "your_token"
WEBHOOK_URL = "https://yourdomain.com/webhook"
requests.post(
f"https://api.telegram.org/bot{BOT_TOKEN}/setWebhook",
json={"url": WEBHOOK_URL}
)
Flask Webhook 示例:
from flask import Flask, request
import requests
app = Flask(__name__)
BOT_TOKEN = "your_token"
@app.route('/webhook', methods=['POST'])
def webhook():
update = request.get_json()
chat_id = update["message"]["chat"]["id"]
text = update["message"]["text"]
requests.post(
f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage",
json={"chat_id": chat_id, "text": f"收到: {text}"}
)
return "OK"
if __name__ == '__main__':
app.run(port=5000)
Mini App 核心 API
WebApp 对象主要属性:
tg.initData;
tg.initDataUnsafe;
tg.initDataUnsafe.user;
tg.themeParams;
tg.colorScheme;
tg.isExpanded;
tg.isFullscreen;
tg.viewportHeight;
tg.platform;
tg.version;
主要方法:
tg.ready();
tg.expand();
tg.close();
tg.requestFullscreen();
tg.sendData(data);
tg.openLink(url);
tg.openTelegramLink(url);
tg.showPopup(params, callback);
tg.showAlert(message);
tg.showConfirm(message);
tg.shareMessage(message);
tg.shareUrl(url);
UI 控件
主按钮 (MainButton):
tg.MainButton.setText("点击我");
tg.MainButton.show();
tg.MainButton.enable();
tg.MainButton.showProgress();
tg.MainButton.hideProgress();
tg.MainButton.onClick(() => {
console.log("主按钮被点击");
});