telegram
Integracao completa com Telegram Bot API. Setup com BotFather, mensagens, webhooks, inline keyboards, grupos, canais. Boilerplates Node.js e Python.
Best use case
telegram is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Integracao completa com Telegram Bot API. Setup com BotFather, mensagens, webhooks, inline keyboards, grupos, canais. Boilerplates Node.js e Python.
Teams using telegram should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/telegram/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How telegram Compares
| Feature / Agent | telegram | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Integracao completa com Telegram Bot API. Setup com BotFather, mensagens, webhooks, inline keyboards, grupos, canais. Boilerplates Node.js e Python.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Telegram Bot API - Integracao Profissional
## Overview
Integracao completa com Telegram Bot API. Setup com BotFather, mensagens, webhooks, inline keyboards, grupos, canais. Boilerplates Node.js e 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
## 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
## How It Works
Skill para implementar bots profissionais no Telegram usando a Bot API oficial. Suporta Node.js/TypeScript e 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`.
---
## 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
## 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!"
```
---
## Setup Com 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
---
## Variaveis De Ambiente
```env
TELEGRAM_BOT_TOKEN=123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11
```
## Node.Js/Typescript
```typescript
// Instalar: npm install node-telegram-bot-api dotenv
// Para TypeScript: npm install -D @types/node-telegram-bot-api typescript
import TelegramBot from 'node-telegram-bot-api';
import dotenv from 'dotenv';
dotenv.config();
const bot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN!, { polling: true });
bot.onText(/\/start/, (msg) => {
bot.sendMessage(msg.chat.id, 'Ola! Eu sou seu bot. Como posso ajudar?');
});
bot.on('message', (msg) => {
if (msg.text && !msg.text.startsWith('/')) {
bot.sendMessage(msg.chat.id, `Voce disse: ${msg.text}`);
}
});
```
## Python
```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()
```
## Sem Biblioteca (Http Puro)
```python
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())
```
---
## 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`.
## Html (Recomendado)
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: _ * [ ] ( ) ~ ` > # + - = | { } . !)
await bot.send_message(
chat_id=chat_id,
text="*Negrito*, _italico_, `codigo`, [link](https://example\\.com)",
parse_mode="MarkdownV2"
)
```
## Foto (Por Url, File_Id Ou Upload)
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")
## Video
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")
## Voz (Ogg Com Opus)
await bot.send_voice(chat_id, voice=open("audio.ogg", "rb"))
## Localizacao
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")
## Enquete
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")
])
## Acao De Chat (Typing, Upload_Photo, Etc.)
await bot.send_chat_action(chat_id, action="typing")
```
## Node.Js Equivalente
```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']);
```
---
## Inline Keyboard (Botoes Dentro Da Mensagem)
```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))
```
## Reply Keyboard (Teclado Customizado)
```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())
```
---
## Receber Updates
Existem duas formas de receber updates: **Long Polling** e **Webhooks**.
## Long Polling (Desenvolvimento)
Mais simples, ideal para desenvolvimento. O bot faz requisicoes periodicas ao servidor do Telegram.
```python
## Python-Telegram-Bot Ja Faz Isso Automaticamente
app.run_polling(allowed_updates=Update.ALL_TYPES)
```
```typescript
// node-telegram-bot-api com polling
const bot = new TelegramBot(token, { polling: true });
```
## Webhooks (Producao)
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
## 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
## Registrar 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"
})
```
---
## 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"}]}'
```
---
## Automacao Com Ia
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()
```
---
## Editar Texto
await bot.edit_message_text(
chat_id=chat_id,
message_id=msg.message_id,
text="Texto atualizado!",
parse_mode="HTML"
)
## Editar Markup (Botoes)
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)
## Encaminhar Mensagem
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
```
---
## 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.
---
## Referencia De Arquivos
| Topico | Arquivo |
|--------|---------|
| 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/` |
## 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
## 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.Related Skills
telegram-mini-app
Expert in building Telegram Mini Apps (TWA) - web apps that run inside Telegram with native-like experience. Covers the TON ecosystem, Telegram Web App API, payments, user authentication, and building viral mini apps that monetize.
telegram-bot-builder
Expert in building Telegram bots that solve real problems - from simple automation to complex AI-powered bots. Covers bot architecture, the Telegram Bot API, user experience, monetization strategies, and scaling bots to thousands of users.
telegram-automation
Automate Telegram tasks via Rube MCP (Composio): send messages, manage chats, share photos/documents, and handle bot commands. Always search tools first for current schemas.
find-skills
Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.
vercel-cli-with-tokens
Deploy and manage projects on Vercel using token-based authentication. Use when working with Vercel CLI using access tokens rather than interactive login — e.g. "deploy to vercel", "set up vercel", "add environment variables to vercel".
vercel-react-view-transitions
Guide for implementing smooth, native-feeling animations using React's View Transition API (`<ViewTransition>` component, `addTransitionType`, and CSS view transition pseudo-elements). Use this skill whenever the user wants to add page transitions, animate route changes, create shared element animations, animate enter/exit of components, animate list reorder, implement directional (forward/back) navigation animations, or integrate view transitions in Next.js. Also use when the user mentions view transitions, `startViewTransition`, `ViewTransition`, transition types, or asks about animating between UI states in React without third-party animation libraries.
vercel-react-native-skills
React Native and Expo best practices for building performant mobile apps. Use when building React Native components, optimizing list performance, implementing animations, or working with native modules. Triggers on tasks involving React Native, Expo, mobile performance, or native platform APIs.
deploy-to-vercel
Deploy applications and websites to Vercel. Use when the user requests deployment actions like "deploy my app", "deploy and give me the link", "push this live", or "create a preview deployment".
vercel-composition-patterns
React composition patterns that scale. Use when refactoring components with boolean prop proliferation, building flexible component libraries, or designing reusable APIs. Triggers on tasks involving compound components, render props, context providers, or component architecture. Includes React 19 API changes.
vercel-deploy
Deploy applications and websites to Vercel. Use this skill when the user requests deployment actions such as "Deploy my app", "Deploy this to production", "Create a preview deployment", "Deploy and give me the link", or "Push this live". No authentication required - returns preview URL and claimable deployment link.
ckm:ui-styling
Create beautiful, accessible user interfaces with shadcn/ui components (built on Radix UI + Tailwind), Tailwind CSS utility-first styling, and canvas-based visual designs. Use when building user interfaces, implementing design systems, creating responsive layouts, adding accessible components (dialogs, dropdowns, forms, tables), customizing themes and colors, implementing dark mode, generating visual designs and posters, or establishing consistent styling patterns across applications.
ckm:design
Comprehensive design skill: brand identity, design tokens, UI styling, logo generation (55 styles, Gemini AI), corporate identity program (50 deliverables, CIP mockups), HTML presentations (Chart.js), banner design (22 styles, social/ads/web/print), icon design (15 styles, SVG, Gemini 3.1 Pro), social photos (HTML→screenshot, multi-platform). Actions: design logo, create CIP, generate mockups, build slides, design banner, generate icon, create social photos, social media images, brand identity, design system. Platforms: Facebook, Twitter, LinkedIn, YouTube, Instagram, Pinterest, TikTok, Threads, Google Ads.