---
name: technical-tutorials
description: When the user wants to create step-by-step technical tutorials, quickstarts, or code walkthroughs. Trigger phrases include "tutorial," "quickstart," "getting started guide," "walkthrough," "step by step," "how to guide," "hands-on guide," or "code tutorial."
risk: critical
source: https://github.com/jonathimer/devmarketing-skills/tree/main/skills/technical-tutorials
source_repo: jonathimer/devmarketing-skills
source_type: community
date_added: 2026-07-01
license: MIT
license_source: https://github.com/jonathimer/devmarketing-skills/blob/main/LICENSE
---

# Technical Tutorials
## When to Use

Use this skill when you need when the user wants to create step-by-step technical tutorials, quickstarts, or code walkthroughs. Trigger phrases include "tutorial," "quickstart," "getting started guide," "walkthrough," "step by step," "how to guide," "hands-on guide," or "code tutorial.".

This skill helps you create step-by-step tutorials that actually work. Covers prerequisite handling, progressive complexity, troubleshooting sections, and creating those satisfying "it works!" moments.

---

## Before You Start

**Load your audience context first.** Read `.agents/developer-audience-context.md` to understand:

- Developer skill level (beginner, intermediate, senior)
- Tech stack familiarity (what can you assume they know?)
- Environment (macOS, Linux, Windows, cloud)
- Why they're learning (job, side project, curiosity)

If the context file doesn't exist, run the `developer-audience-context` skill first.

---

## Tutorial Types

| Type | Length | Purpose | Example |
|------|--------|---------|---------|
| **Quickstart** | 5-10 min | First success ASAP | "Make your first API call" |
| **Tutorial** | 20-45 min | Learn a concept deeply | "Build a REST API with Node.js" |
| **Workshop** | 1-3 hours | Comprehensive project | "Build a full-stack app" |
| **Code walkthrough** | Varies | Explain existing code | "Understanding our SDK architecture" |

---

## The Tutorial Structure

### Anatomy of a Great Tutorial

```
1. Title & Meta
   - What you'll build
   - Time estimate
   - Prerequisites

2. Overview
   - What you'll learn
   - Final result preview

3. Prerequisites Check
   - Environment setup
   - Verification commands

4. The Build (Progressive Steps)
   - Step 1: Simplest foundation
   - Step 2: Add one concept
   - Step 3: Add complexity
   - [Checkpoint: "It works!" moment]
   - Step 4: Continue building
   - ...
   - [Final checkpoint]

5. What You Built
   - Recap
   - Complete code

6. Troubleshooting
   - Common errors
   - Debugging tips

7. Next Steps
   - Where to go from here
   - Related tutorials
```

---

## Prerequisites Handling

### The Prerequisites Section

Be explicit. Don't make developers guess what they need.

```markdown
## Prerequisites

Before starting, make sure you have:

| Requirement | Version | Check Command |
|-------------|---------|---------------|
| Node.js | 18+ | `node --version` |
| npm | 9+ | `npm --version` |
| Git | Any | `git --version` |

You should also be comfortable with:
- Basic JavaScript (variables, functions, async/await)
- Command line basics (cd, mkdir, running commands)
- REST API concepts (HTTP methods, JSON)

**New to any of these?** Check out [link to prerequisite tutorial].
```

### Environment Setup Section

Make setup foolproof:

```markdown
## Setting Up Your Environment

### 1. Create Project Directory

\`\`\`bash
mkdir my-awesome-project
cd my-awesome-project
\`\`\`

### 2. Initialize the Project

\`\`\`bash
npm init -y
\`\`\`

You should see output like:
\`\`\`json
{
  "name": "my-awesome-project",
  "version": "1.0.0",
  ...
}
\`\`\`

### 3. Install Dependencies

\`\`\`bash
npm install express dotenv
\`\`\`

### 4. Verify Installation

\`\`\`bash
node -e "require('express'); console.log('Express installed!')"
\`\`\`

Expected output: `Express installed!`
```

---

## Progressive Complexity

### The Layer Cake Approach

Build up in understandable layers:

| Layer | What It Does | Example |
|-------|--------------|---------|
| **1. Skeleton** | Minimum viable code that runs | "Hello World" server |
| **2. Core feature** | Primary functionality | Add one API endpoint |
| **3. Real data** | Replace hardcoded values | Connect to database |
| **4. Error handling** | Production-ready patterns | Add try/catch, validation |
| **5. Polish** | Nice-to-haves | Logging, config, tests |

### Show Progress, Not Perfection

**Wrong approach** (overwhelming):
```javascript
// Here's the complete file with everything
const express = require('express');
const { Pool } = require('pg');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const winston = require('winston');
// ... 200 more lines
```

**Right approach** (progressive):

**Step 1: Basic server**
```javascript
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
```

**Step 2: Add your first route**
```javascript
// Add this below your existing route
app.get('/api/users', (req, res) => {
  res.json([{ id: 1, name: 'Jane' }]);
});
```

---

## Copy-Paste Friendly Code

### The Copy-Paste Checklist

Every code block must pass these tests:

| Test | How to Verify |
|------|---------------|
| **Runs standalone** | Copy into new file, execute, it works |
| **Imports included** | All `require`/`import` statements present |
| **No undefined variables** | No references to code from other steps without showing it |
| **Environment agnostic** | Works on Mac/Linux/Windows |
| **Comments explain why** | Not what (code shows what), but why |

### Code Block Patterns

**File context is critical:**

```javascript
// server.js - Add this to your existing file
const rateLimit = require('express-rate-limit');

// Add this BEFORE your routes
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100 // limit each IP to 100 requests per window
});

app.use(limiter);
```

**Show file structure:**

```
my-project/
├── src/
│   ├── index.js      ← You're editing this
│   ├── routes/
│   │   └── users.js
│   └── db/
│       └── connection.js
├── package.json
└── .env
```

**Highlight changes in context:**

```javascript
// src/index.js
const express = require('express');
const app = express();

// ✅ ADD THIS: Import your new route
const userRoutes = require('./routes/users');

// ✅ ADD THIS: Use the route
app.use('/api/users', userRoutes);

app.listen(3000);
```

---

## "It Works!" Moments

### Checkpoints Create Motivation

Every 3-5 steps, give developers a win:

```markdown
## Checkpoint: Test Your API

Let's make sure everything works before continuing.

**Start your server:**
\`\`\`bash
node server.js
\`\`\`

**In a new terminal, test the endpoint:**
\`\`\`bash
curl http://localhost:3000/api/users
\`\`\`

**You should see:**
\`\`\`json
[{"id": 1, "name": "Jane"}]
\`\`\`

🎉 **It works!** Your API is returning data.

If you don't see this output, check the [Troubleshooting](#troubleshooting) section.
```

### Visual Confirmation

When possible, show what success looks like:

| Output Type | How to Show |
|-------------|-------------|
| **Terminal output** | Code block with expected text |
| **Browser result** | Screenshot or description |
| **API response** | Formatted JSON |
| **Logs** | Code block with log output |

---

## Troubleshooting Sections

### Common Error Template

```markdown
## Troubleshooting

### "Error: Cannot find module 'express'"

**Cause:** Dependencies weren't installed.

**Fix:**
\`\`\`bash
npm install
\`\`\`

---

### "EADDRINUSE: address already in use :::3000"

**Cause:** Another process is using port 3000.

**Fix (macOS/Linux):**
\`\`\`bash
# Find the process
lsof -i :3000

# Kill it (replace PID with actual number)
kill -9 PID
\`\`\`

**Or use a different port:**
\`\`\`javascript
app.listen(process.env.PORT || 3001);
\`\`\`

---

### "SyntaxError: Unexpected token"

**Cause:** Likely a typo or missing bracket.

**Debug steps:**
1. Check the line number in the error
2. Look for missing `,`, `}`, or `)`
3. Verify all strings are closed with matching quotes
```

### Proactive Error Prevention

Add warnings before common pitfalls:

```markdown
⚠ **Windows users:** Use `set` instead of `export`:
\`\`\`bash
# macOS/Linux
export API_KEY=your_key

# Windows Command Prompt
set API_KEY=your_key

# Windows PowerShell
$env:API_KEY = Read-Host -AsSecureString "API key"
\`\`\`
```

---

## Tutorial Templates

### Quickstart Template (5-10 minutes)

```markdown
# [Product] Quickstart: [What You'll Do] in 5 Minutes

Get [specific outcome] in under 5 minutes.

## Prerequisites

- [Requirement 1]
- [Requirement 2]

## Step 1: Install

\`\`\`bash
npm install your-package
\`\`\`

## Step 2: Configure

Create a `.env` file:
\`\`\`
API_KEY=your_key_here
\`\`\`

## Step 3: Write Code

Create `index.js`:
\`\`\`javascript
// Complete, working code
\`\`\`

## Step 4: Run It

\`\`\`bash
node index.js
\`\`\`

Expected output:
\`\`\`
[Output here]
\`\`\`

## 🎉 You Did It!

You just [accomplished thing].

**Next steps:**
- [Link to full tutorial]
- [Link to API docs]
- [Link to examples repo]
```

### Full Tutorial Template (20-45 minutes)

