SuperAPI AI Directory

telegram-dev

Coding & development

View repository

Updated 10-15 10:42

About this skill

Telegram Ecosystem Development Skills

Comprehensive Telegram development guide, covering the complete technology stack for Bot development, Mini Apps (Web Apps), and client development.

When to Use This Skill

Use this skill when you need help with the following:

  • Develop Telegram Bots (message bots)
  • Create Telegram Mini Apps (mini programs)
  • Build custom Telegram clients
  • Integrate Telegram payments and business features
  • Implement Webhook and long polling
  • Use Telegram authentication and storage
  • Handle messages, media, and files
  • Implement inline mode and keyboards

Telegram Development Ecosystem Overview

Three Core APIs

  1. Bot API - Create bot programs

    • HTTP interface, simple and easy to use
    • Automatically handles encryption and communication
    • Suitable for: chatbots, automation tools
  2. Mini Apps API (Web Apps) - Create web applications

    • JavaScript interface
    • Runs inside Telegram
    • Suitable for: mini programs, games, e-commerce
  3. Telegram API & TDLib - Create clients

    • Complete Telegram protocol implementation
    • Supports all platforms
    • Suitable for: custom clients, enterprise applications

Bot API Development

Quick Start

API endpoint:

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

Get Bot Token:

  1. Talk to @BotFather
  2. Send /newbot
  3. Set the name as prompted
  4. Get the token

First 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

Core API Methods

Update management:

  • getUpdates - Long polling to get updates
  • setWebhook - Set Webhook
  • deleteWebhook - Delete Webhook
  • getWebhookInfo - Query Webhook status

Message operations:

  • sendMessage - Send text message
  • sendPhoto / sendVideo / sendDocument - Send media
  • sendAudio / sendVoice - Send audio
  • sendLocation / sendVenue - Send location
  • editMessageText - Edit message
  • deleteMessage - Delete message
  • forwardMessage / copyMessage - Forward/copy message

Interactive elements:

  • sendPoll - Send poll (up to 12 options)
  • Inline keyboard (InlineKeyboardMarkup)
  • Reply keyboard (ReplyKeyboardMarkup)
  • answerCallbackQuery - Respond to callback queries

File operations:

  • getFile - Get file information
  • downloadFile - Download file
  • Supports files up to 2GB (local Bot API mode)

Payment features:

  • sendInvoice - Send invoice
  • answerPreCheckoutQuery - Process payment
  • Telegram Stars payments (up to 10,000 Stars)

Webhook Configuration

Set 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 example:

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

  • Must use HTTPS
  • Supports TLS 1.2+
  • Ports: 443, 80, 88, 8443
  • Publicly accessible URL

Inline Keyboard

Create inline keyboard:

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

Handle callbacks:

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

Inline Mode

Configure inline mode: Talk to @BotFather and send /setinline

Handle inline queries:

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

Initialize Mini App

HTML template:

<!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 Core API

Main WebApp object properties:

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

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

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

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

Main methods:

// 窗口控制
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 Controls

Main button (MainButton):

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

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

Secondary button (SecondaryButton):

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

Back button (BackButton):

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

Haptic feedback:

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

Storage API

Cloud storage:

// 保存数据
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);
});

Local storage:

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

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

Biometric authentication

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

Location and sensors

Get location:

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

Accelerometer:

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

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

Gyroscope:

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

Device orientation:

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

Payment integration

Initiate payment (Telegram Stars):

tg.openInvoice('https://t.me/$invoice_link', (status) => {
    if (status === 'paid') {
        console.log('支付成功');
    } else if (status === 'cancelled') {
        console.log('支付取消');
    } else if (status === 'failed') {
        console.log('支付失败');
    }
});

Data validation

Server-side validation of initData (Python):

import hmac
import hashlib
from urllib.parse import parse_qs

def validate_init_data(init_data, bot_token):
    # 解析数据
    parsed = parse_qs(init_data)
    received_hash = parsed.get('hash', [''])[0]
    
    # 移除 hash
    data_check_arr = []
    for key, value in parsed.items():
        if key != 'hash':
            data_check_arr.append(f"{key}={value[0]}")
    
    # 排序
    data_check_arr.sort()
    data_check_string = '\n'.join(data_check_arr)
    
    # 计算密钥
    secret_key = hmac.new(
        b"WebAppData",
        bot_token.encode(),
        hashlib.sha256
    ).digest()
    
    # 计算哈希
    calculated_hash = hmac.new(
        secret_key,
        data_check_string.encode(),
        hashlib.sha256
    ).hexdigest()
    
    return calculated_hash == received_hash

