docs: 更新文档和技能

This commit is contained in:
tukuaiai
2025-12-17 20:39:02 +08:00
parent 5b3bddb974
commit fedc55f74c
23 changed files with 956 additions and 346 deletions
-1
View File
@@ -1,4 +1,3 @@
TRANSLATED CONTENT:
# skills/claude-skills
This directory is a **meta-skill**: it turns arbitrary domain material (docs/APIs/code/specs) into a reusable Skill (`SKILL.md` + `references/` + `scripts/` + `assets/`), and ships an executable quality gate + scaffolding.
-1
View File
@@ -1,4 +1,3 @@
TRANSLATED CONTENT:
---
name: claude-skills
description: "Claude Skills meta-skill: extract domain material (docs/APIs/code/specs) into a reusable Skill (SKILL.md + references/scripts/assets), and refactor existing Skills for clarity, activation reliability, and quality gates."
@@ -1,4 +1,3 @@
TRANSLATED CONTENT:
---
name: {{skill_name}}
description: "[Domain] end-to-end capability: includes [capability 1], [capability 2], [capability 3]. Use when [decidable triggers]."
@@ -1,4 +1,3 @@
TRANSLATED CONTENT:
---
name: {{skill_name}}
description: "[Domain] capability: includes [key capability]. Use when [decidable triggers]."
@@ -1,4 +1,3 @@
TRANSLATED CONTENT:
# Skills
Skills are folders of instructions, scripts, and resources that Claude loads dynamically to improve performance on specialized tasks. Skills teach Claude how to complete specific tasks in a repeatable way, whether that's creating documents with your company's brand guidelines, analyzing data using your organization's specific workflows, or automating personal tasks.
@@ -1,4 +1,3 @@
TRANSLATED CONTENT:
# Anti-Patterns (And How to Fix Them)
This file documents common ways Skills fail in practice. Use it when refactoring existing Skills.
@@ -1,4 +1,3 @@
TRANSLATED CONTENT:
# Claude Skills Meta-Skill Reference Index
This directory contains long-form documentation that supports the `claude-skills` meta-skill.
@@ -1,4 +1,3 @@
TRANSLATED CONTENT:
# Quality Checklist (Production Gate)
Use this checklist to decide whether a Skill is shippable. It is intentionally biased toward reliability and maintainability over "more content".
@@ -1,4 +1,3 @@
TRANSLATED CONTENT:
# Skill Spec (This Repo)
This document defines what a "production-grade Skill" means in this repository. Use it as the source of truth when creating or refactoring anything under `skills/`.
@@ -1,4 +1,3 @@
TRANSLATED CONTENT:
#!/usr/bin/env bash
set -euo pipefail
@@ -1,4 +1,3 @@
TRANSLATED CONTENT:
#!/usr/bin/env bash
set -euo pipefail
-1
View File
@@ -1,4 +1,3 @@
TRANSLATED CONTENT:
---
name: snapdom
description: snapDOM is a fast, accurate DOM-to-image capture tool that converts HTML elements into scalable SVG images. Use for capturing HTML elements, converting DOM to images (SVG, PNG, JPG, WebP), preserving styles, fonts, and pseudo-elements.
@@ -1,4 +1,3 @@
TRANSLATED CONTENT:
# Snapdom Documentation Index
## Categories
@@ -1,4 +1,3 @@
TRANSLATED CONTENT:
# Snapdom - Other
**Pages:** 1
+306 -307
View File
@@ -1,261 +1,260 @@
TRANSLATED CONTENT:
# Telegram 生态开发资源索引
# Telegram Ecosystem Development Resource Index
## 官方文档
## Official Documentation
### Bot API
**主文档:** https://core.telegram.org/bots/api
**描述:** Telegram Bot API 完整参考文档
**Main Documentation:** https://core.telegram.org/bots/api
**Description:** Complete reference documentation for the Telegram Bot API
**核心功能:**
- 消息发送和接收
- 媒体文件处理
- 内联模式
- 支付集成
- Webhook 配置
- 游戏和投票
**Core Features:**
- Sending and receiving messages
- Handling media files
- Inline mode
- Payment integration
- Webhook configuration
- Games and polls
### Mini Apps (Web Apps)
**主文档:** https://core.telegram.org/bots/webapps
**完整平台:** https://docs.telegram-mini-apps.com
**描述:** Telegram 小程序开发文档
**Main Documentation:** https://core.telegram.org/bots/webapps
**Full Platform:** https://docs.telegram-mini-apps.com
**Description:** Development documentation for Telegram Mini Apps
**核心功能:**
**Core Features:**
- WebApp API
- 主题和 UI 控件
- 存储(Cloud/Device/Secure
- 生物识别认证
- 位置和传感器
- 支付集成
- Themes and UI controls
- Storage (Cloud/Device/Secure)
- Biometric authentication
- Location and sensors
- Payment integration
### Telegram API & MTProto
**主文档:** https://core.telegram.org
**描述:** 完整的 Telegram 协议和客户端开发
**Main Documentation:** https://core.telegram.org
**Description:** Complete Telegram protocol and client development
**核心功能:**
- MTProto 协议
- TDLib 客户端库
- 认证和加密
- 文件操作
**Core Features:**
- MTProto protocol
- TDLib client library
- Authentication and encryption
- File operations
- Secret Chats
## 官方 GitHub 仓库
## Official GitHub Repositories
### Bot API 服务器
**仓库:** https://github.com/tdlib/telegram-bot-api
**描述:** Telegram Bot API 服务器实现
**特点:**
- 本地模式部署
- 支持大文件(最高 2000 MB
- C++ 实现
- TDLib 基础
### Bot API Server
**Repository:** https://github.com/tdlib/telegram-bot-api
**Description:** Implementation of the Telegram Bot API server
**Features:**
- Local mode deployment
- Support for large files (up to 2000 MB)
- C++ implementation
- Based on TDLib
### Android 客户端
**仓库:** https://github.com/DrKLO/Telegram
**描述:** 官方 Android 客户端源代码
**特点:**
- 完整的 Android 实现
### Android Client
**Repository:** https://github.com/DrKLO/Telegram
**Description:** Source code for the official Android client
**Features:**
- Complete Android implementation
- Material Design
- 可自定义编译
- Customizable compilation
### Desktop 客户端
**仓库:** https://github.com/telegramdesktop/tdesktop
**描述:** 官方桌面客户端 (Windows, macOS, Linux)
**特点:**
- Qt/C++ 实现
- 跨平台支持
- 完整功能
### Desktop Client
**Repository:** https://github.com/telegramdesktop/tdesktop
**Description:** Official desktop client (Windows, macOS, Linux)
**Features:**
- Qt/C++ implementation
- Cross-platform support
- Full functionality
### 官方组织
**组织页面:** https://github.com/orgs/TelegramOfficial/repositories
**包含:**
- Beta 版本
- 支持工具
- 示例代码
### Official Organization
**Organization Page:** https://github.com/orgs/TelegramOfficial/repositories
**Includes:**
- Beta versions
- Support tools
- Example code
## API 方法分类
## API Method Categories
### 更新管理
- `getUpdates` - 长轮询
- `setWebhook` - 设置 Webhook
- `deleteWebhook` - 删除 Webhook
- `getWebhookInfo` - Webhook 信息
### Update Management
- `getUpdates` - Long polling
- `setWebhook` - Set a webhook
- `deleteWebhook` - Delete a webhook
- `getWebhookInfo` - Webhook information
### 消息操作
**发送消息:**
- `sendMessage` - 文本消息
- `sendPhoto` - 图片
- `sendVideo` - 视频
- `sendDocument` - 文档
- `sendAudio` - 音频
- `sendVoice` - 语音
- `sendLocation` - 位置
- `sendVenue` - 地点
- `sendContact` - 联系人
- `sendPoll` - 投票
- `sendDice` - 骰子/飞镖
### Message Operations
**Sending Messages:**
- `sendMessage` - Text message
- `sendPhoto` - Photo
- `sendVideo` - Video
- `sendDocument` - Document
- `sendAudio` - Audio
- `sendVoice` - Voice
- `sendLocation` - Location
- `sendVenue` - Venue
- `sendContact` - Contact
- `sendPoll` - Poll
- `sendDice` - Dice/Darts
**编辑消息:**
- `editMessageText` - 编辑文本
- `editMessageCaption` - 编辑标题
- `editMessageMedia` - 编辑媒体
- `editMessageReplyMarkup` - 编辑键盘
- `deleteMessage` - 删除消息
**Editing Messages:**
- `editMessageText` - Edit text
- `editMessageCaption` - Edit caption
- `editMessageMedia` - Edit media
- `editMessageReplyMarkup` - Edit keyboard
- `deleteMessage` - Delete a message
**其他操作:**
- `forwardMessage` - 转发消息
- `copyMessage` - 复制消息
- `sendChatAction` - 发送动作(输入中...
**Other Operations:**
- `forwardMessage` - Forward a message
- `copyMessage` - Copy a message
- `sendChatAction` - Send an action (typing...)
### 文件操作
- `getFile` - 获取文件信息
- 文件下载 URL: `https://api.telegram.org/file/bot<token>/<file_path>`
- 文件上传:支持 multipart/form-data
- 最大文件:50 MB (标准), 2000 MB (本地 Bot API)
### File Operations
- `getFile` - Get file information
- File download URL: `https://api.telegram.org/file/bot<token>/<file_path>`
- File upload: Supports multipart/form-data
- Max file size: 50 MB (standard), 2000 MB (local Bot API)
### 内联模式
- `answerInlineQuery` - 响应内联查询
- 结果类型:article, photo, gif, video, audio, voice, document, location, venue, contact, game, sticker
### Inline Mode
- `answerInlineQuery` - Respond to an inline query
- Result types: article, photo, gif, video, audio, voice, document, location, venue, contact, game, sticker
### 回调查询
- `answerCallbackQuery` - 响应按钮点击
- 可显示通知或警告
### Callback Queries
- `answerCallbackQuery` - Respond to a button click
- Can display a notification or an alert
### 支付
- `sendInvoice` - 发送发票
- `answerPreCheckoutQuery` - 预结账
- `answerShippingQuery` - 配送查询
- 支持提供商:Stripe, Yandex.Money, Telegram Stars
### Payments
- `sendInvoice` - Send an invoice
- `answerPreCheckoutQuery` - Pre-checkout
- `answerShippingQuery` - Shipping query
- Supported providers: Stripe, Yandex.Money, Telegram Stars
### 游戏
- `sendGame` - 发送游戏
- `setGameScore` - 设置分数
- `getGameHighScores` - 获取排行榜
### Games
- `sendGame` - Send a game
- `setGameScore` - Set a score
- `getGameHighScores` - Get high scores
### 群组管理
- `kickChatMember` / `unbanChatMember` - 封禁/解封
- `restrictChatMember` - 限制权限
- `promoteChatMember` - 提升管理员
- `setChatTitle` / `setChatDescription` - 设置信息
- `setChatPhoto` - 设置头像
- `pinChatMessage` / `unpinChatMessage` - 置顶消息
### Group Management
- `kickChatMember` / `unbanChatMember` - Ban/unban
- `restrictChatMember` - Restrict permissions
- `promoteChatMember` - Promote to admin
- `setChatTitle` / `setChatDescription` - Set chat info
- `setChatPhoto` - Set chat photo
- `pinChatMessage` / `unpinChatMessage` - Pin/unpin a message
## Mini Apps API 详解
## Mini Apps API Details
### 初始化
### Initialization
```javascript
const tg = window.Telegram.WebApp;
tg.ready();
tg.expand();
```
### 主要对象
- **WebApp** - 主接口
- **MainButton** - 主按钮
- **SecondaryButton** - 次要按钮
- **BackButton** - 返回按钮
- **SettingsButton** - 设置按钮
- **HapticFeedback** - 触觉反馈
- **CloudStorage** - 云存储
- **BiometricManager** - 生物识别
- **LocationManager** - 位置服务
- **Accelerometer** - 加速度计
- **Gyroscope** - 陀螺仪
- **DeviceOrientation** - 设备方向
### Main Objects
- **WebApp** - Main interface
- **MainButton** - Main button
- **SecondaryButton** - Secondary button
- **BackButton** - Back button
- **SettingsButton** - Settings button
- **HapticFeedback** - Haptic feedback
- **CloudStorage** - Cloud storage
- **BiometricManager** - Biometrics
- **LocationManager** - Location services
- **Accelerometer** - Accelerometer
- **Gyroscope** - Gyroscope
- **DeviceOrientation** - Device orientation
### 事件系统
40+ 事件包括:
- `themeChanged` - 主题改变
- `viewportChanged` - 视口改变
- `mainButtonClicked` - 主按钮点击
- `backButtonClicked` - 返回按钮点击
- `settingsButtonClicked` - 设置按钮点击
- `invoiceClosed` - 支付完成
- `popupClosed` - 弹窗关闭
- `qrTextReceived` - 扫码结果
- `clipboardTextReceived` - 剪贴板文本
- `writeAccessRequested` - 写入权限请求
- `contactRequested` - 联系人请求
### Event System
40+ events including:
- `themeChanged` - Theme changed
- `viewportChanged` - Viewport changed
- `mainButtonClicked` - Main button clicked
- `backButtonClicked` - Back button clicked
- `settingsButtonClicked` - Settings button clicked
- `invoiceClosed` - Payment completed
- `popupClosed` - Popup closed
- `qrTextReceived` - QR code scan result
- `clipboardTextReceived` - Clipboard text
- `writeAccessRequested` - Write access requested
- `contactRequested` - Contact requested
### 主题参数
### Theme Parameters
```javascript
tg.themeParams = {
bg_color, // 背景色
text_color, // 文本色
hint_color, // 提示色
link_color, // 链接色
button_color, // 按钮色
button_text_color, // 按钮文本色
secondary_bg_color, // 次要背景色
header_bg_color, // 头部背景色
accent_text_color, // 强调文本色
section_bg_color, // 区块背景色
section_header_text_color, // 区块头文本色
subtitle_text_color, // 副标题色
destructive_text_color // 危险操作色
bg_color, // Background color
text_color, // Text color
hint_color, // Hint color
link_color, // Link color
button_color, // Button color
button_text_color, // Button text color
secondary_bg_color, // Secondary background color
header_bg_color, // Header background color
accent_text_color, // Accent text color
section_bg_color, // Section background color
section_header_text_color, // Section header text color
subtitle_text_color, // Subtitle color
destructive_text_color // Destructive action color
}
```
## 开发工具
## Development Tools
### @BotFather 命令
创建和管理 Bot 的核心工具:
### @BotFather Commands
The core tool for creating and managing Bots:
**Bot 管理:**
- `/newbot` - 创建新 Bot
- `/mybots` - 管理我的 Bots
- `/deletebot` - 删除 Bot
- `/token` - 重新生成 token
**Bot Management:**
- `/newbot` - Create a new Bot
- `/mybots` - Manage my Bots
- `/deletebot` - Delete a Bot
- `/token` - Regenerate a token
**设置命令:**
- `/setname` - 设置名称
- `/setdescription` - 设置描述
- `/setabouttext` - 设置关于文本
- `/setuserpic` - 设置头像
**Settings Commands:**
- `/setname` - Set name
- `/setdescription` - Set description
- `/setabouttext` - Set about text
- `/setuserpic` - Set user picture
**功能配置:**
- `/setcommands` - 设置命令列表
- `/setinline` - 启用内联模式
- `/setinlinefeedback` - 内联反馈
- `/setjoingroups` - 允许加入群组
- `/setprivacy` - 隐私模式
**Feature Configuration:**
- `/setcommands` - Set command list
- `/setinline` - Enable inline mode
- `/setinlinefeedback` - Inline feedback
- `/setjoingroups` - Allow joining groups
- `/setprivacy` - Privacy mode
**支付和游戏:**
- `/setgamescores` - 游戏分数
- `/setpayments` - 配置支付
**Payments and Games:**
- `/setgamescores` - Game scores
- `/setpayments` - Configure payments
**Mini Apps**
- `/newapp` - 创建 Mini App
- `/myapps` - 管理 Mini Apps
- `/setmenubutton` - 设置菜单按钮
**Mini Apps:**
- `/newapp` - Create a Mini App
- `/myapps` - Manage Mini Apps
- `/setmenubutton` - Set menu button
### API ID 获取
访问 https://my.telegram.org
1. 登录账号
2. 进入 API development tools
3. 创建应用
4. 获取 API ID API Hash
### Getting an API ID
Visit https://my.telegram.org
1. Log in to your account
2. Go to API development tools
3. Create an application
4. Get your API ID and API Hash
## 常用 Python
## Common Python Libraries
### python-telegram-bot
```bash
pip install python-telegram-bot
```
**特点:**
- 完整的 Bot API 包装
- 异步和同步支持
- 丰富的扩展
- 活跃维护
**Features:**
- Complete Bot API wrapper
- Asynchronous and synchronous support
- Rich extensions
- Actively maintained
**基础示例:**
**Basic Example:**
```python
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text('你好!')
await update.message.reply_text('Hello!')
app = Application.builder().token("TOKEN").build()
app.add_handler(CommandHandler("start", start))
@@ -267,25 +266,25 @@ app.run_polling()
pip install aiogram
```
**特点:**
- 纯异步
- 高性能
- FSM 状态机
- 中间件系统
**Features:**
- Purely asynchronous
- High performance
- FSM state machine
- Middleware system
### Telethon / Pyrogram
MTProto 客户端库:
MTProto client libraries:
```bash
pip install telethon
pip install pyrogram
```
**用途:**
- 自定义客户端
- 用户账号自动化
- 完整 Telegram 功能
**Uses:**
- Custom clients
- User account automation
- Full Telegram functionality
## 常用 Node.js
## Common Node.js Libraries
### node-telegram-bot-api
```bash
@@ -297,25 +296,25 @@ npm install node-telegram-bot-api
npm install telegraf
```
**特点:**
- 现代化
- 中间件架构
- TypeScript 支持
**Features:**
- Modern
- Middleware architecture
- TypeScript support
### grammY
```bash
npm install grammy
```
**特点:**
- 轻量级
- 类型安全
- 插件生态
**Features:**
- Lightweight
- Type-safe
- Plugin ecosystem
## 部署选项
## Deployment Options
### Webhook 托管
**推荐平台:**
### Webhook Hosting
**Recommended Platforms:**
- Heroku
- AWS Lambda
- Google Cloud Functions
@@ -324,142 +323,142 @@ npm install grammy
- Railway
- Render
**要求:**
- HTTPS 支持
- 公网可访问
- 支持的端口:443, 80, 88, 8443
**Requirements:**
- HTTPS support
- Publicly accessible
- Supported ports: 443, 80, 88, 8443
### 长轮询托管
**推荐平台:**
### Long Polling Hosting
**Recommended Platforms:**
- VPS (Vultr, DigitalOcean, Linode)
- Raspberry Pi
- 本地服务器
- Local server
**优点:**
- 无需 HTTPS
- 简单配置
- 适合开发测试
**Advantages:**
- No HTTPS required
- Simple configuration
- Suitable for development and testing
## 安全最佳实践
## Security Best Practices
1. **Token 安全**
- 不要提交到 Git
- 使用环境变量
- 定期轮换
1. **Token Security**
- Do not commit to Git
- Use environment variables
- Rotate tokens regularly
2. **数据验证**
- 验证 initData
- 服务器端验证
- 不信任客户端
2. **Data Validation**
- Validate initData
- Server-side validation
- Do not trust the client
3. **权限控制**
- 检查用户权限
- 管理员验证
- 群组权限
3. **Permission Control**
- Check user permissions
- Admin verification
- Group permissions
4. **速率限制**
- 实现请求限制
- 防止滥用
- 监控异常
4. **Rate Limiting**
- Implement request limits
- Prevent abuse
- Monitor for anomalies
## 调试技巧
## Debugging Tips
### Bot 调试
### Bot Debugging
```python
import logging
logging.basicConfig(level=logging.DEBUG)
```
### Mini App 调试
### Mini App Debugging
```javascript
// 开启调试模式
// Enable debug mode
tg.showAlert(JSON.stringify(tg.initDataUnsafe, null, 2));
// 控制台日志
// Console logs
console.log('WebApp version:', tg.version);
console.log('Platform:', tg.platform);
console.log('Theme:', tg.colorScheme);
```
### Webhook 测试
使用 ngrok 本地测试:
### Webhook Testing
Use ngrok for local testing:
```bash
ngrok http 5000
# 将生成的 https URL 设置为 webhook
# Set the generated https URL as the webhook
```
## 社区资源
## Community Resources
- **Telegram 开发者群组**: @BotDevelopers
- **Telegram API 讨论**: @TelegramBots
- **Mini Apps 讨论**: @WebAppChat
- **Telegram Developer Group**: @BotDevelopers
- **Telegram API Discussion**: @TelegramBots
- **Mini Apps Discussion**: @WebAppChat
## 更新日志
## Changelog
**最新功能:**
- Paid Media (付费媒体)
- Checklist Tasks (检查列表任务)
- Gift Conversion (礼物转换)
- Business Features (商业功能)
- Poll 选项增加到 12
- Story 发布和编辑
**Latest Features:**
- Paid Media
- Checklist Tasks
- Gift Conversion
- Business Features
- Poll options increased to 12
- Story publishing and editing
---
## 完整实现模板 (新增)
## Complete Implementation Templates (New)
### Telegram Bot 按钮和键盘实现指南
**文件:** `Telegram_Bot_按钮和键盘实现模板.md`
**行数:** 404
**大小:** 12 KB
**语言:** 中文
### Telegram Bot Button and Keyboard Implementation Guide
**File:** `Telegram_Bot_button_and_keyboard_implementation_template.md`
**Lines:** 404
**Size:** 12 KB
**Language:** Chinese
精简实用的 Telegram Bot 交互式功能实现指南:
A concise and practical guide to implementing interactive features for Telegram Bots:
**核心内容:**
- 三种按钮类型详解(Inline/Reply/Command Menu
- python-telegram-bot Telethon 双实现对比
- 完整的代码示例(即拿即用)
- 项目结构和模块化设计
- Handler 优先级和事件处理
- 生产环境部署方案
- 安全和错误处理最佳实践
**Core Content:**
- Detailed explanation of three button types (Inline/Reply/Command Menu)
- Comparison of implementations with python-telegram-bot and Telethon
- Complete code examples (ready to use)
- Project structure and modular design
- Handler priority and event handling
- Production deployment solutions
- Security and error handling best practices
**特色:**
- 核心代码精简,去除冗余示例
- 聚焦常用场景和实用技巧
- 完整的快速参考表
**Features:**
- Concise core code, removing redundant examples
- Focus on common scenarios and practical tips
- A complete quick reference table
---
### 动态视图对齐 - 数据展示指南
**文件:** `动态视图对齐实现文档.md`
**行数:** 407
**大小:** 12 KB
**语言:** 中文
### Dynamic View Alignment - Data Display Guide
**File:** `dynamic-view-alignment-implementation-document.md`
**Lines:** 407
**Size:** 12 KB
- **Language:** Chinese
专业的等宽字体数据对齐和格式化方案:
A professional solution for monospaced font data alignment and formatting:
**核心功能:**
- 智能动态视图对齐算法(三步法)
- 自动计算列宽,无需硬编码
- 智能对齐规则(文本左,数字右)
- 完整的格式化系统:
- 交易量智能缩写(B/M/K
- 价格智能精度(自适应小数位)
- 涨跌幅格式化(+/- 符号)
- 资金流向智能显示
**Core Features:**
- Intelligent dynamic view alignment algorithm (three-step method)
- Automatic column width calculation, no hardcoding required
- Smart alignment rules (text left, numbers right)
- Complete formatting system:
- Smart abbreviation for trading volume (B/M/K)
- Smart precision for price (adaptive decimal places)
- Formatting for price change percentage (+/- signs)
- Smart display for fund flow
**应用场景:**
- 排行榜、数据表格、实时行情
- 任何需要专业数据展示的 Telegram Bot
**Use Cases:**
- Leaderboards, data tables, real-time tickers
- Any Telegram Bot that needs professional data display
**技术特点:**
- O(n×m) 线性复杂度,高效实用
- 1000 行数据处理仅需 5-10ms
- 支持中文字符宽度扩展
**Technical Features:**
- O(n×m) linear complexity, highly efficient
- Processes 1000 rows of data in just 5-10ms
- Supports Chinese character width expansion
**视觉效果示例:**
**Visual Effect Example:**
```
1. BTC $1.23B $45,000 +5.23%
2. ETH $890.5M $2,500 +3.12%
@@ -468,4 +467,4 @@ ngrok http 5000
---
**这些模板提供了从基础到生产级别的完整 Telegram Bot 开发解决方案!**
**These templates provide a complete solution for Telegram Bot development, from basic to production level!**
@@ -0,0 +1,404 @@
# Telegram Bot Button and Keyboard Implementation Guide
> A complete reference for developing interactive features for Telegram Bots
---
## 📋 Table of Contents
1. [Button and Keyboard Types](#button-and-keyboard-types)
2. [Implementation Comparison](#implementation-comparison)
3. [Core Code Examples](#core-code-examples)
4. [Best Practices](#best-practices)
---
## Button and Keyboard Types
### 1. Inline Keyboard
**Features**:
- Displayed below a message
- Triggers a callback when clicked, without sending a message
- Supports callback data, URLs, switch queries, etc.
**Use Cases**: Confirmation/cancellation, menu navigation, pagination control, setting options
### 2. Reply Keyboard
**Features**:
- Displayed above the input field
- Sends a text message when a button is clicked
- Can be set as persistent or one-time
**Use Cases**: Quick commands, common actions, form input, main menu
### 3. Bot Command Menu
**Features**:
- Displayed in the "/" button to the left of the input field
- Set via BotFather or the API
- Provides a list of commands and their descriptions
**Use Cases**: Function index, new user guidance, quick command access
### 4. Type Comparison
| Feature | Inline | Reply | Command Menu |
|---|---|---|---|
| Position | Below message | Above input field | "/" menu |
| Trigger | Callback query | Text message | Command |
| Persistence | With message | Configurable | Always present |
| Scenario | Temporary interaction | Resident function | Command index |
---
## Implementation Comparison
### python-telegram-bot (Recommended for Bot development)
**Advantages**:
- Officially recommended, with a complete Handler system
- Rich support for buttons and keyboards
- Excellent performance with the asynchronous version
**Installation**:
```bash
pip install python-telegram-bot==20.7
```
### Telethon (Suitable for user account automation)
**Advantages**:
- Full access to the MTProto API
- Can be used with user accounts and Bots
- Powerful message listening capabilities
**Installation**:
```bash
pip install telethon cryptg
```
---
## Core Code Examples
### 1. Inline Keyboard Implementation
**python-telegram-bot:**
```python
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ContextTypes
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Display an inline keyboard"""
keyboard = [
[
InlineKeyboardButton("📊 View Data", callback_data="view_data"),
InlineKeyboardButton("⚙️ Settings", callback_data="settings"),
],
[
InlineKeyboardButton("🔗 Visit Website", url="https://example.com"),
],
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text("Please choose:", reply_markup=reply_markup)
async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle button clicks"""
query = update.callback_query
await query.answer() # Must be called
if query.data == "view_data":
await query.edit_message_text("Displaying data...")
elif query.data == "settings":
await query.edit_message_text("Settings options...")
# Register handlers
app = Application.builder().token("TOKEN").build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CallbackQueryHandler(button_callback))
app.run_polling()
```
**Telethon:**
```python
from telethon import TelegramClient, events, Button
client = TelegramClient('bot', api_id, api_hash).start(bot_token=BOT_TOKEN)
@client.on(events.NewMessage(pattern='/start'))
async def start(event):
buttons = [
[Button.inline("📊 View Data", b"view_data"), Button.inline("⚙️ Settings", b"settings")],
[Button.url("🔗 Visit Website", "https://example.com")]
]
await event.respond("Please choose:", buttons=buttons)
@client.on(events.CallbackQuery)
async def callback(event):
if event.data == b"view_data":
await event.edit("Displaying data...")
elif event.data == b"settings":
await event.edit("Settings options...")
client.run_until_disconnected()
```
### 2. Reply Keyboard Implementation
**python-telegram-bot:**
```python
from telegram import KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove
async def menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Display a reply keyboard"""
keyboard = [
[KeyboardButton("📊 View Data"), KeyboardButton("⚙️ Settings")],
[KeyboardButton("📚 Help"), KeyboardButton("❌ Hide Keyboard")],
]
reply_markup = ReplyKeyboardMarkup(
keyboard,
resize_keyboard=True,
one_time_keyboard=False
)
await update.message.reply_text("Menu activated", reply_markup=reply_markup)
async def handle_text(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle text messages"""
text = update.message.text
if text == "📊 View Data":
await update.message.reply_text("Displaying data...")
elif text == "❌ Hide Keyboard":
await update.message.reply_text("Keyboard hidden", reply_markup=ReplyKeyboardRemove())
```
**Telethon:**
```python
@client.on(events.NewMessage(pattern='/menu'))
async def menu(event):
buttons = [
[Button.text("📊 View Data"), Button.text("⚙️ Settings")],
[Button.text("📚 Help"), Button.text("❌ Hide Keyboard")]
]
await event.respond("Menu activated", buttons=buttons)
@client.on(events.NewMessage)
async def handle_text(event):
if event.text == "📊 View Data":
await event.respond("Displaying data...")
```
### 3. Bot Command Menu Setup
**Via BotFather:**
```
1. Send /setcommands to @BotFather
2. Choose your Bot
3. Enter the list of commands (format per line: command - description)
start - Start the bot
help - Get help
menu - Display the main menu
settings - Configure settings
```
**Via API (python-telegram-bot):**
```python
from telegram import BotCommand
async def set_commands(app: Application):
"""Set the command menu"""
commands = [
BotCommand("start", "Start the bot"),
BotCommand("help", "Get help"),
BotCommand("menu", "Display the main menu"),
BotCommand("settings", "Configure settings"),
]
await app.bot.set_my_commands(commands)
# Call on startup
app.post_init = set_commands
```
### 4. Project Structure Example
```
telegram_bot/
├── bot.py # Main program
├── config.py # Configuration management
├── requirements.txt
├── .env
├── handlers/
│ ├── command_handlers.py # Command handlers
│ ├── callback_handlers.py # Callback handlers
│ └── message_handlers.py # Message handlers
├── keyboards/
│ ├── inline_keyboards.py # Inline keyboard layouts
│ └── reply_keyboards.py # Reply keyboard layouts
└── utils/
├── logger.py # Logger
└── database.py # Database
```
**Modular Example (keyboards/inline_keyboards.py):**
```python
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
def get_main_menu():
"""Main menu keyboard"""
return InlineKeyboardMarkup([
[
InlineKeyboardButton("📊 Data", callback_data="data"),
InlineKeyboardButton("⚙️ Settings", callback_data="settings"),
],
[InlineKeyboardButton("📚 Help", callback_data="help")],
])
def get_data_menu():
"""Data menu keyboard"""
return InlineKeyboardMarkup([
[
InlineKeyboardButton("📈 Real-time", callback_data="data_realtime"),
InlineKeyboardButton("📊 History", callback_data="data_history"),
],
[InlineKeyboardButton("⬅️ Back", callback_data="back")],
])
```
---
## Best Practices
### 1. Handler Priority
```python
# Match in order of registration, from most specific to most general
app.add_handler(CommandHandler("start", start)) # 1. Specific command
app.add_handler(CallbackQueryHandler(callback)) # 2. Callback query
app.add_handler(ConversationHandler(...)) # 3. Conversation flow
app.add_handler(MessageHandler(filters.TEXT, text_msg)) # 4. General message (last)
```
### 2. Error Handling
```python
async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Global error handler"""
logger.error(f"Update {update} caused error", exc_info=context.error)
# Notify the user
if update and update.effective_message:
await update.effective_message.reply_text("Operation failed, please try again")
app.add_error_handler(error_handler)
```
### 3. Callback Data Management
```python
# Use structured callback_data
callback_data = "action:page:item" # e.g., "view:1:product_123"
# Parse callback data
async def callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
parts = query.data.split(":")
action, page, item = parts
if action == "view":
await show_item(query, page, item)
```
### 4. Keyboard Design Principles
- **Concise**: 2-3 buttons per row at most
- **Clear**: Use emojis to enhance recognition
- **Consistent**: Maintain a uniform layout style
- **Responsive**: Provide timely feedback to user actions
### 5. Security Considerations
```python
# Verify user permissions
ADMIN_IDS = [123456789]
async def admin_only(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
if user_id not in ADMIN_IDS:
await update.message.reply_text("Permission denied")
return
# Execute admin operations
```
### 6. Deployment Solutions
**Webhook (Recommended for production):**
```python
from flask import Flask, request
app_flask = Flask(__name__)
@app_flask.route('/webhook', methods=['POST'])
def webhook():
update = Update.de_json(request.get_json(), bot)
application.update_queue.put(update)
return "OK"
# Set webhook
bot.set_webhook(f"https://yourdomain.com/webhook")
```
**Systemd Service (Linux):**
```ini
[Unit]
Description=Telegram Bot
After=network.target
[Service]
Type=simple
User=your_user
WorkingDirectory=/path/to/bot
ExecStart=/path/to/venv/bin/python bot.py
Restart=always
[Install]
WantedBy=multi-user.target
```
### 7. Common Library Versions
```txt
# requirements.txt
python-telegram-bot==20.7
python-dotenv==1.0.0
aiosqlite==0.19.0
httpx==0.25.2
```
---
## Quick Reference
### Inline Keyboard Button Types
```python
InlineKeyboardButton("Text", callback_data="data") # Callback button
InlineKeyboardButton("Link", url="https://...") # URL button
InlineKeyboardButton("Switch", switch_inline_query="") # Inline query
InlineKeyboardButton("Login", login_url=...) # Login button
InlineKeyboardButton("Pay", pay=True) # Payment button
InlineKeyboardButton("App", web_app=WebAppInfo(...)) # Mini App
```
### Common Event Types
- `events.NewMessage` - New message
- `events.CallbackQuery` - Callback query
- `events.InlineQuery` - Inline query
- `events.ChatAction` - Group action
---
**This guide covers all the core implementations of Telegram Bot buttons and keyboards!**