docs: 更新文档和技能

This commit is contained in:
tukuaiai 2025-12-17 20:39:02 +08:00
parent 924b651e34
commit fb74acbd9b
23 changed files with 956 additions and 346 deletions

View File

@ -98,6 +98,27 @@
---
<details open>
<summary><strong>🧬 胶水编程 (Glue Coding)</strong></summary>
> **软件工程的圣杯与银弹——终于出现了。**
胶水编程是 Vibe Coding 的终极进化形态,可能完美解决三大致命缺陷:
| 问题 | 解法 |
|:---|:---|
| 🎭 AI 幻觉 | ✅ 只使用已验证的成熟代码,零幻觉 |
| 🧩 复杂性爆炸 | ✅ 每个模块都是久经考验的轮子 |
| 🎓 门槛过高 | ✅ 你只需要描述"连接方式" |
**核心理念**:能抄不写,能连不造,能复用不原创。
👉 [深入了解胶水编程](./i18n/zh/documents/胶水编程/README.md)
</details>
---
## 🖼️ 概览
**Vibe Coding** 是一个与 AI 结对编程的终极工作流程,旨在帮助开发者丝滑地将想法变为现实。本指南详细介绍了从项目构思、技术选型、实施规划到具体开发、调试和扩展的全过程,强调以**规划驱动**和**模块化**为核心,避免让 AI 失控导致项目混乱。
@ -245,6 +266,7 @@
### 项目内部文档
* [**胶水编程 (Glue Coding)**](./i18n/zh/documents/胶水编程/): 软件工程的圣杯与银弹Vibe Coding 的终极进化形态。
* [**prompts-library 工具说明**](./libs/external/prompts-library/): 支持 Excel 与 Markdown 格式互转,包含数百个精选提示词。
* [**coding_prompts 集合**](./i18n/zh/prompts/coding_prompts/): 适用于 Vibe Coding 流程的专用提示词。
* [**系统提示词构建原则**](./i18n/zh/documents/方法论与原则/系统提示词构建原则.md): 构建高效 AI 系统提示词的综合指南。

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.

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

View File

@ -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]."

View File

@ -1,4 +1,3 @@
TRANSLATED CONTENT:
---
name: {{skill_name}}
description: "[Domain] capability: includes [key capability]. Use when [decidable triggers]."

View File

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

View File

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

View File

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

View File

@ -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".

View File

