telegram

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Telegram Bot API - Integracao Profissional

Telegram Bot API - 专业集成指南

Overview

概述

Integracao completa com Telegram Bot API. Setup com BotFather, mensagens, webhooks, inline keyboards, grupos, canais. Boilerplates Node.js e Python.
与Telegram Bot API的完整集成。包含BotFather设置、消息、Webhooks、Inline键盘、群组、频道功能。提供Node.js和Python模板。

When to Use This Skill

何时使用此技能

  • When the user mentions "telegram" or related topics
  • When the user mentions "bot telegram" or related topics
  • When the user mentions "telegram bot" or related topics
  • When the user mentions "api telegram" or related topics
  • When the user mentions "chatbot telegram" or related topics
  • When the user mentions "mensagem telegram" or related topics
  • 当用户提及“telegram”或相关话题时
  • 当用户提及“bot telegram”或相关话题时
  • 当用户提及“telegram bot”或相关话题时
  • 当用户提及“api telegram”或相关话题时
  • 当用户提及“chatbot telegram”或相关话题时
  • 当用户提及“mensagem telegram”或相关话题时

Do Not Use This Skill When

何时不使用此技能

  • The task is unrelated to telegram
  • A simpler, more specific tool can handle the request
  • The user needs general-purpose assistance without domain expertise
  • 任务与Telegram无关时
  • 更简单、更特定的工具可处理请求时
  • 用户需要无领域专业知识的通用协助时

How It Works

工作原理

Skill para implementar bots profissionais no Telegram usando a Bot API oficial. Suporta Node.js/TypeScript e Python.
使用官方Bot API在Telegram上实现专业机器人的技能。支持Node.js/TypeScript和Python。

Overview

概述

A Telegram Bot API permite criar bots que interagem com usuarios via mensagens, comandos, inline keyboards, pagamentos e muito mais. Bots sao criados pelo @BotFather e autenticados via token unico.
Base URL:
https://api.telegram.org/bot<TOKEN>/METHOD_NAME
Metodos HTTP: GET e POST Formatos de parametros: query string, application/x-www-form-urlencoded, application/json, multipart/form-data (uploads) Limite de arquivos: 50MB download, 20MB upload (via multipart), 50MB via URL
Portas suportadas para webhooks: 443, 80, 88, 8443
Pre-requisitos:
  • Conta no Telegram
  • Bot criado via @BotFather (fornece o token)
  • Token no formato:
    123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11
Se o usuario nao tem um bot criado, oriente a conversar com @BotFather no Telegram e enviar
/newbot
.

Telegram Bot API允许创建通过消息、命令、Inline键盘、支付等方式与用户交互的机器人。机器人通过@BotFather创建,并通过唯一令牌进行身份验证。
基础URL:
https://api.telegram.org/bot<TOKEN>/METHOD_NAME
HTTP方法: GET 和 POST 参数格式: 查询字符串、application/x-www-form-urlencoded、application/json、multipart/form-data(上传) 文件限制: 下载50MB,上传20MB(通过multipart),通过URL上传50MB
Webhooks支持的端口: 443, 80, 88, 8443
前置条件:
  • Telegram账户
  • 通过@BotFather创建的机器人(提供令牌)
  • 令牌格式:
    123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11
如果用户尚未创建机器人,请指导其在Telegram中与@BotFather对话并发送
/newbot

Decision Tree

决策树

O usuario precisa criar um bot?
├── SIM → Secao "Setup com BotFather" abaixo
└── NAO → Qual linguagem?
    ├── Node.js/TypeScript
    └── Python
    → O que quer fazer?
       ├── Enviar mensagens → Secao "Tipos de Mensagem"
       ├── Receber mensagens → Secao "Receber Updates"
       ├── Teclados interativos → Secao "Keyboards"
       ├── Gerenciar grupos/canais → references/chat-management.md
       ├── Webhook setup → references/webhook-setup.md
       ├── Inline mode → references/advanced-features.md
       ├── Pagamentos → references/advanced-features.md
       ├── Bot de atendimento com IA → Secao "Automacao com IA"
       └── Referencia completa da API → references/api-reference.md
