🚀 快速安装

复制以下命令并运行,立即安装此 Skill:

npx skills add https://skills.sh/claude-office-skills/skills/telegram-bot

💡 提示:需要 Node.js 和 NPM

Telegram 机器人 (Telegram Bot)

构建用于聊天机器人、通知、AI 助手和群组自动化的 Telegram 机器人。基于 n8n 的 Telegram 工作流模板。

概述 (Overview)

此技能涵盖:

  • 机器人设置和配置
  • 消息处理模式
  • AI 驱动的助手
  • 通知工作流
  • 群组自动化

机器人设置 (Bot Setup)

创建机器人 (Creating a Bot)

setup_steps:
  1. create_bot:
      - open: 在 Telegram 上打开 @BotFather (open @BotFather on Telegram)
      - command: /newbot
      - provide: 机器人名称 (bot_name)
      - provide: 机器人用户名(必须以 'bot' 结尾)(bot_username - must end in 'bot')
      - receive: API 令牌 (API_token)
      
  2. configure_bot:
      - command: /setdescription
      - command: /setabouttext
      - command: /setuserpic
      - command: /setcommands
      
  3. get_chat_id:
      - start: 与机器人开始对话 (start conversation with bot)
      - call: https://api.telegram.org/bot{TOKEN}/getUpdates
      - extract: 从响应中提取 chat.id (extract chat.id from response)

机器人命令 (Bot Commands)

commands:
  - command: /start
    description: "启动机器人 (Start the bot)"
    
  - command: /help
    description: "显示可用命令 (Show available commands)"
    
  - command: /status
    description: "检查系统状态 (Check system status)"
    
  - command: /subscribe
    description: "订阅通知 (Subscribe to notifications)"
    
  - command: /unsubscribe
    description: "取消订阅通知 (Unsubscribe from notifications)"

消息处理器 (Message Handlers)

基本消息处理器 (Basic Message Handler)

workflow: "Telegram 消息处理器 (Telegram Message Handler)"
trigger: telegram_message

handlers:
  text_message:
    action: |
      1. 解析消息文本 (Parse message text)
      2. 确定意图 (Determine intent)
      3. 处理请求 (Process request)
      4. 发送回复 (Send response)
      
  command:
    pattern: "^/"
    action: 路由到命令处理器 (route_to_command_handler)
    
  photo:
    action: |
      1. 下载照片 (Download photo)
      2. 使用视觉 AI 处理 (Process with vision AI)
      3. 回复分析结果 (Respond with analysis)
      
  document:
    action: |
      1. 下载文档 (Download document)
      2. 提取内容 (Extract content)
      3. 处理并回复 (Process and respond)
      
  voice:
    action: |
      1. 下载音频 (Download audio)
      2. 使用 Whisper 转录 (Transcribe with Whisper)
      3. 处理文本 (Process text)
      4. 回复(文本或语音)(Respond - text or voice)
      
  location:
    action: |
      1. 提取坐标 (Extract coordinates)
      2. 查找本地信息 (Lookup local info)
      3. 回复相关数据 (Respond with relevant data)

n8n 工作流 (n8n Workflow)

workflow: "Telegram 机器人 n8n (Telegram Bot n8n)"

nodes:
  - name: "Telegram 触发器 (Telegram Trigger)"
    type: "n8n-nodes-base.telegramTrigger"
    parameters:
      updates: ["message", "callback_query"]
      
  - name: "路由消息类型 (Route Message Type)"
    type: "n8n-nodes-base.switch"
    parameters:
      rules:
        - output: 0
          condition: "{{ $json.message.text.startsWith('/') }}"
        - output: 1
          condition: "{{ $json.message.photo }}"
        - output: 2
          condition: "{{ $json.message.voice }}"
        - output: 3
          fallback: true
          
  - name: "使用 AI 处理 (Process with AI)"
    type: "n8n-nodes-base.openAi"
    parameters:
      model: "gpt-4"
      messages:
        - role: "system"
          content: "你是一个乐于助人的 Telegram 助手。 (You are a helpful Telegram assistant.)"
        - role: "user"
          content: "{{ $json.message.text }}"
          
  - name: "发送回复 (Send Response)"
    type: "n8n-nodes-base.telegram"
    parameters:
      chatId: "{{ $json.message.chat.id }}"
      text: "{{ $json.response }}"

AI 驱动的机器人 (AI-Powered Bot)

GPT-4 集成 (GPT-4 Integration)