@ -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/`.

View File

@ -1,4 +1,3 @@
TRANSLATED CONTENT:
#!/usr/bin/env bash
set -euo pipefail

View File

@ -1,4 +1,3 @@
TRANSLATED CONTENT:
#!/usr/bin/env bash
set -euo pipefail

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.

View File

View File

@ -1,4 +1,3 @@
TRANSLATED CONTENT:
# Snapdom Documentation Index
## Categories

View File

@ -1,4 +1,3 @@
TRANSLATED CONTENT:
# Snapdom - Other
**Pages:** 1

View File

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

View File

@ -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!**

View File

@ -14,6 +14,9 @@ i18n/zh/documents/
│ ├── 02-开发环境搭建.md
│ └── 03-IDE配置.md
├── 胶水编程/ # 🧬 Glue Coding 革命性范式
│ └── README.md
├── 方法论与原则/
│ ├── A Formalization of Recursive Self-Optimizing Generative Systems.md
│ ├── gluecoding.md
@ -21,24 +24,34 @@ i18n/zh/documents/
│ ├── 学习经验.md
│ ├── 开发经验.md
│ ├── 编程之道.md
│ ├── 胶水编程.md
│ └── 系统提示词构建原则.md
├── 教程与指南/
│ ├── auggie-mcp配置文档.md
│ ├── LazyVim快捷键大全.md
│ ├── tmux快捷键大全.md
│ ├── 关于手机ssh任意位置链接本地计算机基于frp实现的方法.md
│ └── telegram-dev/
│ └── 关于手机ssh任意位置链接本地计算机基于frp实现的方法.md
├── 模板与资源/
│ ├── 代码组织.md
│ ├── 工具集.md
│ ├── 编程书籍推荐.md
│ └── 通用项目架构模板.md
│ ├── 通用项目架构模板.md
│ └── memory-bank-template/
└── 项目实战经验/
└── telegram-dev/
├── 外部资源聚合/ # 🔗 外部链接汇总
│ ├── AI工具与平台/
│ ├── GitHub精选仓库/
│ ├── 提示词资源/
│ ├── 开发工具/
│ ├── 教程与课程/
│ └── 社区与论坛/
└── 项目实战经验/ # 📁 实战案例
├── fate-engine-dev/
├── polymarket-dev/
├── telegram-dev/
└── ...
```
## 文档分类
@ -52,43 +65,57 @@ i18n/zh/documents/
* [02-开发环境搭建](./从零开始vibecoding/02-开发环境搭建.md) - 搭建开发环境(提示词版)
* [03-IDE配置](./从零开始vibecoding/03-IDE配置.md) - 配置 VS Code / Cursor / Windsurf
### 🧬 胶水编程 (Glue Coding)
**软件工程的圣杯与银弹。** 彻底解决 Vibe Coding 的幻觉、复杂性和门槛问题。
* [胶水编程介绍](./胶水编程/README.md) - 革命性编程范式
### 方法论与原则
关于编程思想、开发哲学和项目核心原则的文档。
* `A Formalization of Recursive Self-Optimizing Generative Systems.md`
* `gluecoding.md`
* `vibe-coding-经验收集.md`
* `学习经验.md`
* `开发经验.md`
* `编程之道.md`
* `胶水编程.md`
* `系统提示词构建原则.md`
* `A Formalization of Recursive Self-Optimizing Generative Systems.md` - 递归自优化系统形式化
* `gluecoding.md` - 胶水编程理论
* `vibe-coding-经验收集.md` - 经验汇总
* `学习经验.md` - 学习心得
* `开发经验.md` - 开发实践
* `编程之道.md` - 编程哲学
* `系统提示词构建原则.md` - 提示词工程
### 教程与指南
具体工具的配置、使用指南和操作教程。
* `auggie-mcp配置文档.md`
* `LazyVim快捷键大全.md`
* `tmux快捷键大全.md`
* `关于手机ssh任意位置链接本地计算机基于frp实现的方法.md`
* `telegram-dev/`
* `auggie-mcp配置文档.md` - Augment MCP 配置
* `LazyVim快捷键大全.md` - LazyVim 快捷键
* `tmux快捷键大全.md` - tmux 快捷键
* `关于手机ssh任意位置链接本地计算机基于frp实现的方法.md` - 远程开发
### 模板与资源
可复用的项目模板、代码结构规范和资源列表。
* `代码组织.md`
* `工具集.md`
* `编程书籍推荐.md`
* `通用项目架构模板.md`
* `代码组织.md` - 代码组织规范
* `工具集.md` - 工具推荐
* `编程书籍推荐.md` - 书籍推荐
* `通用项目架构模板.md` - 项目模板
* `memory-bank-template/` - Memory Bank 模板
### 项目实战经验
### 🔗 外部资源聚合
外部优质资源汇总,持续更新。
* [外部资源聚合](./外部资源聚合/README.md) - 总索引
### 📁 项目实战经验
实际项目开发中的经验总结和案例。
* `telegram-dev/` - Telegram Bot 开发经验
* [项目实战经验](./项目实战经验/README.md) - 总索引
* `fate-engine-dev/` - 命理引擎开发
* `polymarket-dev/` - Polymarket 数据分析
* `telegram-dev/` - Telegram Bot 开发
## 相关资源

View File