Para iniciar um projeto do zero com boilerplate pronto:
bash
python scripts/setup_project.py --language nodejs --path ./meu-bot-telegram
用户需要创建机器人吗?
├── 是 → 下方的“通过BotFather设置”章节
└── 否 → 使用哪种语言?
    ├── Node.js/TypeScript
    └── Python
    → 想要实现什么功能?
       ├── 发送消息 → “消息类型”章节
       ├── 接收消息 → “接收更新”章节
       ├── 交互式键盘 → “键盘”章节
       ├── 管理群组/频道 → references/chat-management.md
       ├── Webhook设置 → references/webhook-setup.md
       ├── Inline模式 → references/advanced-features.md
       ├── 支付功能 → references/advanced-features.md
       ├── AI客服机器人 → “AI自动化”章节
       └── API完整参考 → references/api-reference.md
从零开始使用现成模板启动项目:
bash
python scripts/setup_project.py --language nodejs --path ./meu-bot-telegram

Ou

或者

python scripts/setup_project.py --language python --path ./meu-bot-telegram

Para testar se o token do bot funciona:
```bash
python scripts/test_bot.py --token "SEU_TOKEN"
Para enviar uma mensagem de teste:
bash
python scripts/send_message.py --token "SEU_TOKEN" --chat-id "CHAT_ID" --text "Hello!"

python scripts/setup_project.py --language python --path ./meu-bot-telegram

测试机器人令牌是否可用:
```bash
python scripts/test_bot.py --token "SEU_TOKEN"
发送测试消息:
bash
python scripts/send_message.py --token "SEU_TOKEN" --chat-id "CHAT_ID" --text "Hello!"

Setup Com Botfather