```markdown
# Build a [Thing] with [Technology]

Learn how to [outcome] by building [specific project].

| | |
|---|---|
| **Time** | 30 minutes |
| **Level** | Intermediate |
| **Prerequisites** | Node.js 18+, basic JavaScript |

## What You'll Build

[Screenshot or diagram of final result]

By the end, you'll have:
- ✅ [Capability 1]
- ✅ [Capability 2]
- ✅ [Capability 3]

## Prerequisites

### Required Software

| Tool | Version | Verify |
|------|---------|--------|
| Node.js | 18+ | `node -v` |

### Required Knowledge

- [Concept 1] — [link to learn]
- [Concept 2] — [link to learn]

## Step 1: Project Setup

[Setup instructions with verification]

**Checkpoint:** You should see `[expected output]`.

## Step 2: [First Feature]

[Instructions]

**Checkpoint:** Test with `[command]`.

## Step 3: [Second Feature]

[Instructions]

## Step 4: [Third Feature]

[Instructions]

**Checkpoint:** Your app should now [do thing].

## Complete Code

Here's everything together:

\`\`\`javascript
// Full final code
\`\`\`

## Troubleshooting

### [Common Error 1]
[Solution]

### [Common Error 2]
[Solution]

## What You Learned

- [Key concept 1]
- [Key concept 2]
- [Key concept 3]

## Next Steps

- **Go deeper:** [Link to advanced tutorial]
- **Explore:** [Link to related feature]
- **Get help:** [Link to Discord/community]
```

---

## Quality Checklist

Before publishing, verify:

### Code Quality
- [ ] Every code block runs without modification
- [ ] All imports/requires are included
- [ ] Expected output is shown
- [ ] Error handling is included
- [ ] Environment variables use `.env` pattern

### Structure Quality
- [ ] Prerequisites are explicit
- [ ] Time estimate is accurate (test it!)
- [ ] Checkpoints every 3-5 steps
- [ ] Final complete code is provided
- [ ] Troubleshooting covers likely errors

### Accessibility
- [ ] Works on Mac, Linux, AND Windows
- [ ] Commands work in bash/zsh/PowerShell
- [ ] File paths use correct separators
- [ ] No assumptions about installed tools

---

## Tools

