CLSkills
Back to the library
FREE
API Development

telegram

Integracao completa com Telegram Bot API. Setup com BotFather, mensagens, webhooks, inline keyboards, grupos, canais. Boilerplates Node.js e Python.

Try it — you'd type
Help me with telegram.
And you'd get back
Integracao completa com Telegram Bot API.
Setup com BotFather, mensagens, webhooks, inline keyboards, grupos, canais.
Boilerplates Node.js e Python.
Adding it takes about 30 seconds
1

Click Get this skill. Grab the .md file, one click, no account needed.

2

Add it to Claude. Drop it into ~/.claude/skills/. Claude picks it up the next time you open a session.

3

Ask normally. Type your question. The skill triggers on the right keywords — you don't have to remember anything.

Unlock all skills — $25
You might also like
REST API Scaffold

Scaffold a complete REST API with CRUD operations

GraphQL Schema Generator

Generate GraphQL schema from existing data models

API Documentation

Generate OpenAPI/Swagger documentation from code

API Versioning

Implement API versioning strategy

Rate Limiter

Add rate limiting to API endpoints

API Error Handler

Create standardized API error handling

SKILL FILEWhat Claude actually reads
## Overview

Complete integration with the Telegram Bot API. Setup with BotFather, messages, webhooks, inline keyboards, groups, channels. Node.js and Python boilerplates.

## 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

A skill for building professional Telegram bots using the official Bot API. Supports Node.js/TypeScript and Python.

## Overview

The Telegram Bot API lets you create bots that interact with users through messages, commands, inline keyboards, payments, and much more. Bots are created via @BotFather and authenticated with a unique token.

**Base URL:** `https://api.telegram.org/bot<TOKEN>/METHOD_NAME`
**HTTP methods:** GET and POST
**Parameter formats:** query string, application/x-www-form-urlencoded, application/json, multipart/form-data (uploads)
**File limits:** 50MB download, 20MB upload (via multipart), 50MB via URL

**Supported webhook ports:** 443, 80, 88, 8443

**Prerequisites:**
- A Telegram account
- A bot created via @BotFather (which provides the token)
- Token in the format: `123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11`

If the user does not yet have a bot, guide them to talk to @BotFather on Telegram and send `/newbot`.

---

## Decision Tree

```
Does the user need to create a bot?
├── YES → "Setup with BotFather" section below
└── NO → Which language?
    ├── Node.js/TypeScript
    └── Python
    → What do they want to do?
       ├── Send messages → "Message Types" section
       ├── Receive messages → "Receiving Updates" section
       ├── Interactive keyboards → "Keyboards" section
       ├── Manage groups/channels → references/chat-management.md
       ├── Webhook setup → references/webhook-setup.md
       ├── Inline mode → references/advanced-features.md
       ├── Payments → references/advanced-features.md
       ├── AI-powered support bot → "AI Automation" section
       └── Complete API reference → references/api-reference.md
```

To start a project from scratch with ready-made boilerplate:
```bash
python scripts/setup_project.py --language nodejs --path ./meu-bot-telegram

## Or

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

To test whether the bot token works:
```bash
python scripts/test_bot.py --token "SEU_TOKEN"
```

To send a test message:
```bash
python scripts/send_message.py --token "SEU_TOKEN" --chat-id "CHAT_ID" --text "Hello!"
```

---

## Setup With Botfather

1. Open Telegram and search for @BotFather
2. Send `/newbot`
3. Choose a display name (e.g. "My Awesome Bot")
4. Choose a username (must end with "bot", e.g. `my_awesome_bot`)
5. BotFather returns the token - keep it secure
6. Useful BotFather commands:
   - `/setdescription` - bot description
   - `/setabouttext` - bot "about" text
   - `/setuserpic` - profile picture
   - `/setcommands` - command list
   - `/mybots` - manage existing bots
   - `/setinline` - enable inline mode
   - `/setprivacy` - privacy mode in groups

---

## Environment Variables

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

## Node.Js/Typescript

```typescript
// Install: npm install node-telegram-bot-api dotenv
// For 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

## Install: 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()
```

## Without A Library (Raw Http)

```python
import requests

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

## Check Bot

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

## Send Message

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

---

## Message Types

Telegram supports many content types. Every method accepts `chat_id`, `reply_parameters` (to reply), `reply_markup` (for keyboards), `disable_notification`, and `protect_content`.

## Html (Recommended)

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 (Escape Special Characters: _ * [ ] ( ) ~ ` > # + - = | { } . !)

await bot.send_message(
    chat_id=chat_id,
    text="*Negrito*, _italico_, `codigo`, [link](https://example\\.com)",
    parse_mode="MarkdownV2"
)
```

## Photo (By Url, File_Id, Or Upload)

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

## Document

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

## Voice (Ogg With Opus)

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

## Location

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

## Contact

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

## Poll

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

## Media Group

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

## Chat Action (Typing, Upload_Photo, Etc.)

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

## Node.Js Equivalent

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

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

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

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

---

## Inline Keyboard (Buttons Inside The Message)

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

## Callback Handler

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

app.add_handler(CallbackQueryHandler(button_callback))
```

## Reply Keyboard (Custom 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)
```

## Remove Keyboard

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

---

## Receiving Updates

There are two ways to receive updates: **Long Polling** and **Webhooks**.

## Long Polling (Development)

Simpler, and ideal for development. The bot makes periodic requests to Telegram's server.

```python

## Python-Telegram-Bot Already Does This Automatically

app.run_polling(allowed_updates=Update.ALL_TYPES)
```

```typescript
// node-telegram-bot-api with polling
const bot = new TelegramBot(token, { polling: true });
```

## Webhooks (Production)

For production, webhooks are more efficient. Telegram sends updates via POST to your HTTPS URL.

Read `references/webhook-setup.md` for the complete setup with Express, Flask, ngrok, and deployment.

Quick setup:

```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

## Register 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"
})
```

---

## Bot Commands

Register commands so they appear in the Telegram menu:

```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"}]}'
```

---

## AI Automation

Pattern for an AI-powered support bot (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

    # Indicate that it is typing
    await context.bot.send_chat_action(chat_id, "typing")

    # Keep history
    if chat_id not in user_conversations:
        user_conversations[chat_id] = []

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

    # Call the 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})

    # Limit history (last 20 messages)
    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()
```

---

## Edit Text

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

## Edit Markup (Buttons)

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

## Delete Message

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

## Forward Message

await bot.forward_message(
    chat_id=dest_chat_id,
    from_chat_id=source_chat_id,
    message_id=msg.message_id
)
```

---

## Error Handling

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

async def safe_send(bot, chat_id, text, **kwargs):
    """Send with retry and error handling."""
    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

- **Messages in a private chat:** ~30 msg/second
- **Messages in a group:** ~20 msg/minute per group
- **General broadcast:** ~30 msg/second total
- **Bulk notifications:** use `asyncio.sleep(0.05)` between sends to avoid flooding

If you get a 429 error (Too Many Requests), respect the returned `retry_after` value.

---

## File Reference

| Topic | File |
|--------|---------|
| Webhook setup | `references/webhook-setup.md` |
| Chat management | `references/chat-management.md` |
| Advanced features | `references/advanced-features.md` |
| Complete API reference | `references/api-reference.md` |
| Node.js boilerplate | `assets/boilerplate/nodejs/` |
| Python boilerplate | `assets/boilerplate/python/` |
| Payload examples | `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
```