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 --language nodejs --path ./meu-bot-telegram

## 或

python scripts/setup_project.py --language python --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 设置

  1. 打开 Telegram 并搜索 @BotFather
  2. 发送 /newbot
  3. 选择显示名称(例如:“我的超棒机器人”)
  4. 选择用户名(必须以"bot"结尾,例如:meu_incrivel_bot)
  5. BotFather 返回令牌 - 安全保存
  6. BotFather 的实用命令:
    • /setdescription - 机器人描述
    • /setabouttext - 机器人"关于"文本
    • /setuserpic - 个人资料照片
    • /setcommands - 命令列表
    • /mybots - 管理现有机器人
    • /setinline - 启用内联模式
    • /setprivacy - 群组中的隐私模式

环境变量

TELEGRAM_BOT_TOKEN=123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11

Node.Js/TypeScript

// Instalar: npm install telegraf dotenv
// Para TypeScript: npm install -D typescript
import { Telegraf } from 'telegraf';
import dotenv from 'dotenv';
dotenv.config();

const bot = new Telegraf(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-Dotenv

import os
from dotenv import load_dotenv
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes

load_dotenv()

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text('Ola! Eu sou seu bot. Como posso ajudar?')

async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.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)

import requests

TOKEN = "SEU_TOKEN"
BASE = f"https://api.telegram.org/bot{TOKEN}"

## Verificar Bot

r = requests.get(f"{BASE}/getMe")
print(r.json())

## Enviar Mensagem

r = 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 等效实现

// Foto
bot.sendPhoto(chatId, 'https://example.com/img.jpg', { caption: 'Legenda' });

// Documento
bot.sendDocument(chatId, fs.createReadStream('relatorio.pdf'), { caption: 'Relatorio' });

// Localizacao
bot.sendLocation(chatId, -23.5505, -46.6333);

// Enquete
bot.sendPoll(chatId, 'Qual sua cor favorita?', ['Azul', 'Verde', 'Vermelho']);

内联键盘(消息内的按钮)

from telegram import InlineKeyboardButton, 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")]
])

await bot.send_message(chat_id, "Escolha uma opcao:", reply_markup=keyboard)

## Handler De Callback

async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()  # Importante: sempre responder o callback
    await query.edit_message_text(f"Voce escolheu: {query.data}")

app.add_handler(CallbackQueryHandler(button_callback))

回复键盘(自定义键盘)

from telegram import ReplyKeyboardMarkup, 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
)

await bot.send_message(chat_id, "Escolha:", reply_markup=keyboard)

移除键盘

from telegram import ReplyKeyboardRemove
await bot.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 polling
const bot = new Telegraf(token);
bot.launch();

Webhooks(生产)

对于生产环境,webhook 更高效。Telegram 通过 POST 将更新发送到你的 HTTPS URL。

阅读 references/webhook-setup.md 获取使用 Express、Flask、ngrok 和部署的完整配置。

快速设置:


## Flask Webhook

from flask import Flask, request
import requests

app = Flask(__name__)
TOKEN = "SEU_TOKEN"
BASE = f"https://api.telegram.org/bot{TOKEN}"

@app.route("/webhook", methods=["POST"])
def webhook():
    update = request.get_json()
    if "message" in update and "text" in update["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 Webhook

requests.post(f"{BASE}/setWebhook", json={
    "url": "https://seu-dominio.com/webhook",
    "allowed_updates": ["message", "callback_query"],
    "secret_token": "seu_secret_seguro_aqui"
})

机器人命令

注册命令以显示在 Telegram 菜单中:

from telegram import BotCommand

await bot.set_my_commands([
    BotCommand("start", "Iniciar o bot"),
    BotCommand("help", "Ver comandos disponiveis"),
    BotCommand("settings", "Configuracoes"),
    BotCommand("status", "Ver status do servico"),
])

通过 HTTP:

curl -X POST "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 等)的模式:

from telegram import Update
from telegram.ext import Application, MessageHandler, filters, ContextTypes
import anthropic  # ou openai

client = anthropic.Anthropic()
user_conversations = {}  # chat_id -> messages history

async def ai_response(update: Update, context: ContextTypes.DEFAULT_TYPE):
    chat_id = update.message.chat_id
    user_text = update.message.text

    # Indicar que esta digitando
    await context.bot.send_chat_action(chat_id, "typing")

    # Manter historico
    if chat_id not in user_conversations:
        user_conversations[chat_id] = []

    user_conversations[chat_id].append({"role": "user", "content": user_text})

    # Chamar IA
    response = 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)
    if len(user_conversations[chat_id]) > 20:
        user_conversations[chat_id] = user_conversations[chat_id][-20:]

    await update.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 - 用于增强分析的互补技能

局限性

  • 仅在任务明确匹配上述范围时使用此技能。
  • 不要将输出视为环境特定验证、测试或专家审查的替代品。
  • 如果缺少所需的输入、权限、安全边界或成功标准,请停下来询问澄清。
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