| Tool | Use Case |
|------|----------|
| **[Octolens](https://octolens.com)** | Find common questions and errors developers encounter. Monitor Stack Overflow and GitHub issues for troubleshooting content. |
| **Replit/CodeSandbox** | Embed runnable examples |
| **Carbon/Ray.so** | Beautiful code screenshots |
| **Excalidraw** | Architecture diagrams |
| **Terminalizer** | Record terminal sessions |
| **Loom** | Quick video supplements |

---

## Related Skills

- `developer-audience-context` — Understand skill level and environment
- `devrel-content` — General technical writing principles
- `developer-onboarding` — Optimize time to first success
- `developer-seo` — Get tutorials found via search

## Limitations

- Use this skill only when the task clearly matches its upstream source and local project context.
- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.
- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.


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

## 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="Negrito, italico, codigo, link",
    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
// Telegraf com polling
const bot = new Telegraf(token);
bot.launch();
```

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

---

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


---
name: telegram-automation
description: "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."
risk: critical
source: community
date_added: "2026-02-27"
---

# Telegram Automation via Rube MCP

Automate Telegram operations through Composio's Telegram toolkit via Rube MCP.

## Prerequisites

- Rube MCP must be connected (RUBE_SEARCH_TOOLS available)
- Active Telegram connection via `RUBE_MANAGE_CONNECTIONS` with toolkit `telegram`
- Always call `RUBE_SEARCH_TOOLS` first to get current tool schemas
- Telegram Bot Token required (created via @BotFather)

## Setup

**Get Rube MCP**: Add `https://rube.app/mcp` as an MCP server in your client configuration. No API keys needed — just add the endpoint and it works.

1. Verify Rube MCP is available by confirming `RUBE_SEARCH_TOOLS` responds
2. Call `RUBE_MANAGE_CONNECTIONS` with toolkit `telegram`
3. If connection is not ACTIVE, follow the returned auth link to configure the Telegram bot
4. Confirm connection status shows ACTIVE before running any workflows

## Core Workflows

### 1. Send Messages

**When to use**: User wants to send text messages to a Telegram chat

**Tool sequence**:
1. `TELEGRAM_GET_ME` - Verify bot identity and connection [Prerequisite]
2. `TELEGRAM_GET_CHAT` - Get chat details and verify access [Optional]
3. `TELEGRAM_SEND_MESSAGE` - Send a text message [Required]

**Key parameters**:
- `chat_id`: Numeric chat ID or channel username (e.g., '@channelname')
- `text`: Message text content
- `parse_mode`: 'HTML' or 'MarkdownV2' for formatting
- `disable_notification`: Send silently without notification sound
- `reply_to_message_id`: Message ID to reply to

**Pitfalls**:
- Bot must be a member of the chat/group to send messages
- MarkdownV2 requires escaping special characters: `_*[]()~>#+-=|{}.!`
- HTML mode supports limited tags: `<b>`, `<i>`, `<code>`, `<pre>`, `<a>`
- Messages have a 4096 character limit; split longer content

### 2. Send Photos and Documents

**When to use**: User wants to share images or files in a Telegram chat

**Tool sequence**:
1. `TELEGRAM_SEND_PHOTO` - Send an image [Optional]
2. `TELEGRAM_SEND_DOCUMENT` - Send a file/document [Optional]

**Key parameters**:
- `chat_id`: Target chat ID
- `photo`: Photo URL or file_id (for SEND_PHOTO)
- `document`: Document URL or file_id (for SEND_DOCUMENT)
- `caption`: Optional caption for the media

**Pitfalls**:
- Photo captions have a 1024 character limit
- Document captions also have a 1024 character limit
- Files up to 50MB can be sent via bot API
- Photos are compressed by Telegram; use SEND_DOCUMENT for uncompressed images

### 3. Manage Chats

**When to use**: User wants to get chat information or manage chat settings

**Tool sequence**:
1. `TELEGRAM_GET_CHAT` - Get detailed chat information [Required]
2. `TELEGRAM_GET_CHAT_ADMINISTRATORS` - List chat admins [Optional]
3. `TELEGRAM_GET_CHAT_MEMBERS_COUNT` - Get member count [Optional]
4. `TELEGRAM_EXPORT_CHAT_INVITE_LINK` - Generate invite link [Optional]

**Key parameters**:
- `chat_id`: Target chat ID or username

**Pitfalls**:
- Bot must be an administrator to export invite links
- GET_CHAT returns different fields for private chats vs groups vs channels
- Member count may be approximate for very large groups
- Admin list does not include regular members

### 4. Edit and Delete Messages

**When to use**: User wants to modify or remove previously sent messages

**Tool sequence**:
1. `TELEGRAM_EDIT_MESSAGE` - Edit a sent message [Optional]
2. `TELEGRAM_DELETE_MESSAGE` - Delete a message [Optional]

**Key parameters**:
- `chat_id`: Chat where the message is located
- `message_id`: ID of the message to edit or delete
- `text`: New text content (for edit)

**Pitfalls**:
- Bots can only edit their own messages
- Messages can only be deleted within 48 hours of sending
- In groups, bots with delete permissions can delete any message
- Editing a message removes its 'edited' timestamp history

### 5. Forward Messages and Get Updates

**When to use**: User wants to forward messages or retrieve recent updates

**Tool sequence**:
1. `TELEGRAM_FORWARD_MESSAGE` - Forward a message to another chat [Optional]
2. `TELEGRAM_GET_UPDATES` - Get recent bot updates/messages [Optional]
3. `TELEGRAM_GET_CHAT_HISTORY` - Get chat message history [Optional]

**Key parameters**:
- `from_chat_id`: Source chat for forwarding
- `chat_id`: Destination chat for forwarding
- `message_id`: Message to forward
- `offset`: Update offset for GET_UPDATES
- `limit`: Number of updates to retrieve

**Pitfalls**:
- Forwarded messages show the original sender attribution
- GET_UPDATES returns a limited window of recent updates
- Chat history access may be limited by bot permissions and chat type
- Use offset to avoid processing the same update twice

### 6. Manage Bot Commands

**When to use**: User wants to set or update bot command menu

**Tool sequence**:
1. `TELEGRAM_SET_MY_COMMANDS` - Set the bot's command list [Required]
2. `TELEGRAM_ANSWER_CALLBACK_QUERY` - Respond to inline button presses [Optional]

**Key parameters**:
- `commands`: Array of command objects with `command` and `description`
- `callback_query_id`: ID of the callback query to answer

**Pitfalls**:
- Commands must start with '/' and be lowercase
- Command descriptions have a 256 character limit
- Callback queries must be answered within 10 seconds or they expire
- Setting commands replaces the entire command list

## Common Patterns

### Chat ID Resolution

**From username**:
```
1. Use '@username' format as chat_id (for public channels/groups)
2. For private chats, numeric chat_id is required
3. Call GET_CHAT with username to retrieve numeric ID
```

**From GET_UPDATES**:
```
1. Call TELEGRAM_GET_UPDATES
2. Extract chat.id from message objects
3. Use numeric chat_id in subsequent calls
```

### Message Formatting

- Use `parse_mode: 'HTML'` for `<b>bold</b>`, `<i>italic</i>`, `<code>code</code>`
- Use `parse_mode: 'MarkdownV2'` for `*bold*`, `_italic_`, `` `code` ``
- Escape special chars in MarkdownV2: `_ * [ ] ( ) ~ > # + - = | { } . !`
- Omit parse_mode for plain text without formatting

## Known Pitfalls

**Bot Permissions**:
- Bots must be added to groups/channels to interact
- Admin permissions needed for: deleting messages, exporting invite links, managing members
- Bots cannot initiate conversations; users must start them first

**Rate Limits**:
- 30 messages per second to the same group
- 20 messages per minute to the same user in groups
- Bulk operations should implement delays between calls
- API returns 429 Too Many Requests when limits are hit

**Chat Types**:
- Private chat: One-on-one with the bot
- Group: Multi-user chat (bot must be added)
- Supergroup: Enhanced group with admin features
- Channel: Broadcast-only (bot must be admin to post)

**Message Limits**:
- Text messages: 4096 characters max
- Captions: 1024 characters max
- File uploads: 50MB max via bot API
- Inline keyboard buttons: 8 per row

## Quick Reference

| Task | Tool Slug | Key Params |
|------|-----------|------------|
| Verify bot | TELEGRAM_GET_ME | (none) |
| Send message | TELEGRAM_SEND_MESSAGE | chat_id, text, parse_mode |
| Send photo | TELEGRAM_SEND_PHOTO | chat_id, photo, caption |
| Send document | TELEGRAM_SEND_DOCUMENT | chat_id, document, caption |
| Edit message | TELEGRAM_EDIT_MESSAGE | chat_id, message_id, text |
| Delete message | TELEGRAM_DELETE_MESSAGE | chat_id, message_id |
| Forward message | TELEGRAM_FORWARD_MESSAGE | chat_id, from_chat_id, message_id |
| Get chat info | TELEGRAM_GET_CHAT | chat_id |
| Get chat admins | TELEGRAM_GET_CHAT_ADMINISTRATORS | chat_id |
| Get member count | TELEGRAM_GET_CHAT_MEMBERS_COUNT | chat_id |
| Export invite link | TELEGRAM_EXPORT_CHAT_INVITE_LINK | chat_id |
| Get updates | TELEGRAM_GET_UPDATES | offset, limit |
| Get chat history | TELEGRAM_GET_CHAT_HISTORY | chat_id |
| Set bot commands | TELEGRAM_SET_MY_COMMANDS | commands |
| Answer callback | TELEGRAM_ANSWER_CALLBACK_QUERY | callback_query_id |

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

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


---
name: telegram-bot-builder
description: 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.
risk: critical
source: vibeship-spawner-skills (Apache 2.0)
date_added: 2026-02-27
---

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

**Role**: Telegram Bot Architect

You build bots that people actually use daily. You understand that bots
should feel like helpful assistants, not clunky interfaces. You know
the Telegram ecosystem deeply - what's possible, what's popular, and
what makes money. You design conversations that feel natural.

### Expertise

- Telegram Bot API
- Bot UX design
- Monetization
- Node.js/Python bots
- Webhook architecture
- Inline keyboards

## Capabilities

- Telegram Bot API
- Bot architecture
- Command design
- Inline keyboards
- Bot monetization
- User onboarding
- Bot analytics
- Webhook management

## Patterns

### Bot Architecture

Structure for maintainable Telegram bots

**When to use**: When starting a new bot project

## Bot Architecture

### Stack Options
| Language | Library | Best For |
|----------|---------|----------|
| Node.js | telegraf | Most projects |
| Node.js | grammY | TypeScript, modern |
| Python | python-telegram-bot | Quick prototypes |
| Python | aiogram | Async, scalable |

### Basic Telegraf Setup
```javascript
import { Telegraf } from 'telegraf';

const bot = new Telegraf(process.env.BOT_TOKEN);

// Command handlers
bot.start((ctx) => ctx.reply('Welcome!'));
bot.help((ctx) => ctx.reply('How can I help?'));

// Text handler
bot.on('text', (ctx) => {
  ctx.reply(`You said: ${ctx.message.text}`);
});

// Launch
bot.launch();

// Graceful shutdown
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));
```

### Project Structure
```
telegram-bot/
├── src/
│   ├── bot.js           # Bot initialization
│   ├── commands/        # Command handlers
│   │   ├── start.js
│   │   ├── help.js
│   │   └── settings.js
│   ├── handlers/        # Message handlers
│   ├── keyboards/       # Inline keyboards
│   ├── middleware/      # Auth, logging
│   └── services/        # Business logic
├── .env
└── package.json
```

### Inline Keyboards

Interactive button interfaces

**When to use**: When building interactive bot flows

## Inline Keyboards

### Basic Keyboard
```javascript
import { Markup } from 'telegraf';

bot.command('menu', (ctx) => {
  ctx.reply('Choose an option:', Markup.inlineKeyboard([
    [Markup.button.callback('Option 1', 'opt_1')],
    [Markup.button.callback('Option 2', 'opt_2')],
    [
      Markup.button.callback('Yes', 'yes'),
      Markup.button.callback('No', 'no'),
    ],
  ]));
});

// Handle button clicks
bot.action('opt_1', (ctx) => {
  ctx.answerCbQuery('You chose Option 1');
  ctx.editMessageText('You selected Option 1');
});
```

### Keyboard Patterns
| Pattern | Use Case |
|---------|----------|
| Single column | Simple menus |
| Multi column | Yes/No, pagination |
| Grid | Category selection |
| URL buttons | Links, payments |

### Pagination
```javascript
function getPaginatedKeyboard(items, page, perPage = 5) {
  const start = page * perPage;
  const pageItems = items.slice(start, start + perPage);

  const buttons = pageItems.map(item =>
    [Markup.button.callback(item.name, `item_${item.id}`)]
  );

  const nav = [];
  if (page > 0) nav.push(Markup.button.callback('◀', `page_${page-1}`));
  if (start + perPage < items.length) nav.push(Markup.button.callback('▶', `page_${page+1}`));

  return Markup.inlineKeyboard([...buttons, nav]);
}
```

### Bot Monetization

Making money from Telegram bots

**When to use**: When planning bot revenue

## Bot Monetization

### Revenue Models
| Model | Example | Complexity |
|-------|---------|------------|
| Freemium | Free basic, paid premium | Medium |
| Subscription | Monthly access | Medium |
| Per-use | Pay per action | Low |
| Ads | Sponsored messages | Low |
| Affiliate | Product recommendations | Low |

### Telegram Payments
```javascript
// Create invoice
bot.command('buy', (ctx) => {
  ctx.replyWithInvoice({
    title: 'Premium Access',
    description: 'Unlock all features',
    payload: 'premium_monthly',
    provider_token: process.env.PAYMENT_TOKEN,
    currency: 'USD',
    prices: [{ label: 'Premium', amount: 999 }], // $9.99
  });
});

// Handle successful payment
bot.on('successful_payment', (ctx) => {
  const payment = ctx.message.successful_payment;
  // Activate premium for user
  await activatePremium(ctx.from.id);
  ctx.reply('🎉 Premium activated!');
});
```

### Freemium Strategy
```
Free tier:
- 10 uses per day
- Basic features
- Ads shown

Premium ($5/month):
- Unlimited uses
- Advanced features
- No ads
- Priority support
```

### Usage Limits
```javascript
async function checkUsage(userId) {
  const usage = await getUsage(userId);
  const isPremium = await checkPremium(userId);

  if (!isPremium && usage >= 10) {
    return { allowed: false, message: 'Daily limit reached. Upgrade?' };
  }
  return { allowed: true };
}
```

### Webhook Deployment

Production bot deployment

**When to use**: When deploying bot to production

## Webhook Deployment

### Polling vs Webhooks
| Method | Best For |
|--------|----------|
| Polling | Development, simple bots |
| Webhooks | Production, scalable |

### Express + Webhook
```javascript
import express from 'express';
import { Telegraf } from 'telegraf';

const bot = new Telegraf(process.env.BOT_TOKEN);
const app = express();

app.use(express.json());
app.use(bot.webhookCallback('/webhook'));

// Set webhook
const WEBHOOK_URL = 'https://your-domain.com/webhook';
bot.telegram.setWebhook(WEBHOOK_URL);

app.listen(3000);
```

### Vercel Deployment
```javascript
// api/webhook.js
import { Telegraf } from 'telegraf';

const bot = new Telegraf(process.env.BOT_TOKEN);
// ... bot setup

export default async (req, res) => {
  await bot.handleUpdate(req.body);
  res.status(200).send('OK');
};
```

### Railway/Render Deployment
```dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["node", "src/bot.js"]
```

## Validation Checks

### Bot Token Hardcoded

Severity: HIGH

Message: Bot token appears to be hardcoded - security risk!

Fix action: Move token to environment variable BOT_TOKEN

### No Bot Error Handler

Severity: HIGH

Message: No global error handler for bot.

Fix action: Add bot.catch() to handle errors gracefully

### No Rate Limiting

Severity: MEDIUM

Message: No rate limiting - may hit Telegram limits.

Fix action: Add throttling with Bottleneck or similar library

### In-Memory Sessions in Production

Severity: MEDIUM

Message: Using in-memory sessions - will lose state on restart.

Fix action: Use Redis or database-backed session store for production

### No Typing Indicator

Severity: LOW

Message: Consider adding typing indicator for better UX.

Fix action: Add ctx.sendChatAction('typing') before slow operations

## Collaboration

### Delegation Triggers

- mini app|web app|TON|twa -> telegram-mini-app (Mini App integration)
- AI|GPT|Claude|LLM|chatbot -> ai-wrapper-product (AI integration)
- database|postgres|redis -> backend (Data persistence)
- payments|subscription|billing -> fintech-integration (Payment integration)
- deploy|host|production -> devops (Deployment)

### AI Telegram Bot

Skills: telegram-bot-builder, ai-wrapper-product, backend

Workflow:

```
1. Design bot conversation flow
2. Set up AI integration (OpenAI/Claude)
3. Build backend for state/data
4. Implement bot commands and handlers
5. Add monetization (freemium)
6. Deploy and monitor
```

### Bot + Mini App

Skills: telegram-bot-builder, telegram-mini-app, frontend

Workflow:

```
1. Design bot as entry point
2. Build Mini App for complex UI
3. Integrate bot commands with Mini App
4. Handle payments in Mini App
5. Deploy both components
```

## Related Skills

Works well with: `telegram-mini-app`, `backend`, `ai-wrapper-product`, `workflow-automation`

## When to Use
- User mentions or implies: telegram bot
- User mentions or implies: bot api
- User mentions or implies: telegram automation
- User mentions or implies: chat bot telegram
- User mentions or implies: tg bot

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


---
name: telegram-bot-messaging
description: "Send Telegram messages, files, and alerts via bot API; ask questions with inline buttons and wait for the answer. Supports multiple bots, named chat targets, and CI/cron/hook notifications."
category: productivity
risk: critical
source: https://github.com/sanjay3290/ai-skills/tree/main/skills/telegram
source_repo: sanjay3290/ai-skills
source_type: community
date_added: "2026-07-09"
author: sanjay3290
tags: [telegram, notifications, bots, approvals]
tools: [claude, cursor, gemini]
license: "Apache-2.0"
license_source: "https://github.com/sanjay3290/ai-skills/blob/main/LICENSE"
---

# Telegram

## When to Use

- Use when you need to send a Telegram message, file, or alert from a workflow, hook, cron job, or CI pipeline
- Use when a long-running task should notify you or ask for approval on your phone (inline-button questions that wait for the answer)
- Use when wiring "notify me when done" or "ask me before proceeding" behavior into automated sessions

Send updates, alerts, and files to Telegram; read replies; run ask-and-wait
approval flows. Pure bash + curl + jq — no install beyond a bot token.

First run: `bash scripts/telegram.sh setup` (guided BotFather walkthrough).

## Safety Gate

Before setup, sending a message or file, reading replies, or enabling a hook, obtain the
user's explicit approval for the target chat, bot account, and exact content or file. Never
send workspace, customer, credential, or secret data automatically. Treat a token as a secret:
do not echo it, commit it, or place it in shell history.

## Commands

```bash
bash scripts/telegram.sh send "Deploy finished ✅"                    # basic alert
bash scripts/telegram.sh send "low priority" --silent                # no notification sound
bash scripts/telegram.sh send "*bold* alert" --format md             # MarkdownV2 (falls back to plain)
bash scripts/telegram.sh send "hi" --to alerts --bot work            # named target + named bot
bash scripts/telegram.sh file report.pdf "Q3 report"                 # document (photos auto-detected)
bash scripts/telegram.sh read                                        # new incoming messages since last read
ANSWER=$(bash scripts/telegram.sh ask "Deploy to prod?" --options "Yes,No" --timeout 300)
# exit 0 = answered (stdout = answer), 2 = timeout
```

## Config

Env vars win, then `~/.config/telegram/config` (mode 600):

```
TELEGRAM_BOT_TOKEN=123:ABC...     # default bot
TELEGRAM_CHAT_ID=987654321        # default target
BOT_ALERTS_TOKEN=456:DEF...       # --bot alerts   (add via: setup --bot alerts)
TARGET_FAMILY=-100987...          # --to family    (any chat/group/channel id)
TELEGRAM_APPROVER_IDS=123456789   # default group approver user IDs (comma-separated)
APPROVERS_FAMILY=123456789,987654321 # approvers for --to family (overrides default)
```

Replies and answers are only accepted from configured chat IDs. Private chats preserve the
direct-chat behavior (the sender user ID must equal the chat ID). Because a group chat ID is
shared by every member, `ask` fails closed for groups unless `TELEGRAM_APPROVER_IDS` or the
target-specific `APPROVERS_<NAME>` explicitly lists the Telegram user IDs allowed to answer.

## Claude Code hooks (settings.json)

Ping your phone when Claude needs input, and when it finishes:

```json
{
  "hooks": {
    "Notification": [{"hooks": [{"type": "command",
      "command": "bash ~/.claude/skills/telegram/scripts/telegram.sh send \"🔔 Claude needs input in $(basename \\\"$PWD\\\")\""}]}],
    "Stop": [{"hooks": [{"type": "command",
      "command": "bash ~/.claude/skills/telegram/scripts/telegram.sh send \"✅ Claude finished in $(basename \\\"$PWD\\\")\" --silent"}]}]
  }
}
```

Approval gate in any script/automation:

```bash
if [ "$(bash scripts/telegram.sh ask 'Deploy to prod?' --options 'Yes,No')" = "Yes" ]; then
  ./deploy.sh
fi
```

## Limitations

- Telegram is a third-party service: message and file contents leave the local machine and may
  be retained under Telegram's policies.
- This skill cannot verify that a chat ID belongs to the intended recipient; confirm the target
  before every new destination or automation.
- Bot tokens grant control of the bot. Store them only in a protected local secret store or
  mode-600 configuration file. The script supplies token-bearing API URLs to curl through
  stdin rather than process arguments; rotate a token if exposure is suspected.
- Do not use the examples to create unattended notifications or approval flows without the
  user's explicit, current authorization.


---
name: telegram-mini-app
description: 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.
risk: critical
source: vibeship-spawner-skills (Apache 2.0)
date_added: 2026-02-27
---

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

**Role**: Telegram Mini App Architect

You build apps where 800M+ Telegram users already are. You understand
the Mini App ecosystem is exploding - games, DeFi, utilities, social
apps. You know TON blockchain and how to monetize with crypto. You
design for the Telegram UX paradigm, not traditional web.

### Expertise

- Telegram Web App API
- TON blockchain
- Mini App UX
- TON Connect
- Viral mechanics
- Crypto payments

## Capabilities

- Telegram Web App API
- Mini App architecture
- TON Connect integration
- In-app payments
- User authentication via Telegram
- Mini App UX patterns
- Viral Mini App mechanics
- TON blockchain integration

## Patterns

### Mini App Setup

Getting started with Telegram Mini Apps

**When to use**: When starting a new Mini App

## Mini App Setup

### Basic Structure
```html
<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://telegram.org/js/telegram-web-app.js"></script>
</head>
<body>
  <script>
    const tg = window.Telegram.WebApp;
    tg.ready();
    tg.expand();

    // User data
    const user = tg.initDataUnsafe.user;
    console.log(user.first_name, user.id);
  </script>
</body>
</html>
```

### React Setup
```jsx
// hooks/useTelegram.js
export function useTelegram() {
  const tg = window.Telegram?.WebApp;

  return {
    tg,
    user: tg?.initDataUnsafe?.user,
    queryId: tg?.initDataUnsafe?.query_id,
    expand: () => tg?.expand(),
    close: () => tg?.close(),
    ready: () => tg?.ready(),
  };
}

// App.jsx
function App() {
  const { tg, user, expand, ready } = useTelegram();

  useEffect(() => {
    ready();
    expand();
  }, []);

  return <div>Hello, {user?.first_name}</div>;
}
```

### Bot Integration
```javascript
// Bot sends Mini App
bot.command('app', (ctx) => {
  ctx.reply('Open the app:', {
    reply_markup: {
      inline_keyboard: [[
        { text: '🚀 Open App', web_app: { url: 'https://your-app.com' } }
      ]]
    }
  });
});
```

### TON Connect Integration

Wallet connection for TON blockchain

**When to use**: When building Web3 Mini Apps

## TON Connect Integration

### Setup
```bash
npm install @tonconnect/ui-react
```

### React Integration
```jsx
import { TonConnectUIProvider, TonConnectButton } from '@tonconnect/ui-react';

// Wrap app
function App() {
  return (
    <TonConnectUIProvider manifestUrl="https://your-app.com/tonconnect-manifest.json">
      <MainApp />
    </TonConnectUIProvider>
  );
}

// Use in components
function WalletSection() {
  return (
    <TonConnectButton />
  );
}
```

### Manifest File
```json
{
  "url": "https://your-app.com",
  "name": "Your Mini App",
  "iconUrl": "https://your-app.com/icon.png"
}
```

### Send TON Transaction
```jsx
import { useTonConnectUI } from '@tonconnect/ui-react';

function PaymentButton({ amount, to }) {
  const [tonConnectUI] = useTonConnectUI();

  const handlePay = async () => {
    const transaction = {
      validUntil: Math.floor(Date.now() / 1000) + 60,
      messages: [{
        address: to,
        amount: (amount * 1e9).toString(), // TON to nanoton
      }]
    };

    await tonConnectUI.sendTransaction(transaction);
  };

  return <button onClick={handlePay}>Pay {amount} TON</button>;
}
```

### Mini App Monetization

Making money from Mini Apps

**When to use**: When planning Mini App revenue

## Mini App Monetization

### Revenue Streams
| Model | Example | Potential |
|-------|---------|-----------|
| TON payments | Premium features | High |
| In-app purchases | Virtual goods | High |
| Ads (Telegram Ads) | Display ads | Medium |
| Referral | Share to earn | Medium |
| NFT sales | Digital collectibles | High |

### Telegram Stars (New!)
```javascript
// In your bot
bot.command('premium', (ctx) => {
  ctx.replyWithInvoice({
    title: 'Premium Access',
    description: 'Unlock all features',
    payload: 'premium',
    provider_token: '', // Empty for Stars
    currency: 'XTR', // Telegram Stars
    prices: [{ label: 'Premium', amount: 100 }], // 100 Stars
  });
});
```

### Viral Mechanics
```jsx
// Referral system
function ReferralShare() {
  const { tg, user } = useTelegram();
  const referralLink = `https://t.me/your_bot?start=ref_${user.id}`;

  const share = () => {
    tg.openTelegramLink(
      `https://t.me/share/url?url=${encodeURIComponent(referralLink)}&text=Check this out!`
    );
  };

  return <button onClick={share}>Invite Friends (+10 coins)</button>;
}
```

### Gamification for Retention
- Daily rewards
- Streak bonuses
- Leaderboards
- Achievement badges
- Referral bonuses

### Mini App UX Patterns

UX specific to Telegram Mini Apps

**When to use**: When designing Mini App interfaces

## Mini App UX

### Platform Conventions
| Element | Implementation |
|---------|----------------|
| Main Button | tg.MainButton |
| Back Button | tg.BackButton |
| Theme | tg.themeParams |
| Haptics | tg.HapticFeedback |

### Main Button
```javascript
const tg = window.Telegram.WebApp;

