| name | telegram-dev |
| description | Telegram 生態開發全棧指南 - 涵蓋 Bot API、Mini Apps (Web Apps)、MTProto 客戶端開發。包括訊息處理、支付、內聯模式、Webhook、認證、儲存、感測器 API 等完整開發資源。 |
Telegram 生態開發技能
全面的 Telegram 開發指南,涵蓋 Bot 開發、Mini Apps (Web Apps)、客戶端開發的完整技術棧。
何時使用此技能
當需要以下幫助時使用此技能:
- 開發 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 開發
快速開始
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)
Webhook 要求:
- 必須使用 HTTPS
- 支援 TLS 1.2+
- 埠:443, 80, 88, 8443
- 公共可訪問的 URL
內聯鍵盤
建立內聯鍵盤:
def send_inline_keyboard(chat_id):
keyboard = {
"inline_keyboard": [
[
{"text": "按鈕 1", "callback_data": "btn1"},
{"text": "按鈕 2", "callback_data": "btn2"}
],
[
{"text": "開啟連結", "url": "https://example.com"}
]
]
}
requests.post(
f"{API_URL}/sendMessage",
json={
"chat_id": chat_id,
"text": "選擇一個選項:",
"reply_markup": keyboard
}
)
處理回撥:
def handle_callback_query(callback_query):
query_id = callback_query["id"]
data = callback_query["data"]
chat_id = callback_query["message"]["chat"]["id"]
requests.post(
f"{API_URL}/answerCallbackQuery",
json={"callback_query_id": query_id, "text": f"你點選了 {data}"}
)
requests.post(
f"{API_URL}/editMessageText",
json={
"chat_id": chat_id,
"message_id": callback_query["message"]["message_id"],
"text": f"你選擇了:{data}"
}
)
內聯模式
配置內聯模式:
與 @BotFather 對話,傳送 /setinline
處理內聯查詢:
def handle_inline_query(inline_query):
query_id = inline_query["id"]
query_text = inline_query["query"]
results = [
{
"type": "article",
"id": "1",
"title": "結果 1",
"input_message_content": {
"message_text": f"你搜索了:{query_text}"
}
}
]
requests.post(
f"{API_URL}/answerInlineQuery",
json={"inline_query_id": query_id, "results": results}
)
Mini Apps (Web Apps) 開發
初始化 Mini App
HTML 模板:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://telegram.org/js/telegram-web-app.js"></script>
<title>My Mini App</title>
</head>
<body>
<h1>Telegram Mini App</h1>
<button id="mainBtn">主按鈕</button>
<script>
const tg = window.Telegram.WebApp;
tg.ready();
tg.expand();
const user = tg.initDataUnsafe?.user;
if (user) {
console.log("使用者名稱:", user.first_name);
console.log("使用者ID:", user.id);
}
tg.MainButton.text = "提交";
tg.MainButton.show();
tg.MainButton.onClick(() => {
tg.sendData(JSON.stringify({action: "submit"}));
});
tg.BackButton.show();
tg.BackButton.onClick(() => {
tg.close();
});
</script>
</body>
</html>
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("主按鈕被點選");
});
次要按鈕 (SecondaryButton):
tg.SecondaryButton.setText("取消");
tg.SecondaryButton.show();
tg.SecondaryButton.onClick(() => {
tg.close();
});
返回按鈕 (BackButton):
tg.BackButton.show();
tg.BackButton.onClick(() => {
});
觸覺反饋:
tg.HapticFeedback.impactOccurred('light');
tg.HapticFeedback.notificationOccurred('success');
tg.HapticFeedback.selectionChanged();
儲存 API
雲端儲存:
tg.CloudStorage.setItem('key', 'value', (error, success) => {
if (success) console.log('儲存成功');
});
tg.CloudStorage.getItem('key', (error, value) => {
console.log('值:', value);
});
tg.CloudStorage.removeItem('key');
tg.CloudStorage.getKeys((error, keys) => {
console.log('所有鍵:', keys);
});
本地儲存:
localStorage.setItem('key', 'value');
const value = localStorage.getItem('key');
tg.SecureStorage.setItem('secret', 'value', callback);
tg.SecureStorage.getItem('secret', callback);
生物識別認證
const bioManager = tg.BiometricManager;
bioManager.init(() => {
if (bioManager.isInited) {
console.log('支援的型別:', bioManager.biometricType);
if (bioManager.isAccessGranted) {
} else {
bioManager.requestAccess({reason: '需要驗證身份'}, (success) => {
if (success) {
console.log('授權成功');
}
});
}
}
});
bioManager.authenticate({reason: '確認操作'}, (success, token) => {
if (success) {
console.log('認證成功,token:', token);
}
});
位置和感測器
獲取位置:
tg.LocationManager.init(() => {
if (tg.LocationManager.isInited) {
tg.LocationManager.getLocation((location) => {
console.log('緯度:', location.latitude);
console.log('經度:', location.longitude);
});
}
});
加速度計:
tg.Accelerometer.start({refresh_rate: 100}, (started) => {
if (started) {
tg.Accelerometer.onEvent((event) => {
console.log('加速度:', event.x, event.y, event.z);
});
}
});
tg.Accelerometer.stop();
陀螺儀:
tg.Gyroscope.start({refresh_rate: 100}, callback);
tg.Gyroscope.onEvent((event) => {
console.log('旋轉速度:', event.x, event.y, event.z);
});
裝置方向:
tg.DeviceOrientation.start({refresh_rate: 100}, callback);
tg.DeviceOrientation.onEvent((event) => {
console.log('方向:', event.absolute, event.alpha, event.beta, event.gamma);
});
支付整合
發起支付 (Telegram Stars):
tg.openInvoice('https://t.me/$invoice_link', (status) => {
if (status === 'paid') {
console.log('支付成功');
} else if (status === 'cancelled') {
console.log('支付取消');
} else if (status === 'failed') {
console.log('支付失敗');
}
});
資料驗證
伺服器端驗證 initData (Python):
import hmac
import hashlib
from urllib.parse import parse_qs
def validate_init_data(init_data, bot_token):
parsed = parse_qs(init_data)
received_hash = parsed.get('hash', [''])[0]
data_check_arr = []
for key, value in parsed.items():
if key != 'hash':
data_check_arr.append(f"{key}={value[0]}")
data_check_arr.sort()
data_check_string = '\n'.join(data_check_arr)
secret_key = hmac.new(
b"WebAppData",
bot_token.encode(),
hashlib.sha256
).digest()
calculated_hash = hmac.new(
secret_key,
data_check_string.encode(),
hashlib.sha256
).hexdigest()
return calculated_hash == received_hash
啟動 Mini App
從鍵盤按鈕:
keyboard = {
"keyboard": [[
{
"text": "開啟應用",
"web_app": {"url": "https://yourdomain.com/app"}
}
]],
"resize_keyboard": True
}
requests.post(
f"{API_URL}/sendMessage",
json={
"chat_id": chat_id,
"text": "點選按鈕開啟應用",
"reply_markup": keyboard
}
)
從內聯按鈕:
keyboard = {
"inline_keyboard": [[
{
"text": "啟動應用",
"web_app": {"url": "https://yourdomain.com/app"}
}
]]
}
從選單按鈕:
與 @BotFather 對話:
/setmenubutton
→ 選擇你的 Bot
→ 提供 URL: https://yourdomain.com/app
客戶端開發 (TDLib)
使用 TDLib
Python 示例 (python-telegram):
from telegram.client import Telegram
tg = Telegram(
api_id='your_api_id',
api_hash='your_api_hash',
phone='+1234567890',
database_encryption_key='changeme1234',
)
tg.login()
result = tg.send_message(
chat_id=123456789,
text='Hello from TDLib!'
)
result = tg.get_chats()
result.wait()
chats = result.update
print(chats)
tg.stop()
MTProto 協議
特點:
最佳實踐
Bot 開發
-
錯誤處理
try:
response = requests.post(url, json=data, timeout=10)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"請求失敗: {e}")
-
速率限制
- 群組訊息:最多 20 條/分鐘
- 私聊訊息:最多 30 條/秒
- 全侷限制:避免過於頻繁
-
使用 Webhook 而非長輪詢
-
資料驗證
- 始終驗證 initData
- 不要信任客戶端資料
- 伺服器端驗證所有操作
Mini Apps 開發
-
響應式設計
tg.onEvent('themeChanged', () => {
document.body.style.backgroundColor = tg.themeParams.bg_color;
});
tg.onEvent('viewportChanged', () => {
console.log('新高度:', tg.viewportHeight);
});
-
效能最佳化
- 最小化 JavaScript 包大小
- 使用懶載入
- 最佳化圖片和資源
-
使用者體驗
- 適配深色/淺色主題
- 使用原生 UI 控制元件(MainButton 等)
- 提供觸覺反饋
- 快速響應使用者操作
-
安全考慮
- HTTPS 強制
- 驗證 initData
- 不在客戶端儲存敏感資訊
- 使用 SecureStorage 儲存金鑰
常用庫和工具
Python
python-telegram-bot - 功能強大的 Bot 框架
aiogram - 非同步 Bot 框架
telethon / pyrogram - MTProto 客戶端
Node.js
node-telegram-bot-api - Bot API 包裝器
telegraf - 現代 Bot 框架
grammy - 輕量級框架
其他語言
- PHP:
telegram-bot-sdk
- Go:
telegram-bot-api
- Java:
TelegramBots
- C#:
Telegram.Bot
參考資源
官方文件
GitHub 倉庫
工具
參考檔案
此技能包含詳細的 Telegram 開發資源索引和完整實現模板:
- index.md - 完整的資源連結和快速導航
- Telegram_Bot_按鈕和鍵盤實現模板.md - 互動式按鈕和鍵盤實現指南(404 行,12 KB)
- 三種按鈕型別詳解(Inline/Reply/Command Menu)
- python-telegram-bot 和 Telethon 雙實現對比
- 完整的即用程式碼示例和專案結構
- Handler 系統、錯誤處理和部署方案
- 動態檢視對齊實現文件.md - Telegram 資料展示指南(407 行,12 KB)
- 智慧動態對齊演算法(三步法,O(n×m) 複雜度)
- 等寬字型環境的完美對齊方案
- 智慧數值格式化系統(B/M/K 自動縮寫)
- 排行榜和資料表格專業展示
這些精簡指南提供了核心的 Telegram Bot 開發解決方案:
- 按鈕和鍵盤互動的所有實現方式
- 訊息和資料的專業格式化展示
- 實用的最佳實踐和快速參考
使用此技能掌握 Telegram 生態的全棧開發!