通过BotFather设置

  1. Abra o Telegram e busque @BotFather
  2. Envie
    /newbot
  3. Escolha nome de exibicao (ex: "Meu Bot Incrivel")
  4. Escolha username (deve terminar com "bot", ex:
    meu_incrivel_bot
    )
  5. BotFather retorna o token - guarde com seguranca
  6. Comandos uteis do BotFather:
    • /setdescription
      - descricao do bot
    • /setabouttext
      - texto "sobre" do bot
    • /setuserpic
      - foto de perfil
    • /setcommands
      - lista de comandos
    • /mybots
      - gerenciar bots existentes
    • /setinline
      - habilitar inline mode
    • /setprivacy
      - modo privacidade em grupos

  1. 打开Telegram并搜索@BotFather
  2. 发送
    /newbot
  3. 选择显示名称(例如:"Meu Bot Incrivel")
  4. 选择用户名(必须以“bot”结尾,例如:
    meu_incrivel_bot
  5. BotFather返回令牌 - 请妥善保存
  6. BotFather实用命令:
    • /setdescription
      - 设置机器人描述
    • /setabouttext
      - 设置机器人“关于”文本
    • /setuserpic
      - 设置头像
    • /setcommands
      - 设置命令列表
    • /mybots
      - 管理现有机器人
    • /setinline
      - 启用Inline模式
    • /setprivacy
      - 设置群组隐私模式

Variaveis De Ambiente

环境变量

env
TELEGRAM_BOT_TOKEN=123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11
env
TELEGRAM_BOT_TOKEN=123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11

Node.Js/Typescript

Node.Js/Typescript

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();
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

Python

python
undefined
python
undefined

Instalar: Pip Install Python-Telegram-Bot Python-Dotenv

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()
undefined
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()
undefined

Sem Biblioteca (Http Puro)

无框架(纯HTTP)

python
import requests

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

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

Verificar Bot

Verificar Bot

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

Enviar Mensagem

Enviar Mensagem

r = requests.post(f"{BASE}/sendMessage", json={ "chat_id": "CHAT_ID", "text": "Hello from pure HTTP!", "parse_mode": "HTML" }) print(r.json())

---
r = requests.post(f"{BASE}/sendMessage", json={ "chat_id": "CHAT_ID", "text": "Hello from pure HTTP!", "parse_mode": "HTML" }) print(r.json())

---

Tipos De Mensagem

消息类型

O Telegram suporta diversos tipos de conteudo. Todos os metodos aceitam
chat_id
,
reply_parameters
(para responder),
reply_markup
(para keyboards),
disable_notification
e
protect_content
.
Telegram支持多种内容类型。所有方法均接受
chat_id
reply_parameters
(用于回复)、
reply_markup
(用于键盘)、
disable_notification
protect_content

Html (Recomendado)

Html(推荐)

await bot.send_message( chat_id=chat_id, text="<b>Negrito</b>, <i>italico</i>, <code>codigo</code>, <a href='https://example.com'>link</a>", parse_mode="HTML" )
await bot.send_message( chat_id=chat_id, text="<b>Negrito</b>, <i>italico</i>, <code>codigo</code>, <a href='https://example.com'>link</a>", parse_mode="HTML" )

Markdownv2 (Escapar Caracteres Especiais: _ * [ ] ( ) ~ ` > # + - = | { } . !)

Markdownv2(转义特殊字符: _ * [ ] ( ) ~ ` > # + - = | { } . !)

await bot.send_message( chat_id=chat_id, text="Negrito, italico,
codigo
, link", parse_mode="MarkdownV2" )
undefined
await bot.send_message( chat_id=chat_id, text="Negrito, italico,
codigo
, link", parse_mode="MarkdownV2" )
undefined

Foto (Por Url, File_Id Ou Upload)

图片(通过URL、File_Id或上传)

await bot.send_photo(chat_id, photo="https://example.com/img.jpg", caption="Legenda aqui")
await bot.send_photo(chat_id, photo="https://example.com/img.jpg", caption="Legenda aqui")

Documento

文档

await bot.send_document(chat_id, document=open("relatorio.pdf", "rb"), caption="Relatorio mensal")
await bot.send_document(chat_id, document=open("relatorio.pdf", "rb"), caption="Relatorio mensal")

Video

视频

await bot.send_video(chat_id, video="https://example.com/video.mp4", caption="Assista!")
await bot.send_video(chat_id, video="https://example.com/video.mp4", caption="Assista!")

Audio

音频

await bot.send_audio(chat_id, audio=open("musica.mp3", "rb"), title="Minha Musica")
await bot.send_audio(chat_id, audio=open("musica.mp3", "rb"), title="Minha Musica")

Voz (Ogg Com Opus)

语音(Ogg格式+Opus编码)

await bot.send_voice(chat_id, voice=open("audio.ogg", "rb"))
await bot.send_voice(chat_id, voice=open("audio.ogg", "rb"))

Localizacao

位置

await bot.send_location(chat_id, latitude=-23.5505, longitude=-46.6333)
await bot.send_location(chat_id, latitude=-23.5505, longitude=-46.6333)

Contato

联系人

await bot.send_contact(chat_id, phone_number="+5511999999999", first_name="Joao")
await bot.send_contact(chat_id, phone_number="+5511999999999", first_name="Joao")

Enquete

投票

await bot.send_poll( chat_id, question="Qual sua cor favorita?", options=["Azul", "Verde", "Vermelho"], is_anonymous=False )
await bot.send_poll( chat_id, question="Qual sua cor favorita?", options=["Azul", "Verde", "Vermelho"], is_anonymous=False )

Grupo De Midias

媒体组

await bot.send_media_group(chat_id, media=[ InputMediaPhoto("url1", caption="Foto 1"), InputMediaPhoto("url2"), InputMediaVideo("url3") ])
await bot.send_media_group(chat_id, media=[ InputMediaPhoto("url1", caption="Foto 1"), InputMediaPhoto("url2"), InputMediaVideo("url3") ])

Acao De Chat (Typing, Upload_Photo, Etc.)

聊天动作(输入中、上传图片等)

await bot.send_chat_action(chat_id, action="typing")
undefined
await bot.send_chat_action(chat_id, action="typing")
undefined

Node.Js Equivalente

Node.Js 等效代码

typescript
// 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']);

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

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

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

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

Inline Keyboard (Botoes Dentro Da Mensagem)

Inline键盘(消息内按钮)

python
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)
python
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))
undefined
async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE): query = update.callback_query await query.answer() # 重要:务必回复回调 await query.edit_message_text(f"Voce escolheu: {query.data}")
app.add_handler(CallbackQueryHandler(button_callback))
undefined