ai_bot:
  name: "AI 助手机器人 (AI Assistant Bot)"
  
  system_prompt: |
    你是 Telegram 上一个乐于助人的 AI 助手。
    (You are a helpful AI assistant on Telegram.)
    
    准则 (Guidelines):
    - 保持简洁(Telegram 有消息长度限制)(Be concise - Telegram has message limits)
    - 适当使用表情符号 (Use emojis appropriately)
    - 在有用时使用 markdown 格式化 (Format with markdown when helpful)
    - 如有必要,提出澄清性问题 (Ask clarifying questions if needed)
    
  features:
    - conversational_memory: true
    - context_window: 最后 10 条消息 (last_10_messages)
    - tools: [网络搜索 (web_search), 计算器 (calculator), 天气 (weather)]
    
  message_formatting:
    max_length: 4096
    split_long_messages: true
    use_markdown: true

多模态机器人 (Multi-Modal Bot)

multimodal_bot:
  handlers:
    text:
      model: gpt-4
      action: 聊天完成 (chat_completion)
      
    image:
      model: gpt-4-vision
      action: 分析并回复 (analyze_and_respond)
      
    voice:
      transcribe: whisper
      process: gpt-4
      respond: 文本或语音 (text_or_voice)
      
    document:
      extract: 根据类型 (based_on_type)
      summarize: gpt-4
      respond: 文本 (text)

通知系统 (Notification System)

警报机器人 (Alert Bot)

workflow: "系统警报机器人 (System Alert Bot)"

triggers:
  - source: 监控系统 (monitoring_system)
    event: 警报 (alert)
  - source: CI/CD
    event: 构建状态 (build_status)
  - source: 电商 (ecommerce)
    event: 新订单 (new_order)
    
notification_templates:
  alert:
    format: |
      🚨 *警报:{severity} (Alert: {severity})*
      
      *服务 (Service):* {service}
      *消息 (Message):* {message}
      *时间 (Time):* {timestamp}
      
      [查看仪表板 (View Dashboard)]({dashboard_link})
      
  build:
    format: |
      {status_emoji} *构建 {status} (Build {status})*
      
      *项目 (Project):* {project}
      *分支 (Branch):* {branch}
      *提交 (Commit):* `{commit_short}`
      
      {details}
      
  order:
    format: |
      🛒 *新订单!(New Order!)*
      
      *订单 (Order):* #{order_id}
      *客户 (Customer):* {customer}
      *总计 (Total):* ${total}
      *商品数 (Items):* {item_count}
      
routing:
  by_severity:
    critical: [管理员群组 (admin_group), 值班人员 (on_call_user)]
    warning: [团队群组 (team_group)]
    info: [日志频道 (logging_channel)]

定时通知 (Scheduled Notifications)

scheduled_notifications:
  daily_digest:
    schedule: "每日上午 9 点 (9am daily)"
    template: |
      📊 *每日摘要 - {date} (Daily Summary)*
      
      📈 销售额 (Sales): ${sales} ({change})
      👥 新用户 (New users): {new_users}
      🎫 未处理工单 (Open tickets): {tickets}
      
      祝你有美好的一天!☀️ (Have a great day!)
      
  weekly_report:
    schedule: "周一上午 9 点 (Monday 9am)"
    template: 每周指标报告 (weekly_metrics_report)
    
  reminder:
    trigger: 自定义事件 (custom_event)
    template: |
      ⏰ *提醒 (Reminder)*
      
      {reminder_text}
      
      创建者 (Scheduled by): {creator}

群组自动化 (Group Automation)

欢迎机器人 (Welcome Bot)

group_bot:
  on_member_join:
    action: |
      1. 检查是否为新成员 (Check if new member)
      2. 发送欢迎消息 (Send welcome message)
      3. 分享规则 (Share rules)
      4. 建议自我介绍 (Suggest introduction)
      
    template: |
      👋 欢迎来到 {group_name},{user_name}!(Welcome to {group_name}, {user_name}!)
      
      请 (Please):
      1. 阅读 /rules
      2. 介绍一下自己 (Introduce yourself)
      3. 随时提问 (Ask questions anytime)!
      
      祝您愉快!🎉 (Enjoy your stay!)
      
  on_member_leave:
    action: 可选的告别 (optional_goodbye)
    
  moderation:
    - spam_detection: 自动删除 + 警告 (auto_delete + warn)
    - link_filtering: 仅限白名单 (whitelist_only)
    - flood_control: 速率限制 (rate_limit)

