원클릭으로
telegram-dev
Telegram 生態開發全棧指南 - 涵蓋 Bot API、Mini Apps (Web Apps)、MTProto 客戶端開發。包括訊息處理、支付、內聯模式、Webhook、認證、儲存、感測器 API 等完整開發資源。
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
메뉴
Telegram 生態開發全棧指南 - 涵蓋 Bot API、Mini Apps (Web Apps)、MTProto 客戶端開發。包括訊息處理、支付、內聯模式、Webhook、認證、儲存、感測器 API 等完整開發資源。
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
SOC 직업 분류 기준
Claude Code 高階開發指南 - 全面的中文教程,涵蓋工具使用、REPL 環境、開發工作流、MCP 整合、高階模式和最佳實踐。適合學習 Claude Code 的高階功能和開發技巧。
Auto-detect network issues and force proxy usage with proxychains4. Use this skill when encountering connection timeouts, DNS failures, or blocked network access. Default proxy is http://127.0.0.1:9910
| name | telegram-dev |
| description | Telegram 生態開發全棧指南 - 涵蓋 Bot API、Mini Apps (Web Apps)、MTProto 客戶端開發。包括訊息處理、支付、內聯模式、Webhook、認證、儲存、感測器 API 等完整開發資源。 |
全面的 Telegram 開發指南,涵蓋 Bot 開發、Mini Apps (Web Apps)、客戶端開發的完整技術棧。
當需要以下幫助時使用此技能:
Bot API - 建立機器人程式
Mini Apps API (Web Apps) - 建立 Web 應用
Telegram API & TDLib - 建立客戶端
API 端點:
https://api.telegram.org/bot<TOKEN>/METHOD_NAME
獲取 Bot Token:
/newbot第一個 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
更新管理:
getUpdates - 長輪詢獲取更新setWebhook - 設定 WebhookdeleteWebhook - 刪除 WebhookgetWebhookInfo - 查詢 Webhook 狀態訊息操作:
sendMessage - 傳送文字訊息sendPhoto / sendVideo / sendDocument - 傳送媒體sendAudio / sendVoice - 傳送音訊sendLocation / sendVenue - 傳送位置editMessageText - 編輯訊息deleteMessage - 刪除訊息forwardMessage / copyMessage - 轉發/複製訊息互動元素:
sendPoll - 傳送投票(最多 12 個選項)answerCallbackQuery - 響應回撥查詢檔案操作:
getFile - 獲取檔案資訊downloadFile - 下載檔案支付功能:
sendInvoice - 傳送發票answerPreCheckoutQuery - 處理支付設定 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 要求:
建立內聯鍵盤:
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}
)
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>
// 獲取 Telegram WebApp 物件
const tg = window.Telegram.WebApp;
// 通知 Telegram 應用已準備好
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(() => {
// 傳送資料到 Bot
tg.sendData(JSON.stringify({action: "submit"}));
});
// 新增返回按鈕
tg.BackButton.show();
tg.BackButton.onClick(() => {
tg.close();
});
</script>
</body>
</html>
WebApp 物件主要屬性:
// 初始化資料
tg.initData // 原始初始化字串
tg.initDataUnsafe // 解析後的物件
// 使用者和主題
tg.initDataUnsafe.user // 使用者資訊
tg.themeParams // 主題顏色
tg.colorScheme // 'light' 或 'dark'
// 狀態
tg.isExpanded // 是否全屏
tg.isFullscreen // 是否全屏
tg.viewportHeight // 視口高度
tg.platform // 平臺型別
// 版本
tg.version // WebApp 版本
主要方法:
// 視窗控制
tg.ready() // 標記應用準備就緒
tg.expand() // 展開到全高度
tg.close() // 關閉 Mini App
tg.requestFullscreen() // 請求全屏
// 資料傳送
tg.sendData(data) // 傳送資料到 Bot
// 導航
tg.openLink(url) // 開啟外部連結
tg.openTelegramLink(url) // 開啟 Telegram 連結
// 對話方塊
tg.showPopup(params, callback) // 顯示彈窗
tg.showAlert(message) // 顯示警告
tg.showConfirm(message) // 顯示確認
// 分享
tg.shareMessage(message) // 分享訊息
tg.shareUrl(url) // 分享連結
主按鈕 (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'); // light, medium, heavy
tg.HapticFeedback.notificationOccurred('success'); // success, warning, error
tg.HapticFeedback.selectionChanged();
雲端儲存:
// 儲存資料
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);
// 'finger', 'face', 'unknown'
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]
# 移除 hash
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
從鍵盤按鈕:
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
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()
特點:
錯誤處理
try:
response = requests.post(url, json=data, timeout=10)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"請求失敗: {e}")
速率限制
使用 Webhook 而非長輪詢
資料驗證
響應式設計
// 監聽主題變化
tg.onEvent('themeChanged', () => {
document.body.style.backgroundColor = tg.themeParams.bg_color;
});
// 監聽視口變化
tg.onEvent('viewportChanged', () => {
console.log('新高度:', tg.viewportHeight);
});
效能最佳化
使用者體驗
安全考慮
python-telegram-bot - 功能強大的 Bot 框架aiogram - 非同步 Bot 框架telethon / pyrogram - MTProto 客戶端node-telegram-bot-api - Bot API 包裝器telegraf - 現代 Bot 框架grammy - 輕量級框架telegram-bot-sdktelegram-bot-apiTelegramBotsTelegram.Bot此技能包含詳細的 Telegram 開發資源索引和完整實現模板:
這些精簡指南提供了核心的 Telegram Bot 開發解決方案:
使用此技能掌握 Telegram 生態的全棧開發!