Reply Keyboard (Teclado Customizado)

Reply键盘(自定义键盘)

python
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)
python
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)

Remover Teclado

移除键盘

python
from telegram import ReplyKeyboardRemove
await bot.send_message(chat_id, "Teclado removido", reply_markup=ReplyKeyboardRemove())

python
from telegram import ReplyKeyboardRemove
await bot.send_message(chat_id, "Teclado removido", reply_markup=ReplyKeyboardRemove())

Receber Updates

接收更新

Existem duas formas de receber updates: Long Polling e Webhooks.
有两种接收更新的方式:长轮询(Long Polling)Webhooks

Long Polling (Desenvolvimento)

长轮询(开发环境)

Mais simples, ideal para desenvolvimento. O bot faz requisicoes periodicas ao servidor do Telegram.
python
undefined
更简单,适合开发。机器人定期向Telegram服务器发送请求。
python
undefined

Python-Telegram-Bot Ja Faz Isso Automaticamente

Python-Telegram-Bot 会自动处理

app.run_polling(allowed_updates=Update.ALL_TYPES)

```typescript
// Telegraf com polling
const bot = new Telegraf(token);
bot.launch();
app.run_polling(allowed_updates=Update.ALL_TYPES)

```typescript
// Telegraf 长轮询模式
const bot = new Telegraf(token);
bot.launch();

Webhooks (Producao)

Webhooks(生产环境)

Para producao, webhooks sao mais eficientes. O Telegram envia updates via POST para sua URL HTTPS.
Leia
references/webhook-setup.md
para configuracao completa com Express, Flask, ngrok e deploy.
Setup rapido:
python
undefined
对于生产环境,Webhooks更高效。Telegram通过POST请求将更新发送到你的HTTPS URL。
阅读
references/webhook-setup.md
获取使用Express、Flask、ngrok和部署的完整配置说明。
快速设置:
python
undefined

Flask Webhook

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(f"/webhook/{TOKEN}", 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
from flask import Flask, request import requests
app = Flask(name) TOKEN = "SEU_TOKEN" BASE = f"https://api.telegram.org/bot{TOKEN}"
@app.route(f"/webhook/{TOKEN}", 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

注册Webhook

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

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

---

Comandos Do Bot

机器人命令

Registre comandos para aparecerem no menu do Telegram:
python
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"),
])
Via HTTP:
bash
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"}]}'

注册命令以显示在Telegram菜单中:
python
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:
bash
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"}]}'

Automacao Com Ia

AI自动化

Padrao para bot de atendimento com IA (Claude, GPT, etc.):
python
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()

集成AI(Claude、GPT等)的客服机器人模板:
python
from telegram import Update
from telegram.ext import Application, MessageHandler, filters, ContextTypes
import anthropic  # 或 openai

client = anthropic.Anthropic()
user_conversations = {}  # chat_id -> 消息历史

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

    # 显示正在输入
    await context.bot.send_chat_action(chat_id, "typing")

    # 维护对话历史
    if chat_id not in user_conversations:
        user_conversations[chat_id] = []

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

    # 调用AI
    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})

    # 限制历史长度(最近20条消息)
    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()

