TE

telegram-dev

A comprehensive resource for building Telegram Bots and Web Apps.

Install

mkdir -p .claude/skills/telegram-dev && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/1982" && unzip -o skill.zip -d .claude/skills/telegram-dev && rm skill.zip

Installs to .claude/skills/telegram-dev

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Telegram 生态开发全栈指南 - 涵盖 Bot API、Mini Apps (Web Apps)、MTProto 客户端开发。包括消息处理、支付、内联模式、Webhook、认证、存储、传感器 API 等完整开发资源。
111 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Develop Telegram bots using Bot API
  • Create Telegram Mini Apps with JavaScript
  • Build custom clients using MTProto and TDLib
  • Configure Webhooks and long polling
  • Integrate payments and Telegram Stars
  • Implement inline modes and interactive keyboards

How it works

The skill provides API endpoints and code templates for interacting with Telegram's HTTP-based Bot API, JavaScript-based Mini Apps, and MTProto-based client libraries.

Inputs & outputs

You give it
Bot token or API credentials
You get back
Functional Telegram bot, Mini App, or client

When to use telegram-dev

  • Develop Telegram bots with Python
  • Build Telegram Mini Apps (Web Apps)
  • Configure Telegram Webhooks
  • Integrate payments into Telegram bots

About this skill

Telegram 生态开发技能

全面的 Telegram 开发指南,涵盖 Bot 开发、Mini Apps (Web Apps)、客户端开发的完整技术栈。

何时使用此技能

当需要以下帮助时使用此技能:

  • 开发 Telegram Bot(消息机器人)
  • 创建 Telegram Mini Apps(小程序)
  • 构建自定义 Telegram 客户端
  • 集成 Telegram 支付和业务功能
  • 实现 Webhook 和长轮询
  • 使用 Telegram 认证和存储
  • 处理消息、媒体和文件
  • 实现内联模式和键盘

Telegram 开发生态概览

三大核心 API

  1. Bot API - 创建机器人程序

    • HTTP 接口,简单易用
    • 自动处理加密和通信
    • 适合:聊天机器人、自动化工具
  2. Mini Apps API (Web Apps) - 创建 Web 应用

    • JavaScript 接口
    • 在 Telegram 内运行
    • 适合:小程序、游戏、电商
  3. Telegram API & TDLib - 创建客户端

    • 完整的 Telegram 协议实现
    • 支持所有平台
    • 适合:自定义客户端、企业应用

Bot API 开发

快速开始

API 端点:

https://api.telegram.org/bot<TOKEN>/METHOD_NAME

获取 Bot Token:

  1. 与 @BotFather 对话
  2. 发送 /newbot
  3. 按提示设置名称
  4. 获取 token

第一个 Bot (Python):

import requests

BOT_TOKEN = "your_bot_token_here"
API_URL = f"https://api.telegram.org/bot{BOT_TOKEN}"

# 发送消息
def send_message(chat_id, text):
    url = f"{API_URL}/sendMessage"
    data = {"chat_id": chat_id, "text": text}
    return requests.post(url, json=data)

# 获取更新(长轮询)
def get_updates(offset=None):
    url = f"{API_URL}/getUpdates"
    params = {"offset": offset, "timeout": 30}
    return requests.get(url, params=params).json()

# 主循环
offset = None
while True:
    updates = get_updates(offset)
    for update in updates.get("result", []):
        chat_id = update["message"]["chat"]["id"]
        text = update["message"]["text"]
        
        # 回复消息
        send_message(chat_id, f"你说了:{text}")
        
        offset = update["update_id"] + 1

核心 API 方法

更新管理:

  • getUpdates - 长轮询获取更新
  • setWebhook - 设置 Webhook
  • deleteWebhook - 删除 Webhook
  • getWebhookInfo - 查询 Webhook 状态