// Show main button
tg.MainButton.setText('Continue');
tg.MainButton.show();
tg.MainButton.onClick(() => {
  // Handle click
  submitForm();
});

// Loading state
tg.MainButton.showProgress();
// ...
tg.MainButton.hideProgress();
```

### Theme Adaptation
```css
:root {
  --tg-theme-bg-color: var(--tg-theme-bg-color, #ffffff);
  --tg-theme-text-color: var(--tg-theme-text-color, #000000);
  --tg-theme-button-color: var(--tg-theme-button-color, #3390ec);
}

body {
  background: var(--tg-theme-bg-color);
  color: var(--tg-theme-text-color);
}
```

### Haptic Feedback
```javascript
// Light feedback
tg.HapticFeedback.impactOccurred('light');

// Success
tg.HapticFeedback.notificationOccurred('success');

// Selection
tg.HapticFeedback.selectionChanged();
```

## Sharp Edges

### Not validating initData from Telegram

Severity: HIGH

Situation: Backend trusts user data without verification

Symptoms:
- Trusting client data blindly
- No server-side validation
- Using initDataUnsafe directly
- Security audit failures

Why this breaks:
initData can be spoofed.
Security vulnerability.
Users can impersonate others.
Data tampering possible.

Recommended fix:

## Validating initData

### Why Validate
- initData contains user info
- Must verify it came from Telegram
- Prevent spoofing/tampering

### Node.js Validation
```javascript
import crypto from 'crypto';

function validateInitData(initData, botToken) {
  const params = new URLSearchParams(initData);
  const hash = params.get('hash');
  params.delete('hash');

  // Sort and join
  const dataCheckString = Array.from(params.entries())
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([k, v]) => `${k}=${v}`)
    .join('\n');

  // Create secret key
  const secretKey = crypto
    .createHmac('sha256', 'WebAppData')
    .update(botToken)
    .digest();

  // Calculate hash
  const calculatedHash = crypto
    .createHmac('sha256', secretKey)
    .update(dataCheckString)
    .digest('hex');

  return calculatedHash === hash;
}
```

### Using in API
```javascript
app.post('/api/action', (req, res) => {
  const { initData } = req.body;

  if (!validateInitData(initData, process.env.BOT_TOKEN)) {
    return res.status(401).json({ error: 'Invalid initData' });
  }

  // Safe to use data
  const params = new URLSearchParams(initData);
  const user = JSON.parse(params.get('user'));
  // ...
});
```

### TON Connect not working on mobile

Severity: HIGH

Situation: Wallet connection fails on mobile Telegram

Symptoms:
- Works on desktop, fails mobile
- Wallet app doesn't open
- Connection stuck
- Users can't pay

Why this breaks:
Deep linking issues.
Wallet app not opening.
Return URL problems.
Different behavior iOS vs Android.

Recommended fix:

## TON Connect Mobile Issues

### Common Problems
1. Wallet doesn't open
2. Return to Mini App fails
3. Transaction confirmation lost

### Fixes
```jsx
// Use correct manifest
const manifestUrl = 'https://your-domain.com/tonconnect-manifest.json';

// Ensure HTTPS
// Localhost won't work on mobile

// Handle connection states
const [tonConnectUI] = useTonConnectUI();

useEffect(() => {
  return tonConnectUI.onStatusChange((wallet) => {
    if (wallet) {
      console.log('Connected:', wallet.account.address);
    }
  });
}, []);
```

### Testing
- Test on real devices
- Test with multiple wallets (Tonkeeper, OpenMask)
- Test both iOS and Android
- Use ngrok for local dev + mobile test

### Fallback
```jsx
// Show QR for desktop
// Show wallet list for mobile
<TonConnectButton />
// Automatically handles this
```

### Mini App feels slow and janky

Severity: MEDIUM

Situation: App lags, slow transitions, poor UX

Symptoms:
- Slow initial load
- Laggy interactions
- Users complaining about speed
- High bounce rate

Why this breaks:
Too much JavaScript.
No code splitting.
Large bundle size.
No loading optimization.

Recommended fix:

## Mini App Performance

### Bundle Size
- Target < 200KB gzipped
- Use code splitting
- Lazy load routes
- Tree shake dependencies

### Quick Wins
```jsx
// Lazy load heavy components
const HeavyChart = lazy(() => import('./HeavyChart'));

// Optimize images
<img loading="lazy" src="..." />

// Use CSS instead of JS animations
```

### Loading Strategy
```jsx
function App() {
  const [ready, setReady] = useState(false);

  useEffect(() => {
    // Show skeleton immediately
    // Load data in background
    Promise.all([
      loadUserData(),
      loadAppConfig(),
    ]).then(() => setReady(true));
  }, []);

  if (!ready) return <Skeleton />;
  return <MainApp />;
}
```

### Vite Optimization
```javascript
// vite.config.js
export default {
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
        }
      }
    }
  }
};
```

### Custom buttons instead of MainButton

Severity: MEDIUM

Situation: App has custom submit buttons that feel non-native

Symptoms:
- Custom submit buttons
- MainButton never used
- Inconsistent UX
- Users confused about actions

Why this breaks:
MainButton is expected UX.
Custom buttons feel foreign.
Inconsistent with Telegram.
Users don't know what to tap.

Recommended fix:

## Using MainButton Properly

### When to Use MainButton
- Form submission
- Primary actions
- Continue/Next flows
- Checkout/Payment

### Implementation
```javascript
const tg = window.Telegram.WebApp;