Launching Mini App

From keyboard button:

keyboard = {
    "keyboard": [[
        {
            "text": "打开应用",
            "web_app": {"url": "https://yourdomain.com/app"}
        }
    ]],
    "resize_keyboard": True
}

requests.post(
    f"{API_URL}/sendMessage",
    json={
        "chat_id": chat_id,
        "text": "点击按钮打开应用",
        "reply_markup": keyboard
    }
)

From inline button:

keyboard = {
    "inline_keyboard": [[
        {
            "text": "启动应用",
            "web_app": {"url": "https://yourdomain.com/app"}
        }
    ]]
}

From menu button: Talk to @BotFather:

/setmenubutton
→ 选择你的 Bot
→ 提供 URL: https://yourdomain.com/app

Client development (TDLib)

Using TDLib

Python example (python-telegram):

from telegram.client import Telegram

tg = Telegram(
    api_id='your_api_id',
    api_hash='your_api_hash',
    phone='+1234567890',
    database_encryption_key='changeme1234',
)

tg.login()

# 发送消息
result = tg.send_message(
    chat_id=123456789,
    text='Hello from TDLib!'
)

# 获取聊天列表
result = tg.get_chats()
result.wait()
chats = result.update

print(chats)

tg.stop()

MTProto Protocol

Features:

  • End-to-end encryption
  • High performance
  • Support for all Telegram features
  • Requires API ID/Hash (obtained from https://my.telegram.org )

Best Practices

Bot development

  1. Error handling

    try:
        response = requests.post(url, json=data, timeout=10)
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
    
  2. Rate limiting

    • Group messages: maximum 20 per minute
    • Private messages: maximum 30 per second
    • Global limit: avoid excessive frequency
  3. Use Webhook instead of long polling

    • More efficient
    • Lower latency
    • Better scalability
  4. Data validation

    • Always validate initData
    • Do not trust client data
    • Validate all operations server-side

Mini Apps development

  1. Responsive design

    // 监听主题变化
    tg.onEvent('themeChanged', () => {
        document.body.style.backgroundColor = tg.themeParams.bg_color;
    });
    
    // 监听视口变化
    tg.onEvent('viewportChanged', () => {
        console.log('新高度:', tg.viewportHeight);
    });
    
  2. Performance optimization

    • Minimize JavaScript bundle size
    • Use lazy loading
    • Optimize images and assets
  3. User experience

    • Adapt to dark/light theme
    • Use native UI controls (MainButton, etc.)
    • Provide haptic feedback
    • Respond quickly to user actions
  4. Security considerations

    • Enforce HTTPS
    • Validate initData
    • Do not store sensitive information on the client
    • Use SecureStorage to store keys

Common libraries and tools

Python

  • python-telegram-bot - Powerful bot framework
  • aiogram - Asynchronous bot framework
  • telethon / pyrogram - MTProto client

Node.js

  • node-telegram-bot-api - Bot API wrapper
  • telegraf - Modern bot framework
  • grammy - Lightweight framework

Other languages

  • PHP: telegram-bot-sdk
  • Go: telegram-bot-api
  • Java: TelegramBots
  • C#: Telegram.Bot

Reference resources

Official documentation

GitHub repositories

Tools

  • @BotFather - Create and manage Bots
  • https://my.telegram.org - Get API ID/Hash
  • Telegram Web App testing environment

Reference Files

This skill contains a detailed Telegram development resource index and complete implementation templates:

  • index.md - Complete resource links and quick navigation
  • Telegram_Bot_Buttons_and_Keyboard_Implementation_Templates.md - Interactive buttons and keyboard implementation guide (404 lines, 12 KB)
    • Detailed explanation of three button types (Inline/Reply/Command Menu)
    • Comparison of python-telegram-bot and Telethon dual implementations
    • Complete ready-to-use code examples and project structure
    • Handler system, error handling, and deployment solutions
  • Dynamic_View_Alignment_Implementation_Documentation.md - Telegram data display guide (407 lines, 12 KB)
    • Intelligent dynamic alignment algorithm (three-step method, O(n×m) complexity)
    • Perfect alignment solution for monospaced font environments
    • Intelligent number formatting system (automatic B/M/K abbreviation)
    • Professional display of leaderboards and data tables

These concise guides provide the core Telegram Bot development solutions:

  • All implementation methods for button and keyboard interaction
  • Professional formatting display of messages and data
  • Practical best practices and quick reference

Use this skill to master full-stack development of the Telegram ecosystem!