Editar Texto

编辑文本

await bot.edit_message_text( chat_id=chat_id, message_id=msg.message_id, text="Texto atualizado!", parse_mode="HTML" )
await bot.edit_message_text( chat_id=chat_id, message_id=msg.message_id, text="Texto atualizado!", parse_mode="HTML" )

Editar Markup (Botoes)

编辑Markup(按钮)

await bot.edit_message_reply_markup( chat_id=chat_id, message_id=msg.message_id, reply_markup=new_keyboard )
await bot.edit_message_reply_markup( chat_id=chat_id, message_id=msg.message_id, reply_markup=new_keyboard )

Deletar Mensagem

删除消息

await bot.delete_message(chat_id=chat_id, message_id=msg.message_id)
await bot.delete_message(chat_id=chat_id, message_id=msg.message_id)

Encaminhar Mensagem

转发消息

await bot.forward_message( chat_id=dest_chat_id, from_chat_id=source_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 )

---

Tratamento De Erros

错误处理

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

python
from telegram.error import TelegramError, BadRequest, TimedOut, NetworkError

async def safe_send(bot, chat_id, text, **kwargs):
    """带重试机制的安全发送方法。"""
    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

Rate Limits

速率限制

  • Mensagens em chat privado: ~30 msg/segundo
  • Mensagens em grupo: ~20 msg/minuto por grupo
  • Broadcast geral: ~30 msg/segundo no total
  • Bulk notifications: use
    asyncio.sleep(0.05)
    entre envios para evitar flood
Se receber erro 429 (Too Many Requests), respeite o
retry_after
retornado.

  • 私聊消息: ~30条/秒
  • 群组消息: ~20条/分钟/群组
  • 全局广播: ~30条/秒(总计)
  • 批量通知: 发送间隔使用
    asyncio.sleep(0.05)
    以避免触发限流
如果收到429错误(请求过多),请遵循返回的
retry_after
参数指示的时间重试。

Referencia De Arquivos

文件参考

TopicoArquivo
Setup de webhooks
references/webhook-setup.md
Gerenciamento de chats
references/chat-management.md
Recursos avancados
references/advanced-features.md
Referencia completa da API
references/api-reference.md
Boilerplate Node.js
assets/boilerplate/nodejs/
Boilerplate Python
assets/boilerplate/python/
Exemplos de payloads
assets/examples/
主题文件
Webhooks设置
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/

Best Practices

最佳实践

  • Provide clear, specific context about your project and requirements
  • Review all suggestions before applying them to production code
  • Combine with other complementary skills for comprehensive analysis
  • 提供关于项目和需求的清晰、具体背景
  • 在应用到生产代码前审核所有建议
  • 结合其他互补技能进行全面分析

Common Pitfalls

常见陷阱

  • Using this skill for tasks outside its domain expertise
  • Applying recommendations without understanding your specific context
  • Not providing enough project context for accurate analysis
  • 将此技能用于其领域专业知识之外的任务
  • 在不了解具体背景的情况下应用建议
  • 未提供足够的项目背景以进行准确分析

Related Skills

相关技能

  • instagram
    - Complementary skill for enhanced analysis
  • social-orchestrator
    - Complementary skill for enhanced analysis
  • whatsapp-cloud-api
    - Complementary skill for enhanced analysis
  • instagram
    - 用于增强分析的互补技能
  • social-orchestrator
    - 用于增强分析的互补技能
  • whatsapp-cloud-api
    - 用于增强分析的互补技能

Limitations

局限性

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
  • 仅当任务明确符合上述描述的范围时使用此技能。
  • 不要将输出视为特定环境验证、测试或专家评审的替代品。
  • 如果缺少必要的输入、权限、安全边界或成功标准,请暂停并请求澄清。