Telegram Bot Builder by davila7/claude-code-templates
npx skills add https://github.com/davila7/claude-code-templates --skill 'Telegram Bot Builder'使用 Bot API (v9.4) 构建 Telegram 机器人的综合指南。涵盖 Node.js 和 Python 生态系统,提供适用于生产环境的身份验证、消息传递、键盘、媒体处理、支付、内联模式、Webhook 和部署模式。
在以下情况下使用此技能:
每个机器人都有一个从 @BotFather 获得的唯一令牌。令牌格式:123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11。
所有 API 调用都发送到:https://api.telegram.org/bot<TOKEN>/METHOD_NAME
# .env 文件
BOT_TOKEN=123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11
将令牌存储在环境变量中。切勿将其提交到源代码。
长轮询 (getUpdates) - 更简单,无需 HTTPS,适合开发:
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
// Node.js 使用 node-telegram-bot-api
const bot = new TelegramBot(process.env.BOT_TOKEN, { polling: true });
# Python 使用 python-telegram-bot
app = Application.builder().token(os.getenv("BOT_TOKEN")).build()
app.run_polling()
Webhook (setWebhook) - 更适合生产环境,延迟更低,需要 HTTPS(端口 443、80、88 或 8443):
bot.setWebHook('https://yourdomain.com/webhook', { secret_token: SECRET });
开发和小型机器人选择轮询。处理高流量的生产部署选择 Webhook。
使用 sendMessage 发送文本。支持的解析模式:
<b>粗体</b>, <i>斜体</i>, <code>代码</code>, <pre>块</pre>, <a href="url">链接</a>, <tg-spoiler>剧透</tg-spoiler>*粗体*, _斜体_, 代码, 块, [链接](url), ||剧透||。需要转义:_*[]()~>#+-=|{}.!更简单的转义请选择 HTML。当简单格式化足够时使用 MarkdownV2。
内联键盘 - 附加到消息的按钮:
bot.sendMessage(chatId, '选择:', {
reply_markup: {
inline_keyboard: [
[{ text: '选项 A', callback_data: 'a' }, { text: '选项 B', callback_data: 'b' }],
[{ text: '访问网站', url: 'https://example.com' }]
]
}
});
回复键盘 - 输入字段下方的自定义键盘:
bot.sendMessage(chatId, '选择:', {
reply_markup: {
keyboard: [[{ text: '📊 统计' }, { text: '⚙️ 设置' }]],
resize_keyboard: true,
one_time_keyboard: true
}
});
使用 callback_query 处理内联按钮按下。callback_data 字段限制为 64 字节。始终调用 answerCallbackQuery 以消除加载指示器。
// 照片 (file_id、URL 或上传)
bot.sendPhoto(chatId, 'https://example.com/photo.jpg', { caption: '一张照片' });
// 文档
bot.sendDocument(chatId, fs.createReadStream('./file.pdf'), { caption: '报告' });
// 相册 (2-10 个项目)
bot.sendMediaGroup(chatId, [
{ type: 'photo', media: 'https://example.com/1.jpg', caption: '第一张' },
{ type: 'photo', media: 'https://example.com/2.jpg' }
]);
指定文件的三种方式:file_id(重用先前上传的)、HTTP URL(Telegram 下载它)或多部分上传。文件限制:通过 Bot API 上传 50MB,下载 20MB。
对于多步骤交互(注册、表单、向导),按聊天维护对话状态:
Map 或 Redis 跟踪每个 chatId 的 { step, data }python-telegram-bot 中的 ConversationHandler(内置状态机)完整的对话流程实现请参阅 reference/patterns_and_examples.md。
处理常见错误场景:
retry_after,等待,然后重试description 字段)速率限制:每秒约 30 条消息到不同聊天,每分钟约 20 条消息到同一群组。为重试实现指数退避。
注册在 Telegram 菜单中可见的命令:
bot.setMyCommands([
{ command: 'start', description: '启动机器人' },
{ command: 'help', description: '显示帮助' },
{ command: 'settings', description: '机器人设置' }
]);
命令可以使用 BotCommandScope 限定到特定聊天、用户或语言。
mkdir my-bot && cd my-bot
npm init -y
npm install node-telegram-bot-api dotenv
echo "BOT_TOKEN=your_token_here" > .env
mkdir my-bot && cd my-bot
pip install python-telegram-bot python-dotenv
echo "BOT_TOKEN=your_token_here" > .env
| 语言 | 库 | 风格 | 最适合 |
|---|---|---|---|
| Node.js | node-telegram-bot-api | 基于回调 | 简单机器人,快速原型 |
| Node.js | grammy | 基于中间件 | 复杂机器人,插件 |
| Node.js | telegraf | 基于中间件 | 成熟生态系统 |
| Python | python-telegram-bot | 基于处理器 | 功能齐全,对话 |
| Python | aiogram | 异步优先 | 高性能异步机器人 |
| 类别 | 关键方法 |
|---|---|
| 消息 | sendMessage, sendPhoto, sendVideo, sendDocument, editMessageText, deleteMessage |
| 键盘 | InlineKeyboardMarkup, ReplyKeyboardMarkup, answerCallbackQuery |
| 聊天管理 | getChat, banChatMember, promoteChatMember, setChatPermissions |
| 文件 | getFile, sendMediaGroup, sendDocument |
| 内联模式 | answerInlineQuery 与 InlineQueryResult* 类型 |
| 支付 | sendInvoice, answerPreCheckoutQuery(使用 currency: "XTR" 表示 Telegram Stars) |
| 机器人配置 | setMyCommands, setMyDescription, setWebhook |
pm2 start bot.js --name telegram-bot - 具有自动重启功能的进程管理器docker-compose 进行容器化部署Docker、PM2 和无服务器部署配置请参阅 reference/patterns_and_examples.md。
BOT_TOKEN 存储在环境变量中X-Telegram-Bot-Api-Secret-Tokenallowed_updates 限制为仅需要的类型详细的 API 文档和实现模式,请查阅:
reference/api_methods.md - 按类别组织的 100 多个 Bot API 方法的完整列表(消息传递、聊天管理、贴纸、支付、内联模式、游戏、论坛主题、礼物、护照等)reference/api_types.md - 包含所有字段的 200 多个 Bot API 类型的完整列表(Update、Message、Chat、User、键盘、媒体类型、支付类型、聊天成员、反应等)reference/patterns_and_examples.md - 适用于 Node.js 和 Python 的生产就绪实现模式,包括:内联键盘、Webhook、媒体处理、对话状态管理、数据库集成、管理面板、多语言支持、Docker/PM2/无服务器部署、Telegram Stars 支付和内联模式构建机器人时,从 SKILL.md 开始了解核心概念,然后根据需要加载相应的参考文件以获取详细的 API 信息或实现模式。
每周安装次数
230
仓库
GitHub 星标数
23.5K
首次出现
2026年1月25日
安全审计
安装于
opencode205
gemini-cli195
codex188
cursor180
github-copilot179
claude-code148
Comprehensive guidance for building Telegram bots using the Bot API (v9.4). Covers both Node.js and Python ecosystems with production-ready patterns for authentication, messaging, keyboards, media handling, payments, inline mode, webhooks, and deployment.
Use this skill when:
Every bot has a unique token obtained from @BotFather. Token format: 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11.
All API calls go to: https://api.telegram.org/bot<TOKEN>/METHOD_NAME
# .env file
BOT_TOKEN=123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11
Store the token in environment variables. Never commit it to source code.
Long Polling (getUpdates) - Simpler, no HTTPS required, ideal for development:
// Node.js with node-telegram-bot-api
const bot = new TelegramBot(process.env.BOT_TOKEN, { polling: true });
# Python with python-telegram-bot
app = Application.builder().token(os.getenv("BOT_TOKEN")).build()
app.run_polling()
Webhook (setWebhook) - Better for production, lower latency, requires HTTPS (ports 443, 80, 88, or 8443):
bot.setWebHook('https://yourdomain.com/webhook', { secret_token: SECRET });
Choose polling for development and small bots. Choose webhooks for production deployments handling high traffic.
Send text with sendMessage. Supported parse modes:
<b>bold</b>, <i>italic</i>, <code>code</code>, <pre>block</pre>, <a href="url">link</a>, <tg-spoiler>spoiler</tg-spoiler>*bold*, _italic_, code, block, [link](url), . Requires escaping: Prefer HTML for easier escaping. Use MarkdownV2 when simpler formatting suffices.
Inline Keyboard - Buttons attached to messages:
bot.sendMessage(chatId, 'Choose:', {
reply_markup: {
inline_keyboard: [
[{ text: 'Option A', callback_data: 'a' }, { text: 'Option B', callback_data: 'b' }],
[{ text: 'Visit Site', url: 'https://example.com' }]
]
}
});
Reply Keyboard - Custom keyboard below input field:
bot.sendMessage(chatId, 'Choose:', {
reply_markup: {
keyboard: [[{ text: '📊 Stats' }, { text: '⚙️ Settings' }]],
resize_keyboard: true,
one_time_keyboard: true
}
});
Handle inline button presses with callback_query. The callback_data field is limited to 64 bytes. Always call answerCallbackQuery to dismiss the loading indicator.
// Photo (file_id, URL, or upload)
bot.sendPhoto(chatId, 'https://example.com/photo.jpg', { caption: 'A photo' });
// Document
bot.sendDocument(chatId, fs.createReadStream('./file.pdf'), { caption: 'Report' });
// Album (2-10 items)
bot.sendMediaGroup(chatId, [
{ type: 'photo', media: 'https://example.com/1.jpg', caption: 'First' },
{ type: 'photo', media: 'https://example.com/2.jpg' }
]);
Three ways to specify files: file_id (reuse previously uploaded), HTTP URL (Telegram downloads it), or multipart upload. File limits: 50MB upload, 20MB download via Bot API.
For multi-step interactions (registration, forms, wizards), maintain conversation state per chat:
Map or Redis to track { step, data } per chatIdConversationHandler from python-telegram-bot (built-in state machine)See reference/patterns_and_examples.md for complete conversation flow implementations.
Handle common error scenarios:
retry_after from response, wait, then retrydescription field)Rate limits: ~30 messages/second to different chats, ~20 messages/minute to same group. Implement exponential backoff for retries.
Register commands visible in the Telegram menu:
bot.setMyCommands([
{ command: 'start', description: 'Start the bot' },
{ command: 'help', description: 'Show help' },
{ command: 'settings', description: 'Bot settings' }
]);
Commands can be scoped to specific chats, users, or languages using BotCommandScope.
mkdir my-bot && cd my-bot
npm init -y
npm install node-telegram-bot-api dotenv
echo "BOT_TOKEN=your_token_here" > .env
mkdir my-bot && cd my-bot
pip install python-telegram-bot python-dotenv
echo "BOT_TOKEN=your_token_here" > .env
| Language | Library | Style | Best For |
|---|---|---|---|
| Node.js | node-telegram-bot-api | Callback-based | Simple bots, quick prototypes |
| Node.js | grammy | Middleware-based | Complex bots, plugins |
| Node.js | telegraf | Middleware-based | Mature ecosystem |
| Python | python-telegram-bot | Handler-based | Full-featured, conversations |
| Category | Key Methods |
|---|---|
| Messages | sendMessage, sendPhoto, sendVideo, sendDocument, editMessageText, deleteMessage |
| Keyboards | InlineKeyboardMarkup, ReplyKeyboardMarkup, answerCallbackQuery |
pm2 start bot.js --name telegram-bot - Process manager with auto-restartdocker-composeSee reference/patterns_and_examples.md for Docker, PM2, and serverless deployment configurations.
BOT_TOKEN in environment variablesX-Telegram-Bot-Api-Secret-Token on webhook endpointsallowed_updates to only needed typesFor detailed API documentation and implementation patterns, consult:
reference/api_methods.md - Complete list of 100+ Bot API methods organized by category (messaging, chat management, stickers, payments, inline mode, games, forum topics, gifts, passport, and more)reference/api_types.md - Complete list of 200+ Bot API types with all fields (Update, Message, Chat, User, keyboards, media types, payment types, chat members, reactions, and more)reference/patterns_and_examples.md - Production-ready implementation patterns for Node.js and Python including: inline keyboards, webhooks, media handling, conversation state management, database integration, admin panels, multi-language support, Docker/PM2/serverless deployment, Telegram Stars payments, and inline modeWhen building a bot, start with SKILL.md for core concepts, then load the appropriate reference file for detailed API information or implementation patterns as needed.
Weekly Installs
230
Repository
GitHub Stars
23.5K
First Seen
Jan 25, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykWarn
Installed on
opencode205
gemini-cli195
codex188
cursor180
github-copilot179
claude-code148
agent-browser 浏览器自动化工具 - Vercel Labs 命令行网页操作与测试
144,300 周安装
MCP插件Adaptive Cards开发指南:为Microsoft 365 Copilot创建可视化响应模板
7,500 周安装
Java重构移除参数:提升代码可维护性与可读性的重构技巧
7,500 周安装
Java项目GraalVM原生镜像支持配置指南 - Maven/Gradle/Spring Boot集成
7,500 周安装
GitHub Copilot 配置专家 | 一键生成生产级项目配置 | AI 编程助手设置
7,600 周安装
项目文件夹结构蓝图生成器 - 自动生成多技术栈项目结构文档,提升代码组织一致性
7,600 周安装
Fluent UI Blazor 使用指南:Microsoft.FluentUI.AspNetCore.Components 4 版本完整教程
7,600 周安装
||spoiler||_*[]()~>#+-=|{}.!| Python | aiogram | Async-first | High-performance async bots |
| Chat Mgmt | getChat, banChatMember, promoteChatMember, setChatPermissions |
| Files | getFile, sendMediaGroup, sendDocument |
| Inline Mode | answerInlineQuery with InlineQueryResult* types |
| Payments | sendInvoice, answerPreCheckoutQuery (use currency: "XTR" for Telegram Stars) |
| Bot Config | setMyCommands, setMyDescription, setWebhook |