@ -0,0 +1,172 @@
# 🧬 胶水编程 (Glue Coding)
> **软件工程的圣杯与银弹——终于出现了。**
---
## 🚀 颠覆性宣言
**胶水编程不是一种技术,而是一场革命。**
它可能完美解决了 Vibe Coding 的三大致命缺陷:
| 传统 Vibe Coding 的痛点 | 胶水编程的解法 |
|:---|:---|
| 🎭 **AI 幻觉** - 生成不存在的 API、错误的逻辑 | ✅ **零幻觉** - 只使用已验证的成熟代码 |
| 🧩 **复杂性爆炸** - 项目越大越失控 | ✅ **复杂性归零** - 每个模块都是久经考验的轮子 |
| 🎓 **门槛过高** - 需要深厚编程功底才能驾驭 AI | ✅ **门槛消失** - 你只需要描述"连接方式" |
---
## 💡 核心理念
```
传统编程:人写代码
Vibe CodingAI 写代码,人审代码
胶水编程AI 连接代码,人审连接
```
### 范式转移
**从「生成」到「连接」的根本性转变:**
- ❌ 不再让 AI 从零生成代码(幻觉的根源)
- ❌ 不再重复造轮子(复杂性的根源)
- ❌ 不再要求你理解每一行代码(门槛的根源)
- ✅ 只复用成熟的、经过生产验证的开源项目
- ✅ AI 的唯一职责:理解你的意图,将模块连接起来
- ✅ 你的唯一职责:描述清楚「输入是什么,输出要什么」
---
## 🏗️ 架构哲学
```
┌─────────────────────────────────────────────────────────┐
│ 你的业务需求 │
└─────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│ AI 胶水层 (Glue Layer) │
│ │
│ "我理解你要做什么,让我把这些积木连起来" │
│ │
└─────────────────────────────────────────────────────────┘
┌────────────────┼────────────────┐
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ 成熟模块 A │ │ 成熟模块 B │ │ 成熟模块 C │
│ (10万+ ⭐) │ │ (生产验证) │ │ (官方 SDK) │
└─────────────┘ └─────────────┘ └─────────────┘
```
**实体 (Entity)**:成熟的开源项目、官方 SDK、久经考验的库
**连接 (Link)**AI 生成的胶水代码,负责数据流转和接口适配
**功能 (Function)**:你描述的业务目标
---
## 🎯 为什么这是银弹?
### 1. 幻觉问题 → 彻底消失
AI 不再需要"发明"任何东西。它只需要:
- 阅读模块 A 的文档
- 阅读模块 B 的文档
- 写出 A → B 的数据转换
**这是 AI 最擅长的事情,也是最不容易出错的事情。**
### 2. 复杂性问题 → 转嫁给社区
每个模块背后都有:
- 数千个 Issue 的讨论
- 数百个贡献者的智慧
- 数年的生产环境打磨
**你不是在管理复杂性,你是在站在巨人的肩膀上。**
### 3. 门槛问题 → 降到最低
你不需要懂:
- 底层实现原理
- 最佳实践细节
- 边界情况处理
你只需要会说人话:
> "我要把 Telegram 的消息,经过 GPT 处理,存到 PostgreSQL"
**AI 会帮你找到最合适的轮子,然后把它们粘起来。**
---
## 📋 实践流程
```
1. 明确目标
└─→ "我要实现 XXX 功能"
2. 寻找轮子
└─→ "有没有成熟的库/项目已经做过类似的事?"
└─→ 让 AI 帮你搜索、评估、推荐
3. 理解接口
└─→ 把官方文档喂给 AI
└─→ AI 总结:输入是什么,输出是什么
4. 描述连接
└─→ "A 的输出要变成 B 的输入"
└─→ AI 生成胶水代码
5. 验证运行
└─→ 跑通 → 完成
└─→ 报错 → 把错误扔给 AI继续粘
```
---
## 🔥 经典案例
### 案例Polymarket 数据分析 Bot
**需求**:实时获取 Polymarket 数据,分析后推送到 Telegram
**传统做法**:从零写爬虫、写分析逻辑、写 Bot → 3000 行代码2 周时间
**胶水做法**
```
轮子 1: polymarket-py (官方 SDK)
轮子 2: pandas (数据分析)
轮子 3: python-telegram-bot (消息推送)
胶水代码: 50 行
开发时间: 2 小时
```
---
## 📚 延伸阅读
- [胶水开发提示词](../../prompts/coding_prompts/胶水开发.md)
- [项目实战polymarket-dev](../项目实战经验/polymarket-dev/)
---
## 🎖️ 总结
> **能抄不写,能连不造,能复用不原创。**
胶水编程是 Vibe Coding 的终极进化形态。
它不是偷懒,而是**工程智慧的最高体现**——
用最少的原创代码,撬动最大的生产力。
**这就是软件工程等待了 50 年的银弹。**
---
*"The best code is no code at all. The second best is glue code."*