tools-telegram-bot-builder

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Telegram 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
undefined

Bot Architecture

Bot Architecture

Stack Options

技术栈选项

LanguageLibraryBest For
Node.jstelegrafMost projects
Node.jsgrammYTypeScript, modern
Pythonpython-telegram-botQuick prototypes
PythonaiogramAsync, scalable
编程语言适用场景
Node.jstelegraf大多数项目
Node.jsgrammYTypeScript项目、现代开发
Pythonpython-telegram-bot快速原型开发
Pythonaiogram异步开发、高扩展性

Basic Telegraf Setup

基础Telegraf配置

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

// 命令处理器
bot.start((ctx) => ctx.reply('欢迎!'));
bot.help((ctx) => ctx.reply('我能帮你什么?'));

// 文本消息处理器
bot.on('text', (ctx) => {
  ctx.reply(`你说:${ctx.message.text}`);
});

// 启动机器人
bot.launch();

// 优雅停机
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.json
undefined
telegram-bot/
├── src/
│   ├── bot.js           # 机器人初始化文件
│   ├── commands/        # 命令处理器
│   │   ├── start.js
│   │   ├── help.js
│   │   └── settings.js
│   ├── handlers/        # 消息处理器
│   ├── keyboards/       # 内联键盘配置
│   ├── middleware/      # 认证、日志中间件
│   └── services/        # 业务逻辑服务
├── .env
└── package.json
undefined

Inline Keyboards

内联键盘

Interactive button interfaces
When to use: When building interactive bot flows
python
undefined
交互式按钮界面
适用场景:构建交互式机器人流程时
python
undefined

Inline Keyboards

Inline Keyboards

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('请选择一个选项:', Markup.inlineKeyboard([
    [Markup.button.callback('选项1', 'opt_1')],
    [Markup.button.callback('选项2', 'opt_2')],
    [
      Markup.button.callback('是', 'yes'),
      Markup.button.callback('否', 'no'),
    ],
  ]));
});

// 处理按钮点击事件
bot.action('opt_1', (ctx) => {
  ctx.answerCbQuery('你选择了选项1');
  ctx.editMessageText('你已选择选项1');
});

Keyboard Patterns

键盘设计模式

PatternUse Case
Single columnSimple menus
Multi columnYes/No, pagination
GridCategory selection
URL buttonsLinks, 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]);
}
undefined
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]);
}
undefined

Bot Monetization

机器人变现

Making money from Telegram bots
When to use: When planning bot revenue
javascript
undefined
实现Telegram机器人盈利的方法
适用场景:规划机器人收入来源时
javascript
undefined

Bot Monetization

Bot Monetization

Revenue Models

盈利模式

ModelExampleComplexity
FreemiumFree basic, paid premiumMedium
SubscriptionMonthly accessMedium
Per-usePay per actionLow
AdsSponsored messagesLow
AffiliateProduct recommendationsLow
盈利模式示例复杂度
免费增值模式基础功能免费,高级功能付费中等
订阅模式月度付费访问中等
按次付费模式每次操作付费
广告模式赞助消息
联盟营销模式产品推荐返佣

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
// 创建发票
bot.command('buy', (ctx) => {
  ctx.replyWithInvoice({
    title: '高级权限',
    description: '解锁全部功能',
    payload: 'premium_monthly',
    provider_token: process.env.PAYMENT_TOKEN,
    currency: 'USD',
    prices: [{ label: '高级权限', amount: 999 }], // 9.99美元
  });
});

// 处理支付成功事件
bot.on('successful_payment', (ctx) => {
  const payment = ctx.message.successful_payment;
  // 为用户激活高级权限
  await activatePremium(ctx.from.id);
  ctx.reply('🎉 高级权限已激活!');
});

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 };
}
undefined
javascript
async function checkUsage(userId) {
  const usage = await getUsage(userId);
  const isPremium = await checkPremium(userId);

  if (!isPremium && usage >= 10) {
    return { allowed: false, message: '每日使用限额已达,是否升级?' };
  }
  return { allowed: true };
}
undefined

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-app
,
backend
,
ai-wrapper-product
,
workflow-automation
适配技能:
telegram-mini-app
backend
ai-wrapper-product
workflow-automation