消息操作:

  • sendMessage - 发送文本消息
  • sendPhoto / sendVideo / sendDocument - 发送媒体
  • sendAudio / sendVoice - 发送音频
  • sendLocation / sendVenue - 发送位置
  • editMessageText - 编辑消息
  • deleteMessage - 删除消息
  • forwardMessage / copyMessage - 转发/复制消息

交互元素:

  • sendPoll - 发送投票(最多 12 个选项)
  • 内联键盘 (InlineKeyboardMarkup)
  • 回复键盘 (ReplyKeyboardMarkup)
  • answerCallbackQuery - 响应回调查询

文件操作:

  • getFile - 获取文件信息
  • downloadFile - 下载文件
  • 支持最大 2GB 文件(本地 Bot API 模式)

支付功能:

  • sendInvoice - 发送发票
  • answerPreCheckoutQuery - 处理支付
  • Telegram Stars 支付(最高 10,000 Stars)

Webhook 配置

设置 Webhook:

import requests

BOT_TOKEN = "your_token"
WEBHOOK_URL = "https://yourdomain.com/webhook"

requests.post(
    f"https://api.telegram.org/bot{BOT_TOKEN}/setWebhook",
    json={"url": WEBHOOK_URL}
)

Flask Webhook 示例:

from flask import Flask, request
import requests

app = Flask(__name__)
BOT_TOKEN = "your_token"

@app.route('/webhook', methods=['POST'])
def webhook():
    update = request.get_json()
    
    chat_id = update["message"]["chat"]["id"]
    text = update["message"]["text"]
    
    # 发送回复
    requests.post(
        f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage",
        json={"chat_id": chat_id, "text": f"收到: {text}"}
    )
    
    return "OK"

if __name__ == '__main__':
    app.run(port=5000)

Webhook 要求:

  • 必须使用 HTTPS
  • 支持 TLS 1.2+
  • 端口:443, 80, 88, 8443
  • 公共可访问的 URL

内联键盘

创建内联键盘:

def send_inline_keyboard(chat_id):
    keyboard = {
        "inline_keyboard": [
            [
                {"text": "按钮 1", "callback_data": "btn1"},
                {"text": "按钮 2", "callback_data": "btn2"}
            ],
            [
                {"text": "打开链接", "url": "https://example.com"}
            ]
        ]
    }
    
    requests.post(
        f"{API_URL}/sendMessage",
        json={
            "chat_id": chat_id,
            "text": "选择一个选项:",
            "reply_markup": keyboard
        }
    )

处理回调:

def handle_callback_query(callback_query):
    query_id = callback_query["id"]
    data = callback_query["data"]
    chat_id = callback_query["message"]["chat"]["id"]
    
    # 响应回调
    requests.post(
        f"{API_URL}/answerCallbackQuery",
        json={"callback_query_id": query_id, "text": f"你点击了 {data}"}
    )
    
    # 更新消息
    requests.post(
        f"{API_URL}/editMessageText",
        json={
            "chat_id": chat_id,
            "message_id": callback_query["message"]["message_id"],
            "text": f"你选择了:{data}"
        }
    )

内联模式

配置内联模式: 与 @BotFather 对话,发送 /setinline

处理内联查询:

def handle_inline_query(inline_query):
    query_id = inline_query["id"]
    query_text = inline_query["query"]
    
    # 创建结果
    results = [
        {
            "type": "article",
            "id": "1",
            "title": "结果 1",
            "input_message_content": {
                "message_text": f"你搜索了:{query_text}"
            }
        }
    ]
    
    requests.post(
        f"{API_URL}/answerInlineQuery",
        json={"inline_query_id": query_id, "results": results}
    )

Mini Apps (Web Apps) 开发

初始化 Mini App

HTML 模板:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://telegram.org/js/telegram-web-app.js"></script>
    <title>My Mini App</title>