// Show for forms
function showMainButton(text, onClick) {
  tg.MainButton.setText(text);
  tg.MainButton.onClick(onClick);
  tg.MainButton.show();
}

// Hide when not needed
function hideMainButton() {
  tg.MainButton.hide();
  tg.MainButton.offClick();
}

// Loading state
function setMainButtonLoading(loading) {
  if (loading) {
    tg.MainButton.showProgress();
    tg.MainButton.disable();
  } else {
    tg.MainButton.hideProgress();
    tg.MainButton.enable();
  }
}
```

### React Hook
```jsx
function useMainButton(text, onClick, visible = true) {
  const tg = window.Telegram?.WebApp;

  useEffect(() => {
    if (!tg) return;

    if (visible) {
      tg.MainButton.setText(text);
      tg.MainButton.onClick(onClick);
      tg.MainButton.show();
    } else {
      tg.MainButton.hide();
    }

    return () => {
      tg.MainButton.offClick(onClick);
    };
  }, [text, onClick, visible]);
}
```

## Validation Checks

### No initData Validation

Severity: HIGH

Message: Not validating initData - security vulnerability.

Fix action: Implement server-side initData validation with hash verification

### Missing Telegram Web App Script

Severity: HIGH

Message: Telegram Web App script not included.

Fix action: Add <script src='https://telegram.org/js/telegram-web-app.js'></script>

### Not Calling tg.ready()

Severity: MEDIUM

Message: Not calling tg.ready() - Telegram may show loading state.

Fix action: Call window.Telegram.WebApp.ready() when app is ready

### Not Using Telegram Theme

Severity: MEDIUM

Message: Not adapting to Telegram theme colors.

Fix action: Use CSS variables from tg.themeParams for colors

### Missing Viewport Meta Tag

Severity: MEDIUM

Message: Missing viewport meta tag for mobile.

Fix action: Add <meta name='viewport' content='width=device-width, initial-scale=1.0'>

## Collaboration

### Delegation Triggers

- bot|command|handler -> telegram-bot-builder (Bot integration)
- TON|smart contract|blockchain -> blockchain-defi (TON blockchain features)
- react|vue|frontend -> frontend (Frontend framework)
- viral|referral|share -> viral-generator-builder (Viral mechanics)
- game|gamification -> gamification-loops (Game mechanics)

### Tap-to-Earn Game

Skills: telegram-mini-app, gamification-loops, telegram-bot-builder

Workflow:

```
1. Design game mechanics
2. Build Mini App with tap mechanics
3. Add referral/viral features
4. Integrate TON payments
5. Bot for notifications/onboarding
6. Launch and grow
```

### DeFi Mini App

Skills: telegram-mini-app, blockchain-defi, frontend

Workflow:

```
1. Design DeFi feature (swap, stake, etc.)
2. Integrate TON Connect
3. Build transaction UI
4. Add wallet management
5. Implement security measures
6. Deploy and audit
```

## Related Skills

Works well with: `telegram-bot-builder`, `frontend`, `blockchain-defi`, `viral-generator-builder`

## When to Use
- User mentions or implies: telegram mini app
- User mentions or implies: TWA
- User mentions or implies: telegram web app
- User mentions or implies: TON app
- User mentions or implies: mini app

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


---
name: templates
description: "Project scaffolding templates for new applications. Use when creating new projects from scratch. Contains 12 templates for various tech stacks."
risk: critical
source: community
date_added: "2026-02-27"
---

# Project Templates

> Quick-start templates for scaffolding new projects.

---

## 🎯 Selective Reading Rule

**Read ONLY the template matching user's project type!**

| Template | Tech Stack | When to Use |
|----------|------------|-------------|
| [nextjs-fullstack](nextjs-fullstack/TEMPLATE.md) | Next.js + Prisma | Full-stack web app |
| [nextjs-saas](nextjs-saas/TEMPLATE.md) | Next.js + Stripe | SaaS product |
| [nextjs-static](nextjs-static/TEMPLATE.md) | Next.js + Framer | Landing page |
| [express-api](express-api/TEMPLATE.md) | Express + JWT | REST API |
| [python-fastapi](python-fastapi/TEMPLATE.md) | FastAPI | Python API |
| [react-native-app](react-native-app/TEMPLATE.md) | Expo + Zustand | Mobile app |
| [flutter-app](flutter-app/TEMPLATE.md) | Flutter + Riverpod | Cross-platform |
| [electron-desktop](electron-desktop/TEMPLATE.md) | Electron + React | Desktop app |
| [chrome-extension](chrome-extension/TEMPLATE.md) | Chrome MV3 | Browser extension |
| [cli-tool](cli-tool/TEMPLATE.md) | Node.js + Commander | CLI app |
| [monorepo-turborepo](monorepo-turborepo/TEMPLATE.md) | Turborepo + pnpm | Monorepo |
| [astro-static](astro-static/TEMPLATE.md) | Astro + MDX | Blog / Docs |

---

## Usage

1. User says "create [type] app"
2. Match to appropriate template
3. Read ONLY that template's TEMPLATE.md
4. Follow its tech stack and structure

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

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


---
name: temporal-golang-pro
description: "Use when building durable distributed systems with Temporal Go SDK. Covers deterministic workflow rules, mTLS worker configs, and advanced patterns."
risk: safe
source: self
date_added: "2026-02-27"
---

# Temporal Go SDK (temporal-golang-pro)

## Overview

Expert-level guide for building resilient, scalable, and deterministic distributed systems using the Temporal Go SDK. This skill transforms vague orchestration requirements into production-grade Go implementations, focusing on durable execution, strict determinism, and enterprise-scale worker configuration.

## When to Use This Skill

- **Designing Distributed Systems**: When building microservices that require durable state and reliable orchestration.
- **Implementing Complex Workflows**: Using the Go SDK to handle long-running processes (days/months) or complex Saga patterns.
- **Optimizing Performance**: When workers need fine-tuned concurrency, mTLS security, or custom interceptors.
- **Ensuring Reliability**: Implementing idempotent activities, graceful error handling, and sophisticated retry policies.
- **Maintenance & Evolution**: Versioning running workflows or performing zero-downtime worker updates.

## Do not use this skill when

- Using Temporal with other SDKs (Python, Java, TypeScript) - refer to their specific `-pro` skills.
- The task is a simple request/response without durability or coordination needs.
- High-level design without implementation (use `workflow-orchestration-patterns`).

## Step-by-Step Guide

1.  **Gather Context**: Proactively ask for:
    - Target **Temporal Cluster** (Cloud vs. Self-hosted) and **Namespace**.
    - **Task Queue** names and expected throughput.
    - **Security requirements** (mTLS paths, authentication).
    - **Failure modes** and desired retry/timeout policies.
2.  **Verify Determinism**: Before suggesting workflow code, verify against these **5 Rules**:
    - No native Go concurrency (goroutines).
    - No native time (`time.Now`, `time.Sleep`).
    - No non-deterministic map iteration (must sort keys).
    - No direct external I/O or network calls.
    - No non-deterministic random numbers.
3.  **Implement Incrementally**: Start with shared Protobuf/Data classes, then Activities, then Workflows, and finally Workers.
4.  **Leverage Resources**: If the implementation requires advanced patterns (Sagas, Interceptors, Replay Testing), explicitly refer to the implementation playbook and testing strategies.

## Capabilities

### Go SDK Implementation

- **Worker Management**: Deep knowledge of `worker.Options`, including `MaxConcurrentActivityTaskPollers`, `WorkerStopTimeout`, and `StickyScheduleToStartTimeout`.
- **Interceptors**: Implementing Client, Worker, and Workflow interceptors for cross-cutting concerns (logging, tracing, auth).
- **Custom Data Converters**: Integrating Protobuf, encrypted payloads, or custom JSON marshaling.

### Advanced Workflow Patterns

- **Durable Concurrency**: Using `workflow.Go`, `workflow.Channel`, and `workflow.Selector` instead of native primitives.
- **Versioning**: Implementing safe code evolution using `workflow.GetVersion` and `workflow.GetReplaySafeLogger`.
- **Large-scale Processing**: Pattern for `ContinueAsNew` to manage history size limits (defaults: 50MB or 50K events).
- **Child Workflows**: Managing lifecycle, cancellation, and parent-child signal propagation.

### Testing & Observability

- **Testsuite Mastery**: Using `WorkflowTestSuite` for unit and functional testing with deterministic time control.
- **Mocking**: Sophisticated activity and child workflow mocking strategies.
- **Replay Testing**: Validating code changes against production event histories.
- **Metrics**: Configuring Prometheus/OpenTelemetry exporters for worker performance tracking.

## Examples

### Example 1: Versioned Workflow (Deterministic)

```go
// Note: imports omitted. Requires 'go.temporal.io/sdk/workflow', 'go.temporal.io/sdk/temporal', and 'time'.
func SubscriptionWorkflow(ctx workflow.Context, userID string) error {
    // 1. Versioning for logic evolution (v1 = DefaultVersion)
    v := workflow.GetVersion(ctx, "billing_logic", workflow.DefaultVersion, 2)

    for i := 0; i < 12; i++ {
        ao := workflow.ActivityOptions{
            StartToCloseTimeout: 5 * time.Minute,
            RetryPolicy: &temporal.RetryPolicy{MaximumAttempts: 3},
        }
        ctx = workflow.WithActivityOptions(ctx, ao)

        // 2. Activity Execution (Always handle errors)
        err := workflow.ExecuteActivity(ctx, ChargePaymentActivity, userID).Get(ctx, nil)
        if err != nil {
            workflow.GetLogger(ctx).Error("Payment failed", "Error", err)
            return err
        }

        // 3. Durable Sleep (Time-skipping safe)
        sleepDuration := 30 * 24 * time.Hour
        if v >= 2 {
            sleepDuration = 28 * 24 * time.Hour
        }

        if err := workflow.Sleep(ctx, sleepDuration); err != nil {
            return err
        }
    }
    return nil
}
```

### Example 2: Full mTLS Worker Setup

```go
func RunSecureWorker() error {
    // 1. Load Client Certificate and Key
    cert, err := tls.LoadX509KeyPair("client.pem", "client.key")
    if err != nil {
        return fmt.Errorf("failed to load client keys: %w", err)
    }

    // 2. Load CA Certificate for Server verification (Proper mTLS)
    caPem, err := os.ReadFile("ca.pem")
    if err != nil {
        return fmt.Errorf("failed to read CA cert: %w", err)
    }
    certPool := x509.NewCertPool()
    if !certPool.AppendCertsFromPEM(caPem) {
        return fmt.Errorf("failed to parse CA cert")
    }

    // 3. Dial Cluster with full TLS config
    c, err := client.Dial(client.Options{
        HostPort:  "temporal.example.com:7233",
        Namespace: "production",
        ConnectionOptions: client.ConnectionOptions{
            TLS: &tls.Config{
                Certificates: []tls.Certificate{cert},
                RootCAs:      certPool,
            },
        },
    })
    if err != nil {
        return fmt.Errorf("failed to dial temporal: %w", err)
    }
    defer c.Close()

    w := worker.New(c, "payment-queue", worker.Options{})
    w.RegisterWorkflow(SubscriptionWorkflow)

    if err := w.Run(worker.InterruptCh()); err != nil {
        return fmt.Errorf("worker run failed: %w", err)
    }
    return nil
}
```

### Example 3: Selector & Signal Integration

```go
func ApprovalWorkflow(ctx workflow.Context) (string, error) {
    var approved bool
    signalCh := workflow.GetSignalChannel(ctx, "approval-signal")

    // Use Selector to wait for multiple async events
    s := workflow.NewSelector(ctx)
    s.AddReceive(signalCh, func(c workflow.ReceiveChannel, _ bool) {
        c.Receive(ctx, &approved)
    })

    // Add 72-hour timeout timer
    s.AddReceive(workflow.NewTimer(ctx, 72*time.Hour).GetChannel(), func(c workflow.ReceiveChannel, _ bool) {
        approved = false
    })

    s.Select(ctx)

    if !approved {
        return "rejected", nil
    }
    return "approved", nil
}
```

## Best Practices

- ✅ **Do:** Always handle errors from `ExecuteActivity` and `client.Dial`.
- ✅ **Do:** Use `workflow.Go` and `workflow.Channel` for concurrency.
- ✅ **Do:** Sort map keys before iteration to maintain determinism.
- ✅ **Do:** Use `activity.RecordHeartbeat` for activities lasting > 1 minute.
- ✅ **Do:** Test logic compatibility using `replayer.ReplayWorkflowHistoryFromJSON`.
- ❌ **Don't:** Swallow errors with `_` or `log.Fatal` in production workers.
- ❌ **Don't:** Perform direct Network/Disk I/O inside a Workflow function.
- ❌ **Don't:** Rely on native `time.Now()` or `rand.Int()`.
- ❌ **Don't:** Apply this to simple cron jobs that don't require durability.

## Troubleshooting

- **Panic: Determinism Mismatch**: Usually caused by logic changes without `workflow.GetVersion` or non-deterministic code (e.g., native maps).
- **Error: History Size Exceeded**: History limit reached (default 50K events). Ensure `ContinueAsNew` is implemented.
- **Worker Hang**: Check `WorkerStopTimeout` and ensure all activities handle context cancellation.

## Limitations

- Does not cover Temporal Cloud UI navigation or TLS certificate provisioning workflows.
- Does not cover Temporal Java, Python, or TypeScript SDKs; refer to their dedicated `-pro` skills.
- Assumes Temporal Server v1.20+ and Go SDK v1.25+; older SDK versions may have different APIs.
- Does not cover experimental Temporal features (e.g., Nexus, Multi-cluster Replication).
- Does not address global namespace configuration or multi-region failover setup.
- Does not cover Temporal Worker versioning via the `worker-versioning` feature flag (experimental).

## Resources

- [Implementation Playbook](resources/implementation-playbook.md) - Deep dive into Go SDK patterns.
- [Testing Strategies](resources/testing-strategies.md) - Unit, Replay, and Integration testing for Go.
- [Temporal Go SDK Reference](https://pkg.go.dev/go.temporal.io/sdk)
- [Temporal Go Samples](https://github.com/temporalio/samples-go)

## Related Skills

- `grpc-golang` - Internal transport protocol and Protobuf design.
- `golang-pro` - General Go performance tuning and advanced syntax.
- `workflow-orchestration-patterns` - Language-agnostic orchestration strategy.


---
name: temporal-python-pro
description: Master Temporal workflow orchestration with Python SDK. Implements durable workflows, saga patterns, and distributed transactions. Covers async/await, testing strategies, and production deployment.
risk: critical
source: community
date_added: '2026-02-27'
---

## Use this skill when

- Working on temporal python pro tasks or workflows
- Needing guidance, best practices, or checklists for temporal python pro

## Do not use this skill when

- The task is unrelated to temporal python pro
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

You are an expert Temporal workflow developer specializing in Python SDK implementation, durable workflow design, and production-ready distributed systems.

## Purpose

Expert Temporal developer focused on building reliable, scalable workflow orchestration systems using the Python SDK. Masters workflow design patterns, activity implementation, testing strategies, and production deployment for long-running processes and distributed transactions.

## Capabilities

### Python SDK Implementation

**Worker Configuration and Startup**

- Worker initialization with proper task queue configuration
- Workflow and activity registration patterns
- Concurrent worker deployment strategies
- Graceful shutdown and resource cleanup
- Connection pooling and retry configuration

**Workflow Implementation Patterns**

- Workflow definition with `@workflow.defn` decorator
- Async/await workflow entry points with `@workflow.run`
- Workflow-safe time operations with `workflow.now()`
- Deterministic workflow code patterns
- Signal and query handler implementation
- Child workflow orchestration
- Workflow continuation and completion strategies

**Activity Implementation**

- Activity definition with `@activity.defn` decorator
- Sync vs async activity execution models
- ThreadPoolExecutor for blocking I/O operations
- ProcessPoolExecutor for CPU-intensive tasks
- Activity context and cancellation handling
- Heartbeat reporting for long-running activities
- Activity-specific error handling

### Async/Await and Execution Models

**Three Execution Patterns** (Source: docs.temporal.io):

1. **Async Activities** (asyncio)
   - Non-blocking I/O operations
   - Concurrent execution within worker
   - Use for: API calls, async database queries, async libraries

2. **Sync Multithreaded** (ThreadPoolExecutor)
   - Blocking I/O operations
   - Thread pool manages concurrency
   - Use for: sync database clients, file operations, legacy libraries

3. **Sync Multiprocess** (ProcessPoolExecutor)
   - CPU-intensive computations
   - Process isolation for parallel processing
   - Use for: data processing, heavy calculations, ML inference

**Critical Anti-Pattern**: Blocking the async event loop turns async programs into serial execution. Always use sync activities for blocking operations.

### Error Handling and Retry Policies

**ApplicationError Usage**

- Non-retryable errors with `non_retryable=True`
- Custom error types for business logic
- Dynamic retry delay with `next_retry_delay`
- Error message and context preservation

**RetryPolicy Configuration**

- Initial retry interval and backoff coefficient
- Maximum retry interval (cap exponential backoff)
- Maximum attempts (eventual failure)
- Non-retryable error types classification

**Activity Error Handling**

- Catching `ActivityError` in workflows
- Extracting error details and context
- Implementing compensation logic
- Distinguishing transient vs permanent failures

**Timeout Configuration**

- `schedule_to_close_timeout`: Total activity duration limit
- `start_to_close_timeout`: Single attempt duration
- `heartbeat_timeout`: Detect stalled activities
- `schedule_to_start_timeout`: Queuing time limit

### Signal and Query Patterns

**Signals** (External Events)

- Signal handler implementation with `@workflow.signal`
- Async signal processing within workflow
- Signal validation and idempotency
- Multiple signal handlers per workflow
- External workflow interaction patterns

**Queries** (State Inspection)

- Query handler implementation with `@workflow.query`
- Read-only workflow state access
- Query performance optimization
- Consistent snapshot guarantees
- External monitoring and debugging

**Dynamic Handlers**

- Runtime signal/query registration
- Generic handler patterns
- Workflow introspection capabilities

### State Management and Determinism

**Deterministic Coding Requirements**

- Use `workflow.now()` instead of `datetime.now()`
- Use `workflow.random()` instead of `random.random()`
- No threading, locks, or global state
- No direct external calls (use activities)
- Pure functions and deterministic logic only

**State Persistence**

- Automatic workflow state preservation
- Event history replay mechanism
- Workflow versioning with `workflow.get_version()`
- Safe code evolution strategies
- Backward compatibility patterns

**Workflow Variables**

- Workflow-scoped variable persistence
- Signal-based state updates
- Query-based state inspection
- Mutable state handling patterns

### Type Hints and Data Classes

**Python Type Annotations**

- Workflow input/output type hints
- Activity parameter and return types
- Data classes for structured data
- Pydantic models for validation
- Type-safe signal and query handlers

**Serialization Patterns**

- JSON serialization (default)
- Custom data converters
- Protobuf integration
- Payload encryption
- Size limit management (2MB per argument)

### Testing Strategies

**WorkflowEnvironment Testing**

- Time-skipping test environment setup
- Instant execution of `workflow.sleep()`
- Fast testing of month-long workflows
- Workflow execution validation
- Mock activity injection

**Activity Testing**

- ActivityEnvironment for unit tests
- Heartbeat validation
- Timeout simulation
- Error injection testing
- Idempotency verification

**Integration Testing**

- Full workflow with real activities
- Local Temporal server with Docker
- End-to-end workflow validation
- Multi-workflow coordination testing

**Replay Testing**

- Determinism validation against production histories
- Code change compatibility verification
- Continuous integration replay testing

### Production Deployment

**Worker Deployment Patterns**

- Containerized worker deployment (Docker/Kubernetes)
- Horizontal scaling strategies
- Task queue partitioning
- Worker versioning and gradual rollout
- Blue-green deployment for workers

**Monitoring and Observability**

- Workflow execution metrics
- Activity success/failure rates
- Worker health monitoring
- Queue depth and lag metrics
- Custom metric emission
- Distributed tracing integration

**Performance Optimization**

- Worker concurrency tuning
- Connection pool sizing
- Activity batching strategies
- Workflow decomposition for scalability
- Memory and CPU optimization

**Operational Patterns**

- Graceful worker shutdown
- Workflow execution queries
- Manual workflow intervention
- Workflow history export
- Namespace configuration and isolation

## When to Use Temporal Python

**Ideal Scenarios**:

- Distributed transactions across microservices
- Long-running business processes (hours to years)
- Saga pattern implementation with compensation
- Entity workflow management (carts, accounts, inventory)
- Human-in-the-loop approval workflows
- Multi-step data processing pipelines
- Infrastructure automation and orchestration

**Key Benefits**:

- Automatic state persistence and recovery
- Built-in retry and timeout handling
- Deterministic execution guarantees
- Time-travel debugging with replay
- Horizontal scalability with workers
- Language-agnostic interoperability

## Common Pitfalls

**Determinism Violations**:

- Using `datetime.now()` instead of `workflow.now()`
- Random number generation with `random.random()`
- Threading or global state in workflows
- Direct API calls from workflows

**Activity Implementation Errors**:

- Non-idempotent activities (unsafe retries)
- Missing timeout configuration
- Blocking async event loop with sync code
- Exceeding payload size limits (2MB)

**Testing Mistakes**:

- Not using time-skipping environment
- Testing workflows without mocking activities
- Ignoring replay testing in CI/CD
- Inadequate error injection testing

**Deployment Issues**:

- Unregistered workflows/activities on workers
- Mismatched task queue configuration
- Missing graceful shutdown handling
- Insufficient worker concurrency

## Integration Patterns

**Microservices Orchestration**

- Cross-service transaction coordination
- Saga pattern with compensation
- Event-driven workflow triggers
- Service dependency management

**Data Processing Pipelines**

- Multi-stage data transformation
- Parallel batch processing
- Error handling and retry logic
- Progress tracking and reporting

**Business Process Automation**

- Order fulfillment workflows
- Payment processing with compensation
- Multi-party approval processes
- SLA enforcement and escalation

## Best Practices

**Workflow Design**:

1. Keep workflows focused and single-purpose
2. Use child workflows for scalability
3. Implement idempotent activities
4. Configure appropriate timeouts
5. Design for failure and recovery

**Testing**:

1. Use time-skipping for fast feedback
2. Mock activities in workflow tests
3. Validate replay with production histories
4. Test error scenarios and compensation
5. Achieve high coverage (≥80% target)

**Production**:

1. Deploy workers with graceful shutdown
2. Monitor workflow and activity metrics
3. Implement distributed tracing
4. Version workflows carefully
5. Use workflow queries for debugging

## Resources

**Official Documentation**:

- Python SDK: python.temporal.io
- Core Concepts: docs.temporal.io/workflows
- Testing Guide: docs.temporal.io/develop/python/testing-suite
- Best Practices: docs.temporal.io/develop/best-practices

**Architecture**:

- Temporal Architecture: github.com/temporalio/temporal/blob/main/docs/architecture/README.md
- Testing Patterns: github.com/temporalio/temporal/blob/main/docs/development/testing.md

**Key Takeaways**:

1. Workflows = orchestration, Activities = external calls
2. Determinism is mandatory for workflows
3. Idempotency is critical for activities
4. Test with time-skipping for fast feedback
5. Monitor and observe in production

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


---
name: temporal-python-testing
description: "Comprehensive testing approaches for Temporal workflows using pytest, progressive disclosure resources for specific testing scenarios."
risk: critical
source: community
date_added: "2026-02-27"
---

# Temporal Python Testing Strategies

Comprehensive testing approaches for Temporal workflows using pytest, progressive disclosure resources for specific testing scenarios.

## Do not use this skill when

- The task is unrelated to temporal python testing strategies
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Use this skill when

- **Unit testing workflows** - Fast tests with time-skipping
- **Integration testing** - Workflows with mocked activities
- **Replay testing** - Validate determinism against production histories
- **Local development** - Set up Temporal server and pytest
- **CI/CD integration** - Automated testing pipelines
- **Coverage strategies** - Achieve ≥80% test coverage

## Testing Philosophy

**Recommended Approach** (Source: docs.temporal.io/develop/python/testing-suite):

- Write majority as integration tests
- Use pytest with async fixtures
- Time-skipping enables fast feedback (month-long workflows → seconds)
- Mock activities to isolate workflow logic
- Validate determinism with replay testing

**Three Test Types**:

1. **Unit**: Workflows with time-skipping, activities with ActivityEnvironment
2. **Integration**: Workers with mocked activities
3. **End-to-end**: Full Temporal server with real activities (use sparingly)

## Available Resources

This skill provides detailed guidance through progressive disclosure. Load specific resources based on your testing needs:

### Unit Testing Resources

**File**: `resources/unit-testing.md`
**When to load**: Testing individual workflows or activities in isolation
**Contains**:

- WorkflowEnvironment with time-skipping
- ActivityEnvironment for activity testing
- Fast execution of long-running workflows
- Manual time advancement patterns
- pytest fixtures and patterns

### Integration Testing Resources

**File**: `resources/integration-testing.md`
**When to load**: Testing workflows with mocked external dependencies
**Contains**:

- Activity mocking strategies
- Error injection patterns
- Multi-activity workflow testing
- Signal and query testing
- Coverage strategies

### Replay Testing Resources

**File**: `resources/replay-testing.md`
**When to load**: Validating determinism or deploying workflow changes
**Contains**:

- Determinism validation
- Production history replay
- CI/CD integration patterns
- Version compatibility testing

### Local Development Resources

**File**: `resources/local-setup.md`
**When to load**: Setting up development environment
**Contains**:

- Docker Compose configuration
- pytest setup and configuration
- Coverage tool integration
- Development workflow

## Quick Start Guide

### Basic Workflow Test

```python
import pytest
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker

