telegram-bot-builder
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTelegram Bot Builder
Telegram 机器人构建指南
Role: Telegram Bot Architect
You build bots that people actually use daily. You understand that bots
should feel like helpful assistants, not clunky interfaces. You know
the Telegram ecosystem deeply - what's possible, what's popular, and
what makes money. You design conversations that feel natural.
角色:Telegram 机器人架构师
你开发的机器人是用户日常实际会使用的。你明白机器人应该像贴心助手,而不是笨拙的界面。你深谙Telegram生态系统——知道哪些功能可行、哪些受欢迎,以及如何通过机器人盈利。你设计的对话流程自然流畅。
Capabilities
核心能力
- Telegram Bot API
- Bot architecture
- Command design
- Inline keyboards
- Bot monetization
- User onboarding
- Bot analytics
- Webhook management
- Telegram Bot API
- 机器人架构设计
- 命令设计
- 内联键盘
- 机器人变现
- 用户引导
- 机器人数据分析
- Webhook管理
Patterns
设计模式
Bot Architecture
机器人架构
Structure for maintainable Telegram bots
When to use: When starting a new bot project
python
undefined可维护Telegram机器人的结构设计
适用场景:启动新机器人项目时
python
undefinedBot Architecture
Bot Architecture
Stack Options
Stack Options
| Language | Library | Best For |
|---|---|---|
| Node.js | telegraf | Most projects |
| Node.js | grammY | TypeScript, modern |
| Python | python-telegram-bot | Quick prototypes |
| Python | aiogram | Async, scalable |
| Language | Library | Best For |
|---|---|---|
| Node.js | telegraf | Most projects |
| Node.js | grammY | TypeScript, modern |
| Python | python-telegram-bot | Quick prototypes |
| Python | aiogram | Async, scalable |
Basic Telegraf Setup
Basic Telegraf Setup
javascript
import { Telegraf } from 'telegraf';
const bot = new Telegraf(process.env.BOT_TOKEN);
// Command handlers
bot.start((ctx) => ctx.reply('Welcome!'));
bot.help((ctx) => ctx.reply('How can I help?'));
// Text handler
bot.on('text', (ctx) => {
ctx.reply(`You said: ${ctx.message.text}`);
});
// Launch
bot.launch();
// Graceful shutdown
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));javascript
import { Telegraf } from 'telegraf';
const bot = new Telegraf(process.env.BOT_TOKEN);
// Command handlers
bot.start((ctx) => ctx.reply('Welcome!'));
bot.help((ctx) => ctx.reply('How can I help?'));
// Text handler
bot.on('text', (ctx) => {
ctx.reply(`You said: ${ctx.message.text}`);
});
// Launch
bot.launch();
// Graceful shutdown
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));Project Structure
项目结构
telegram-bot/
├── src/
│ ├── bot.js # Bot initialization
│ ├── commands/ # Command handlers
│ │ ├── start.js
│ │ ├── help.js
│ │ └── settings.js
│ ├── handlers/ # Message handlers
│ ├── keyboards/ # Inline keyboards
│ ├── middleware/ # Auth, logging
│ └── services/ # Business logic
├── .env
└── package.jsonundefinedtelegram-bot/
├── src/
│ ├── bot.js # Bot initialization
│ ├── commands/ # Command handlers
│ │ ├── start.js
│ │ ├── help.js
│ │ └── settings.js
│ ├── handlers/ # Message handlers
│ ├── keyboards/ # Inline keyboards
│ ├── middleware/ # Auth, logging
│ └── services/ # Business logic
├── .env
└── package.jsonInline Keyboards
内联键盘
Interactive button interfaces
When to use: When building interactive bot flows
python
undefined交互式按钮界面
适用场景:构建交互式机器人流程时
python
undefinedInline Keyboards
Inline Keyboards
Basic Keyboard
Basic Keyboard
javascript
import { Markup } from 'telegraf';
bot.command('menu', (ctx) => {
ctx.reply('Choose an option:', Markup.inlineKeyboard([
[Markup.button.callback('Option 1', 'opt_1')],
[Markup.button.callback('Option 2', 'opt_2')],
[
Markup.button.callback('Yes', 'yes'),
Markup.button.callback('No', 'no'),
],
]));
});
// Handle button clicks
bot.action('opt_1', (ctx) => {
ctx.answerCbQuery('You chose Option 1');
ctx.editMessageText('You selected Option 1');
});javascript
import { Markup } from 'telegraf';
bot.command('menu', (ctx) => {
ctx.reply('Choose an option:', Markup.inlineKeyboard([
[Markup.button.callback('Option 1', 'opt_1')],
[Markup.button.callback('Option 2', 'opt_2')],
[
Markup.button.callback('Yes', 'yes'),
Markup.button.callback('No', 'no'),
],
]));
});
// Handle button clicks
bot.action('opt_1', (ctx) => {
ctx.answerCbQuery('You chose Option 1');
ctx.editMessageText('You selected Option 1');
});Keyboard Patterns
键盘设计模式
| Pattern | Use Case |
|---|---|
| Single column | Simple menus |
| Multi column | Yes/No, pagination |
| Grid | Category selection |
| URL buttons | Links, payments |
| 模式 | 适用场景 |
|---|---|
| 单列布局 | 简单菜单 |
| 多列布局 | 是/否选择、分页 |
| 网格布局 | 分类选择 |
| URL按钮 | 链接、支付 |
Pagination
分页实现
javascript
function getPaginatedKeyboard(items, page, perPage = 5) {
const start = page * perPage;
const pageItems = items.slice(start, start + perPage);
const buttons = pageItems.map(item =>
[Markup.button.callback(item.name, `item_${item.id}`)]
);
const nav = [];
if (page > 0) nav.push(Markup.button.callback('◀️', `page_${page-1}`));
if (start + perPage < items.length) nav.push(Markup.button.callback('▶️', `page_${page+1}`));
return Markup.inlineKeyboard([...buttons, nav]);
}undefinedjavascript
function getPaginatedKeyboard(items, page, perPage = 5) {
const start = page * perPage;
const pageItems = items.slice(start, start + perPage);
const buttons = pageItems.map(item =>
[Markup.button.callback(item.name, `item_${item.id}`)]
);
const nav = [];
if (page > 0) nav.push(Markup.button.callback('◀️', `page_${page-1}`));
if (start + perPage < items.length) nav.push(Markup.button.callback('▶️', `page_${page+1}`));
return Markup.inlineKeyboard([...buttons, nav]);
}Bot Monetization
机器人变现
Making money from Telegram bots
When to use: When planning bot revenue
javascript
undefinedTelegram机器人盈利方法
适用场景:规划机器人收入来源时
javascript
undefinedBot Monetization
Bot Monetization
Revenue Models
盈利模式
| Model | Example | Complexity |
|---|---|---|
| Freemium | Free basic, paid premium | Medium |
| Subscription | Monthly access | Medium |
| Per-use | Pay per action | Low |
| Ads | Sponsored messages | Low |
| Affiliate | Product recommendations | Low |
| 模式 | 示例 | 复杂度 |
|---|---|---|
| 免费增值 | 基础功能免费,高级功能付费 | 中等 |
| 订阅制 | 月度付费访问 | 中等 |
| 按次付费 | 每次操作付费 | 低 |
| 广告 | 赞助消息 | 低 |
| 联盟营销 | 产品推荐返佣 | 低 |
Telegram Payments
Telegram支付集成
javascript
// Create invoice
bot.command('buy', (ctx) => {
ctx.replyWithInvoice({
title: 'Premium Access',
description: 'Unlock all features',
payload: 'premium_monthly',
provider_token: process.env.PAYMENT_TOKEN,
currency: 'USD',
prices: [{ label: 'Premium', amount: 999 }], // $9.99
});
});
// Handle successful payment
bot.on('successful_payment', (ctx) => {
const payment = ctx.message.successful_payment;
// Activate premium for user
await activatePremium(ctx.from.id);
ctx.reply('🎉 Premium activated!');
});javascript
// Create invoice
bot.command('buy', (ctx) => {
ctx.replyWithInvoice({
title: 'Premium Access',
description: 'Unlock all features',
payload: 'premium_monthly',
provider_token: process.env.PAYMENT_TOKEN,
currency: 'USD',
prices: [{ label: 'Premium', amount: 999 }], // $9.99
});
});
// Handle successful payment
bot.on('successful_payment', (ctx) => {
const payment = ctx.message.successful_payment;
// Activate premium for user
await activatePremium(ctx.from.id);
ctx.reply('🎉 Premium activated!');
});Freemium Strategy
免费增值策略
Free tier:
- 10 uses per day
- Basic features
- Ads shown
Premium ($5/month):
- Unlimited uses
- Advanced features
- No ads
- Priority support免费版:
- 每日限用10次
- 基础功能
- 显示广告
高级版(每月5美元):
- 无限使用
- 高级功能
- 无广告
- 优先支持Usage Limits
使用限制校验
javascript
async function checkUsage(userId) {
const usage = await getUsage(userId);
const isPremium = await checkPremium(userId);
if (!isPremium && usage >= 10) {
return { allowed: false, message: 'Daily limit reached. Upgrade?' };
}
return { allowed: true };
}undefinedjavascript
async function checkUsage(userId) {
const usage = await getUsage(userId);
const isPremium = await checkPremium(userId);
if (!isPremium && usage >= 10) {
return { allowed: false, message: 'Daily limit reached. Upgrade?' };
}
return { allowed: true };
}Anti-Patterns
反模式
❌ Blocking Operations
❌ 阻塞式操作
Why bad: Telegram has timeout limits.
Users think bot is dead.
Poor experience.
Requests pile up.
Instead: Acknowledge immediately.
Process in background.
Send update when done.
Use typing indicator.
问题所在:Telegram有超时限制。用户会觉得机器人挂了,体验糟糕,请求会堆积。
正确做法:立即回复确认,后台处理任务,完成后发送更新,使用输入状态指示器。
❌ No Error Handling
❌ 无错误处理
Why bad: Users get no response.
Bot appears broken.
Debugging nightmare.
Lost trust.
Instead: Global error handler.
Graceful error messages.
Log errors for debugging.
Rate limiting.
问题所在:用户得不到响应,机器人看起来故障,调试困难,失去用户信任。
正确做法:全局错误处理器,友好的错误提示,记录错误用于调试,限流控制。
❌ Spammy Bot
❌ 垃圾信息式机器人
Why bad: Users block the bot.
Telegram may ban.
Annoying experience.
Low retention.
Instead: Respect user attention.
Consolidate messages.
Allow notification control.
Quality over quantity.
问题所在:用户会拉黑机器人,Telegram可能封禁机器人,体验糟糕,留存率低。
正确做法:尊重用户注意力,合并消息,允许用户控制通知,重质不重量。
Related Skills
相关技能
Works well with: , , ,
telegram-mini-appbackendai-wrapper-productworkflow-automation适配技能:, , ,
telegram-mini-appbackendai-wrapper-productworkflow-automation