</head>
<body>
    <h1>Telegram Mini App</h1>
    <button id="mainBtn">主按钮</button>
    
    <script>
        // 获取 Telegram WebApp 对象
        const tg = window.Telegram.WebApp;
        
        // 通知 Telegram 应用已准备好
        tg.ready();
        
        // 展开到全屏
        tg.expand();
        
        // 显示用户信息
        const user = tg.initDataUnsafe?.user;
        if (user) {
            console.log("用户名:", user.first_name);
            console.log("用户ID:", user.id);
        }
        
        // 配置主按钮
        tg.MainButton.text = "提交";
        tg.MainButton.show();
        tg.MainButton.onClick(() => {
            // 发送数据到 Bot
            tg.sendData(JSON.stringify({action: "submit"}));
        });
        
        // 添加返回按钮
        tg.BackButton.show();
        tg.BackButton.onClick(() => {
            tg.close();
        });
    </script>
</body>
</html>

Mini App 核心 API

WebApp 对象主要属性:

// 初始化数据
tg.initData           // 原始初始化字符串
tg.initDataUnsafe     // 解析后的对象

// 用户和主题
tg.initDataUnsafe.user       // 用户信息
tg.themeParams                // 主题颜色
tg.colorScheme                // 'light' 或 'dark'

// 状态
tg.isExpanded         // 是否全屏
tg.isFullscreen       // 是否全屏
tg.viewportHeight     // 视口高度
tg.platform           // 平台类型

// 版本
tg.version            // WebApp 版本

主要方法:

// 窗口控制
tg.ready()            // 标记应用准备就绪
tg.expand()           // 展开到全高度
tg.close()            // 关闭 Mini App
tg.requestFullscreen() // 请求全屏

// 数据发送
tg.sendData(data)     // 发送数据到 Bot

// 导航
tg.openLink(url)      // 打开外部链接
tg.openTelegramLink(url) // 打开 Telegram 链接

// 对话框
tg.showPopup(params, callback)  // 显示弹窗
tg.showAlert(message)           // 显示警告
tg.showConfirm(message)         // 显示确认

// 分享
tg.shareMessage(message)        // 分享消息
tg.shareUrl(url)                // 分享链接

UI 控件

主按钮 (MainButton):

tg.MainButton.setText("点击我");
tg.MainButton.show();
tg.MainButton.enable();
tg.MainButton.showProgress();  // 显示加载
tg.MainButton.hideProgress();

tg.MainButton.onClick(() => {
    console.log("主按钮被点击");
});

次要按钮 (SecondaryButton):

tg.SecondaryButton.setText("取消");
tg.SecondaryButton.show();
tg.SecondaryButton.onClick(() => {
    tg.close();
});

返回按钮 (BackButton):

tg.BackButton.show();
tg.BackButton.onClick(() => {
    // 返回逻辑
});

触觉反馈:

tg.HapticFeedback.impactOccurred('light');  // light, medium, heavy
tg.HapticFeedback.notificationOccurred('success'); // success, warning, error
tg.HapticFeedback.selectionChanged();

存储 API

云存储:

// 保存数据
tg.CloudStorage.setItem('key', 'value', (error, success) => {
    if (success) console.log('保存成功');
});

// 获取数据
tg.CloudStorage.getItem('key', (error, value) => {
    console.log('值:', value);
});

// 删除数据
tg.CloudStorage.removeItem('key');

// 获取所有键
tg.CloudStorage.getKeys((error, keys) => {
    console.log('所有键:', keys);
});

本地存储:

// 普通本地存储
localStorage.setItem('key', 'value');
const value = localStorage.getItem('key');

// 安全存储(需要生物识别)
tg.SecureStorage.setItem('secret', 'value', callback);
tg.SecureStorage.getItem('secret', callback);

生物识别认证

const bioManager = tg.BiometricManager;

// 初始化
bioManager.init(() => {
    if (bioManager.isInited) {
        console.log('支持的类型:', bioManager.biometricType);
        // 'finger', 'face', 'unknown'
        
        if (bioManager.isAccessGranted) {
            // 已授权,可以使用
        } else {
            // 请求授权
            bioManager.requestAccess({reason: '需要验证身份'}, (success) => {
                if (success) {
                    console.log('授权成功');
                }
            });
        }
    }
});