投票与调查机器人 (Poll & Survey Bot)

poll_bot:
  commands:
    /poll:
      format: "/poll 问题 | 选项1 | 选项2 | ..."
      action: 创建投票 (create_poll)
      
    /survey:
      action: 开始多问题调查 (start_multi_question_survey)
      
    /results:
      action: 显示汇总结果 (show_aggregated_results)
      
  features:
    - anonymous_voting: 可选 (optional)
    - multiple_choice: 可选 (optional)
    - scheduled_close: 可选 (optional)
    - export_results: 导出到表格 (to_sheets)

内联功能 (Inline Features)

内联键盘 (Inline Keyboard)

inline_keyboard:
  example:
    text: "选择一个选项: (Choose an option:)"
    keyboard:
      - row:
          - text: "选项 1 (Option 1)"
            callback_data: "opt_1"
          - text: "选项 2 (Option 2)"
            callback_data: "opt_2"
      - row:
          - text: "取消 (Cancel)"
            callback_data: "cancel"
            
  callback_handler:
    opt_1:
      action: 处理选项 1 (process_option_1)
      response: "你选择了选项 1 (You selected Option 1)"
      
    opt_2:
      action: 处理选项 2 (process_option_2)
      response: "你选择了选项 2 (You selected Option 2)"
      
    cancel:
      action: 取消操作 (cancel_operation)
      response: "操作已取消 (Operation cancelled)"

内联查询 (Inline Query)

inline_mode:
  trigger: "@botname 查询 (query)"
  
  results:
    - type: 文章 (article)
      title: "{query} 结果 (result)"
      description: "点击发送 (Click to send)"
      message_text: "查询结果:{query} (Result for: {query})"
      
    - type: 照片 (photo)
      photo_url: "{search_result_image}"
      
    - type: GIF
      gif_url: "{gif_url}"

输出示例 (Output Example)

请求 (Request): “为服务器警报创建一个 Telegram 通知机器人 (Create a Telegram notification bot for server alerts)”

输出 (Output):

# 服务器警报 Telegram 机器人 (Server Alert Telegram Bot)

## 设置 (Setup)

1. 使用 @BotFather 创建机器人 (Create bot with @BotFather)
2. 获取令牌:`123456:ABC-DEF...` (Get token)
3. 获取警报频道的聊天 ID (Get chat ID for alerts channel)

## n8n 工作流 (n8n Workflow)

```yaml
节点 (nodes):
  1. Webhook(接收警报)(Webhook - receives alerts)
  2. 格式化消息 (Format Message)
  3. Telegram 发送 (Telegram Send)

警报模板 (Alert Templates)

严重警报 (Critical Alert):

🚨 严重警报 (CRITICAL ALERT)

服务器 (Server): production-web-01
状态 (Status): 宕机 (DOWN)
时间 (Time): 2026-01-30 14:32:05 UTC

详情 (Details):
- CPU: 98%
- 内存 (Memory): 95%
- 磁盘 (Disk): 89%

[查看 Grafana (View Grafana)] [确认 (Acknowledge)]

恢复 (Recovery):

✅ 已恢复 (RECOVERED)

服务器 (Server): production-web-01
停机时间 (Downtime): 5 分钟 (5 minutes)
状态 (Status): 所有系统正常 (All systems normal)

事件已自动解决 (Incident resolved automatically).

实现 (Implementation)

// 发送警报函数 (Send alert function)
async function sendAlert(severity, message, details) {
  const emoji = {
    critical: '🚨',
    warning: '⚠️',
    info: 'ℹ️',
    success: '✅'
  };
  
  const text = `${emoji[severity]} *${severity.toUpperCase()}*\n\n${message}\n\n${details}`;
  
  await telegram.sendMessage({
    chat_id: ALERT_CHANNEL_ID,
    text: text,
    parse_mode: 'Markdown'
  });
}

功能 (Features)

  • 基于严重程度的路由 (Severity-based routing)
  • 内联操作按钮 (Inline action buttons)
  • 确认跟踪 (Acknowledgment tracking)
  • 升级规则 (Escalation rules)

---

*Telegram 机器人技能 - Claude 办公技能套件的一部分 (Telegram Bot Skill - Part of Claude Office Skills)*

📄 原始文档

完整文档(英文):

https://skills.sh/claude-office-skills/skills/telegram-bot

💡 提示:点击上方链接查看 skills.sh 原始英文文档,方便对照翻译。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。