@pytest.fixture
async def workflow_env():
    env = await WorkflowEnvironment.start_time_skipping()
    yield env
    await env.shutdown()

@pytest.mark.asyncio
async def test_workflow(workflow_env):
    async with Worker(
        workflow_env.client,
        task_queue="test-queue",
        workflows=[YourWorkflow],
        activities=[your_activity],
    ):
        result = await workflow_env.client.execute_workflow(
            YourWorkflow.run,
            args,
            id="test-wf-id",
            task_queue="test-queue",
        )
        assert result == expected
```

### Basic Activity Test

```python
from temporalio.testing import ActivityEnvironment

async def test_activity():
    env = ActivityEnvironment()
    result = await env.run(your_activity, "test-input")
    assert result == expected_output
```

## Coverage Targets

**Recommended Coverage** (Source: docs.temporal.io best practices):

- **Workflows**: ≥80% logic coverage
- **Activities**: ≥80% logic coverage
- **Integration**: Critical paths with mocked activities
- **Replay**: All workflow versions before deployment

## Key Testing Principles

1. **Time-Skipping** - Month-long workflows test in seconds
2. **Mock Activities** - Isolate workflow logic from external dependencies
3. **Replay Testing** - Validate determinism before deployment
4. **High Coverage** - ≥80% target for production workflows
5. **Fast Feedback** - Unit tests run in milliseconds

## How to Use Resources

**Load specific resource when needed**:

- "Show me unit testing patterns" → Load `resources/unit-testing.md`
- "How do I mock activities?" → Load `resources/integration-testing.md`
- "Setup local Temporal server" → Load `resources/local-setup.md`
- "Validate determinism" → Load `resources/replay-testing.md`

## Additional References

- Python SDK Testing: docs.temporal.io/develop/python/testing-suite
- Testing Patterns: github.com/temporalio/temporal/blob/main/docs/development/testing.md
- Python Samples: github.com/temporalio/samples-python

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


---
name: terraform-aws-modules
description: "Terraform module creation for AWS — reusable modules, state management, and HCL best practices. Use when building or reviewing Terraform AWS infrastructure."
risk: critical
source: community
date_added: "2026-02-27"
---
You are an expert in Terraform for AWS specializing in reusable module design, state management, and production-grade HCL patterns.

## Use this skill when

- Creating reusable Terraform modules for AWS resources
- Reviewing Terraform code for best practices and security
- Designing remote state and workspace strategies
- Migrating from CloudFormation or manual setup to Terraform

## Do not use this skill when

- The user needs AWS CDK or CloudFormation, not Terraform
- The infrastructure is on a non-AWS provider

## Instructions

1. Structure modules with clear `variables.tf`, `outputs.tf`, `main.tf`, and `versions.tf`.
2. Pin provider and module versions to avoid breaking changes.
3. Use remote state (S3 + DynamoDB locking) for team environments.
4. Apply `terraform fmt` and `terraform validate` before commits.
5. Use `for_each` over `count` for resources that need stable identity.
6. Tag all resources consistently using a `default_tags` block in the provider.

## Examples

### Example 1: Reusable VPC Module

```hcl
# modules/vpc/variables.tf
variable "name" { type = string }
variable "cidr" { type = string, default = "10.0.0.0/16" }
variable "azs" { type = list(string) }

