name: telegram
description: Integracao completa com Telegram Bot API. Setup com BotFather, mensagens, webhooks, inline keyboards, grupos, canais. Boilerplates Node.js e Python.
risk: critical
source: community
date_added: ‘2026-03-06’
author: renat
tags:
- messaging
- telegram
- bots
- webhooks
tools: - claude-code
- antigravity
- cursor
- gemini-cli
- codex-cli
Telegram Bot API - 专业集成
概述
与 Telegram Bot API 的完整集成。使用 BotFather 设置、消息、webhook、内联键盘、群组、频道。提供 Node.js 和 Python 样板代码。
何时使用此技能
- 当用户提到"telegram"或相关主题时
- 当用户提到"bot telegram"或相关主题时
- 当用户提到"telegram bot"或相关主题时
- 当用户提到"api telegram"或相关主题时
- 当用户提到"chatbot telegram"或相关主题时
- 当用户提到"mensagem telegram"或相关主题时
何时不使用此技能
- 任务与 telegram 无关时
- 更简单、更具体的工具可以处理该请求时
- 用户需要无领域专长的通用帮助时
工作原理
使用官方 Bot API 在 Telegram 上实现专业机器人的技能。支持 Node.js/TypeScript 和 Python。
概述
Telegram Bot API 允许创建通过消息、命令、内联键盘、支付等与用户交互的机器人。机器人由 @BotFather 创建,并通过唯一令牌进行认证。
Base URL:https://api.telegram.org/bot<TOKEN>/METHOD_NAME
HTTP 方法:GET 和 POST
参数格式:query string、application/x-www-form-urlencoded、application/json、multipart/form-data(上传)
文件限制:下载 50MB,上传 20MB(通过 multipart),通过 URL 50MB
Webhook 支持的端口:443、80、88、8443
前置条件:
- Telegram 账户
- 通过 @BotFather 创建的机器人(提供令牌)
- 令牌格式:
123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11
如果用户还没有创建机器人,请指导他们在 Telegram 中与 @BotFather 对话并发送/newbot。
决策树
用户需要创建机器人吗? ├── 是 → 下方"使用 BotFather 设置"部分 └── 否 → 使用什么语言? ├── Node.js/TypeScript └── Python → 想做什么? ├── 发送消息 → "消息类型"部分 ├── 接收消息 → "接收更新"部分 ├── 交互式键盘 → "键盘"部分 ├── 管理群组/频道 → references/chat-management.md ├── Webhook 设置 → references/webhook-setup.md ├── 内联模式 → references/advanced-features.md ├── 支付 → references/advanced-features.md ├── AI 客服机器人 → "AI 自动化"部分 └── 完整 API 参考 → references/api-reference.md要用现成样板从零开始项目:
python scripts/setup_project.py--languagenodejs--path./meu-bot-telegram## 或python scripts/setup_project.py--languagepython--path./meu-bot-telegram要测试机器人令牌是否有效:
python scripts/test_bot.py--token"SEU_TOKEN"要发送测试消息:
python scripts/send_message.py--token"SEU_TOKEN"--chat-id"CHAT_ID"--text"Hello!"使用 BotFather 设置
- 打开 Telegram 并搜索 @BotFather
- 发送
/newbot - 选择显示名称(例如:“我的超棒机器人”)
- 选择用户名(必须以"bot"结尾,例如:
meu_incrivel_bot) - BotFather 返回令牌 - 安全保存
- BotFather 的实用命令:
/setdescription- 机器人描述/setabouttext- 机器人"关于"文本/setuserpic- 个人资料照片/setcommands- 命令列表/mybots- 管理现有机器人/setinline- 启用内联模式/setprivacy- 群组中的隐私模式
环境变量
TELEGRAM_BOT_TOKEN=123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11Node.Js/TypeScript
// Instalar: npm install telegraf dotenv// Para TypeScript: npm install -D typescriptimport{Telegraf}from'telegraf';importdotenvfrom'dotenv';dotenv.config();constbot=newTelegraf(process.env.TELEGRAM_BOT_TOKEN!);bot.start((ctx)=>{ctx.reply('Ola! Eu sou seu bot. Como posso ajudar?');});bot.on('text',(ctx)=>{if(!ctx.message.text.startsWith('/')){ctx.reply(`Voce disse:${ctx.message.text}`);}});bot.launch();Python
## Instalar: Pip Install Python-Telegram-Bot Python-Dotenvimportosfromdotenvimportload_dotenvfromtelegramimportUpdatefromtelegram.extimportApplication,CommandHandler,MessageHandler,filters,ContextTypes load_dotenv()asyncdefstart(update:Update,context:ContextTypes.DEFAULT_TYPE):awaitupdate.message.reply_text('Ola! Eu sou seu bot. Como posso ajudar?')asyncdefecho(update:Update,context:ContextTypes.DEFAULT_TYPE):awaitupdate.message.reply_text(f'Voce disse:{update.message.text}')app=Application.builder().token(os.getenv('TELEGRAM_BOT_TOKEN')).build()app.add_handler(CommandHandler('start',start))app.add_handler(MessageHandler(filters.TEXT&~filters.COMMAND,echo))app.run_polling()不使用库(纯 HTTP)
importrequests TOKEN="SEU_TOKEN"BASE=f"https://api.telegram.org/bot{TOKEN}"## Verificar Botr=requests.get(f"{BASE}/getMe")print(r.json())## Enviar Mensagemr=requests.post(f"{BASE}/sendMessage",json={"chat_id":"CHAT_ID","text":"Hello from pure HTTP!","parse_mode":"HTML"})print(r.json())消息类型
Telegram 支持多种内容类型。所有方法都接受chat_id、reply_parameters(用于回复)、reply_markup(用于键盘)、disable_notification和protect_content。
HTML(推荐)
await bot.send_message(
chat_id=chat_id,
text=“Negrito,italico,codigo, link”,
parse_mode=“HTML”
)
MarkdownV2(转义特殊字符:_ * [ ] ( ) ~ ` > # + - = | { } . !)
await bot.send_message(
chat_id=chat_id,
text=“Negrito,italico,codigo, link”,
parse_mode=“MarkdownV2”
)
## 照片(按 URL、File_Id 或上传) await bot.send_photo(chat_id, photo="https://example.com/img.jpg", caption="Legenda aqui") ## 文档 await bot.send_document(chat_id, document=open("relatorio.pdf", "rb"), caption="Relatorio mensal") ## 视频 await bot.send_video(chat_id, video="https://example.com/video.mp4", caption="Assista!") ## 音频 await bot.send_audio(chat_id, audio=open("musica.mp3", "rb"), title="Minha Musica") ## 语音(带 Opus 的 Ogg) await bot.send_voice(chat_id, voice=open("audio.ogg", "rb")) ## 位置 await bot.send_location(chat_id, latitude=-23.5505, longitude=-46.6333) ## 联系人 await bot.send_contact(chat_id, phone_number="+5511999999999", first_name="Joao") ## 投票 await bot.send_poll( chat_id, question="Qual sua cor favorita?", options=["Azul", "Verde", "Vermelho"], is_anonymous=False ) ## 媒体组 await bot.send_media_group(chat_id, media=[ InputMediaPhoto("url1", caption="Foto 1"), InputMediaPhoto("url2"), InputMediaVideo("url3") ]) ## 聊天动作(打字、上传照片等) await bot.send_chat_action(chat_id, action="typing")Node.Js 等效实现
// Fotobot.sendPhoto(chatId,'https://example.com/img.jpg',{caption:'Legenda'});// Documentobot.sendDocument(chatId,fs.createReadStream('relatorio.pdf'),{caption:'Relatorio'});// Localizacaobot.sendLocation(chatId,-23.5505,-46.6333);// Enquetebot.sendPoll(chatId,'Qual sua cor favorita?',['Azul','Verde','Vermelho']);内联键盘(消息内的按钮)
fromtelegramimportInlineKeyboardButton,InlineKeyboardMarkup keyboard=InlineKeyboardMarkup([[InlineKeyboardButton("Opcao A",callback_data="opt_a"),InlineKeyboardButton("Opcao B",callback_data="opt_b")],[InlineKeyboardButton("Abrir Site",url="https://example.com")],[InlineKeyboardButton("Compartilhar",switch_inline_query="texto")]])awaitbot.send_message(chat_id,"Escolha uma opcao:",reply_markup=keyboard)## Handler De Callbackasyncdefbutton_callback(update:Update,context:ContextTypes.DEFAULT_TYPE):query=update.callback_queryawaitquery.answer()# Importante: sempre responder o callbackawaitquery.edit_message_text(f"Voce escolheu:{query.data}")app.add_handler(CallbackQueryHandler(button_callback))回复键盘(自定义键盘)
fromtelegramimportReplyKeyboardMarkup,KeyboardButton keyboard=ReplyKeyboardMarkup([[KeyboardButton("Enviar Localizacao",request_location=True)],[KeyboardButton("Enviar Contato",request_contact=True)],["Opcao 1","Opcao 2"]],resize_keyboard=True,one_time_keyboard=True)awaitbot.send_message(chat_id,"Escolha:",reply_markup=keyboard)移除键盘
fromtelegramimportReplyKeyboardRemoveawaitbot.send_message(chat_id,"Teclado removido",reply_markup=ReplyKeyboardRemove())接收更新
有两种接收更新的方式:长轮询(Long Polling)和Webhooks。
长轮询(开发)
更简单,适合开发。机器人定期向 Telegram 服务器发起请求。
## Python-Telegram-Bot 已自动处理app.run_polling(allowed_updates=Update.ALL_TYPES)// Telegraf com pollingconstbot=newTelegraf(token);bot.launch();Webhooks(生产)
对于生产环境,webhook 更高效。Telegram 通过 POST 将更新发送到你的 HTTPS URL。
阅读references/webhook-setup.md获取使用 Express、Flask、ngrok 和部署的完整配置。
快速设置:
## Flask WebhookfromflaskimportFlask,requestimportrequests app=Flask(__name__)TOKEN="SEU_TOKEN"BASE=f"https://api.telegram.org/bot{TOKEN}"@app.route("/webhook",methods=["POST"])defwebhook():update=request.get_json()if"message"inupdateand"text"inupdate["message"]:chat_id=update["message"]["chat"]["id"]text=update["message"]["text"]requests.post(f"{BASE}/sendMessage",json={"chat_id":chat_id,"text":f"Recebi:{text}"})return"OK",200## Registrar Webhookrequests.post(f"{BASE}/setWebhook",json={"url":"https://seu-dominio.com/webhook","allowed_updates":["message","callback_query"],"secret_token":"seu_secret_seguro_aqui"})机器人命令
注册命令以显示在 Telegram 菜单中:
fromtelegramimportBotCommandawaitbot.set_my_commands([BotCommand("start","Iniciar o bot"),BotCommand("help","Ver comandos disponiveis"),BotCommand("settings","Configuracoes"),BotCommand("status","Ver status do servico"),])通过 HTTP:
curl-XPOST"https://api.telegram.org/bot$TOKEN/setMyCommands"\-H"Content-Type: application/json"\-d'{"commands":[{"command":"start","description":"Iniciar o bot"},{"command":"help","description":"Ajuda"}]}'使用 AI 自动化
AI 客服机器人(Claude、GPT 等)的模式:
fromtelegramimportUpdatefromtelegram.extimportApplication,MessageHandler,filters,ContextTypesimportanthropic# ou openaiclient=anthropic.Anthropic()user_conversations={}# chat_id -> messages historyasyncdefai_response(update:Update,context:ContextTypes.DEFAULT_TYPE):chat_id=update.message.chat_id user_text=update.message.text# Indicar que esta digitandoawaitcontext.bot.send_chat_action(chat_id,"typing")# Manter historicoifchat_idnotinuser_conversations:user_conversations[chat_id]=[]user_conversations[chat_id].append({"role":"user","content":user_text})# Chamar IAresponse=client.messages.create(model="claude-sonnet-4-20250514",max_tokens=1024,system="Voce e um assistente prestativo. Responda em portugues.",messages=user_conversations[chat_id])reply=response.content[0].text user_conversations[chat_id].append({"role":"assistant","content":reply})# Limitar historico (ultimas 20 mensagens)iflen(user_conversations[chat_id])>20:user_conversations[chat_id]=user_conversations[chat_id][-20:]awaitupdate.message.reply_text(reply)app=Application.builder().token(TOKEN).build()app.add_handler(MessageHandler(filters.TEXT&~filters.COMMAND,ai_response))app.run_polling()编辑文本
await bot.edit_message_text(
chat_id=chat_id,
message_id=msg.message_id,
text=“Texto atualizado!”,
parse_mode=“HTML”
)
编辑标记(按钮)
await bot.edit_message_reply_markup(
chat_id=chat_id,
message_id=msg.message_id,
reply_markup=new_keyboard
)
删除消息
await bot.delete_message(chat_id=chat_id, message_id=msg.message_id)
转发消息
await bot.forward_message(
chat_id=dest_chat_id,
from_chat_id=source_chat_id,
message_id=msg.message_id
)
--- ## 错误处理 ```python from telegram.error import TelegramError, BadRequest, TimedOut, NetworkError async def safe_send(bot, chat_id, text, **kwargs): """Envio com retry e tratamento de erros.""" max_retries = 3 for attempt in range(max_retries): try: return await bot.send_message(chat_id, text, **kwargs) except TimedOut: if attempt < max_retries - 1: await asyncio.sleep(2 ** attempt) continue raise except BadRequest as e: if "chat not found" in str(e).lower(): print(f"Chat {chat_id} nao encontrado") return None raise except NetworkError: if attempt < max_retries - 1: await asyncio.sleep(2 ** attempt) continue raise速率限制
- 私聊消息:~30 条/秒
- 群组消息:每群组 ~20 条/分钟
- 整体广播:总计 ~30 条/秒
- 批量通知:在发送之间使用
asyncio.sleep(0.05)以避免触发风控
如果收到 429 错误(请求过多),请遵循返回的retry_after。
文件参考
| 主题 | 文件 |
|---|---|
| Webhook 设置 | references/webhook-setup.md |
| 聊天管理 | references/chat-management.md |
| 高级功能 | references/advanced-features.md |
| 完整 API 参考 | references/api-reference.md |
| Node.js 样板 | assets/boilerplate/nodejs/ |
| Python 样板 | assets/boilerplate/python/ |
| 负载示例 | assets/examples/ |
最佳实践
- 提供关于项目和需求的清晰、具体的上下文
- 在应用到生产代码之前审查所有建议
- 与其他互补技能结合以获得全面分析
常见陷阱
- 将此技能用于其领域专长之外的任务
- 在不理解你的具体上下文的情况下应用建议
- 未提供足够的项目上下文以进行准确分析
相关技能
instagram- 用于增强分析的互补技能social-orchestrator- 用于增强分析的互补技能whatsapp-cloud-api- 用于增强分析的互补技能
局限性
- 仅在任务明确匹配上述范围时使用此技能。
- 不要将输出视为环境特定验证、测试或专家审查的替代品。
- 如果缺少所需的输入、权限、安全边界或成功标准,请停下来询问澄清。