// 执行认证
bioManager.authenticate({reason: '确认操作'}, (success, token) => {
    if (success) {
        console.log('认证成功,token:', token);
    }
});

位置和传感器

获取位置:

tg.LocationManager.init(() => {
    if (tg.LocationManager.isInited) {
        tg.LocationManager.getLocation((location) => {
            console.log('纬度:', location.latitude);
            console.log('经度:', location.longitude);
        });
    }
});

加速度计:

tg.Accelerometer.start({refresh_rate: 100}, (started) => {
    if (started) {
        tg.Accelerometer.onEvent((event) => {
            console.log('加速度:', event.x, event.y, event.z);
        });
    }
});

// 停止
tg.Accelerometer.stop();

陀螺仪:

tg.Gyroscope.start({refresh_rate: 100}, callback);
tg.Gyroscope.onEvent((event) => {
    console.log('旋转速度:', event.x, event.y, event.z);
});

设备方向:

tg.DeviceOrientation.start({refresh_rate: 100}, callback);
tg.DeviceOrientation.onEvent((event) => {
    console.log('方向:', event.absolute, event.alpha, event.beta, event.gamma);
});

支付集成

**发起支付 (Telegram S


Content truncated.

When not to use it

  • When requiring non-Telegram specific messaging protocols
  • When building applications that do not run within the Telegram ecosystem

Prerequisites

Telegram accountBot token from @BotFatherAPI ID and Hash from my.telegram.org

Limitations

  • Requires HTTPS for Webhook configurations
  • Subject to Telegram's message rate limits
  • File uploads limited to 2GB in local Bot API mode

How it compares

It offers a centralized repository of implementation templates and specific Telegram-native patterns compared to manual API documentation lookups.

Compared to similar skills

telegram-dev side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
telegram-dev (this skill)28moReviewIntermediate
add-new-setting-field17moNo flagsIntermediate
shopify-apps14moReviewIntermediate
ccxt-typescript16moReviewBeginner

Try saying

Example prompts that trigger this skill in your AI assistant.

You might also like

add-new-setting-field

tsukumijima

【設定追加時は必ず参照】KonomiTV に新しい設定 (v-switch/v-select など) を追加する際の必須手順。SettingsStore.ts / Settings.ts / config.py / Settings/*.vue への追加が必要

12

shopify-apps

alinaqi

Shopify app development - Remix, Admin API, checkout extensions

19

ccxt-typescript

ccxt

CCXT cryptocurrency exchange library for TypeScript and JavaScript developers (Node.js and browser). Covers both REST API (standard) and WebSocket API (real-time). Helps install CCXT, connect to exchanges, fetch market data, place orders, stream live tickers/orderbooks, handle authentication, and manage errors. Use when working with crypto exchanges in TypeScript/JavaScript projects, trading bots, arbitrage systems, or portfolio management tools. Includes both REST and WebSocket examples.

15

openrouter-hello-world

jeremylongshore

Create your first OpenRouter API request with a simple example. Use when learning OpenRouter or testing your setup. Trigger with phrases like 'openrouter hello world', 'openrouter first request', 'openrouter quickstart', 'test openrouter'.

733

langfuse-install-auth

jeremylongshore

Install and configure Langfuse SDK authentication for LLM observability. Use when setting up a new Langfuse integration, configuring API keys, or initializing Langfuse tracing in your project. Trigger with phrases like "install langfuse", "setup langfuse", "langfuse auth", "configure langfuse API key", "langfuse tracing setup".

01

perplexity-known-pitfalls

jeremylongshore

Identify and avoid Perplexity anti-patterns and common integration mistakes. Use when reviewing Perplexity code for issues, onboarding new developers, or auditing existing Perplexity integrations for best practices violations. Trigger with phrases like "perplexity mistakes", "perplexity anti-patterns", "perplexity pitfalls", "perplexity what not to do", "perplexity code review".

01

Search skills

Search the agent skills registry