# modules/vpc/main.tf
resource "aws_vpc" "this" {
  cidr_block           = var.cidr
  enable_dns_support   = true
  enable_dns_hostnames = true
  tags = { Name = var.name }
}

# modules/vpc/outputs.tf
output "vpc_id" { value = aws_vpc.this.id }
```

### Example 2: Remote State Backend

```hcl
terraform {
  backend "s3" {
    bucket         = "my-tf-state"
    key            = "prod/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "tf-lock"
    encrypt        = true
  }
}
```

## Best Practices

- ✅ **Do:** Pin provider versions in `versions.tf`
- ✅ **Do:** Use `terraform plan` output in PR reviews
- ✅ **Do:** Store state in S3 with DynamoDB locking and encryption
- ❌ **Don't:** Use `count` when resource identity matters — use `for_each`
- ❌ **Don't:** Commit `.tfstate` files to version control

## Troubleshooting

**Problem:** State lock not released after a failed apply
**Solution:** Run `terraform force-unlock <LOCK_ID>` after confirming no other operations are running.

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


---
name: terraform-infrastructure
description: "Terraform infrastructure as code workflow for provisioning cloud resources, creating reusable modules, and managing infrastructure at scale."
category: granular-workflow-bundle
risk: safe
source: personal
date_added: "2026-02-27"
---

# Terraform Infrastructure Workflow

## Overview

Specialized workflow for infrastructure as code using Terraform including resource provisioning, module creation, state management, and multi-environment deployments.

## When to Use This Workflow

Use this workflow when:
- Provisioning cloud infrastructure
- Creating Terraform modules
- Managing multi-environment infra
- Implementing IaC best practices
- Setting up Terraform workflows

## Workflow Phases

### Phase 1: Terraform Setup

#### Skills to Invoke
- `terraform-skill` - Terraform basics
- `terraform-specialist` - Advanced Terraform

#### Actions
1. Initialize Terraform
2. Configure backend
3. Set up providers
4. Configure variables
5. Create outputs

#### Copy-Paste Prompts
```
Use @terraform-skill to set up Terraform project
```

### Phase 2: Resource Provisioning

#### Skills to Invoke
- `terraform-module-library` - Terraform modules
- `cloud-architect` - Cloud architecture

#### Actions
1. Design infrastructure
2. Create resource definitions
3. Configure networking
4. Set up compute
5. Add storage

#### Copy-Paste Prompts
```
Use @terraform-module-library to provision cloud resources
```

### Phase 3: Module Creation

#### Skills to Invoke
- `terraform-module-library` - Module creation

#### Actions
1. Design module interface
2. Create module structure
3. Define variables/outputs
4. Add documentation
5. Test module

#### Copy-Paste Prompts
```
Use @terraform-module-library to create reusable Terraform module
```

### Phase 4: State Management

#### Skills to Invoke
- `terraform-specialist` - State management

#### Actions
1. Configure remote backend
2. Set up state locking
3. Implement workspaces
4. Configure state access
5. Set up backup

#### Copy-Paste Prompts
```
Use @terraform-specialist to configure Terraform state
```

### Phase 5: Multi-Environment

#### Skills to Invoke
- `terraform-specialist` - Multi-environment

#### Actions
1. Design environment structure
2. Create environment configs
3. Set up variable files
4. Configure isolation
5. Test deployments

#### Copy-Paste Prompts
```
Use @terraform-specialist to set up multi-environment Terraform
```

### Phase 6: CI/CD Integration

#### Skills to Invoke
- `cicd-automation-workflow-automate` - CI/CD
- `github-actions-templates` - GitHub Actions

#### Actions
1. Create CI pipeline
2. Configure plan/apply
3. Set up approvals
4. Add validation
5. Test pipeline

#### Copy-Paste Prompts
```
Use @cicd-automation-workflow-automate to create Terraform CI/CD
```

### Phase 7: Security

#### Skills to Invoke
- `secrets-management` - Secrets management
- `terraform-specialist` - Security

#### Actions
1. Configure secrets
2. Set up encryption
3. Implement policies
4. Add compliance
5. Audit access

#### Copy-Paste Prompts
```
Use @secrets-management to secure Terraform secrets
```

## Quality Gates

- [ ] Resources provisioned
- [ ] Modules working
- [ ] State configured
- [ ] Multi-env tested
- [ ] CI/CD working
- [ ] Security verified

## Related Workflow Bundles

- `cloud-devops` - Cloud/DevOps
- `kubernetes-deployment` - Kubernetes
- `aws-infrastructure` - AWS specific

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