Logo
热心市民王先生

04-实施指南 (Implementation Guide)

技术研究 人工智能 Telegram

1. 在 Telegram 中搜索 2. 发送 命令 3. 按提示设置 Bot 名称和用户名(必须以 结尾) 示例对话:

本章节提供详细的实施步骤,帮助你快速完成 GitHub Actions 与 Telegram Bot 的集成。

前置条件

在开始之前,请确保:

  1. ✅ 拥有一个 Telegram 账号
  2. ✅ 创建了一个 Telegram Bot(通过 @BotFather
  3. ✅ 有一个 GitHub 仓库
  4. ✅ 拥有仓库的 Settings 访问权限(用于配置 Secrets)

步骤 1:创建 Telegram Bot 并获取 Token

1.1 与 BotFather 对话

  1. 在 Telegram 中搜索 @BotFather
  2. 发送 /newbot 命令
  3. 按提示设置 Bot 名称和用户名(必须以 bot 结尾)

示例对话:

你: /newbot
BotFather: 好的,新机器人。我们要怎么称呼它?请选择机器人的名称。
你: My CI Notifier
BotFather: 不错。现在请选择机器人的用户名。它必须以 bot 结尾,例如 TetrisBot 或 tetris_bot。
你: my_ci_notifier_bot
BotFather: ✨ 完成!...
    使用此令牌访问 HTTP API:
    123456789:ABCdefGHIjklMNOpqrSTUvwxyz

1.2 保存 Token

重要:Token 是访问 Bot API 的密钥,请妥善保管!

格式:123456789:ABCdefGHIjklMNOpqrSTUvwxyz

步骤 2:获取 Chat ID

Chat ID 是消息接收方的标识,可以是:

  • 个人用户 ID(私聊 Bot)
  • 群组 ID(Bot 作为成员)
  • 频道 ID(Bot 作为管理员)

方法 1:通过 API 获取

  1. 先向 Bot 发送一条任意消息
  2. 访问以下 URL:
https://api.telegram.org/bot<你的Token>/getUpdates
  1. 在返回的 JSON 中查找 chat.id
{
  "ok": true,
  "result": [{
    "message": {
      "chat": {
        "id": 123456789,
        "type": "private"
      }
    }
  }]
}

Chat ID = 123456789

方法 2:如果是群组

  1. 将 Bot 添加到群组
  2. 发送一条消息(如 /test
  3. 访问 getUpdates API
  4. 群组 ID 格式为负数,如 -1234567890123

步骤 3:配置 GitHub Secrets

3.1 打开仓库设置

  1. 进入 GitHub 仓库页面
  2. 点击 Settings 标签
  3. 左侧菜单选择 Secrets and variablesActions

3.2 添加 Secrets

点击 New repository secret,添加以下两个 Secrets:

Secret 名称说明
TELEGRAM_TOKEN123456789:ABCdef...Bot API Token
TELEGRAM_CHAT_ID123456789接收消息的 Chat ID

配置截图示意:

┌─────────────────────────────────────────────┐
│  Name: TELEGRAM_TOKEN                       │
│  Secret: •••••••••••••••••••••••••••••••   │
└─────────────────────────────────────────────┘

步骤 4:创建工作流文件

方案 A:使用 curl(推荐入门)

在仓库中创建 .github/workflows/telegram-notify.yml

name: Telegram Notification

on:
  push:
    branches: [main, master]
  pull_request:
    branches: [main, master]
  workflow_dispatch:

jobs:
  notify:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
      
      - name: Send Telegram Notification
        env:
          TELEGRAM_TOKEN: ${{ secrets.TELEGRAM_TOKEN }}
          TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
        run: |
          # 构建消息内容
          MESSAGE=$(cat <<EOF
🔔 GitHub Actions 事件通知

📦 仓库: ${{ github.repository }}
🌿 分支: ${{ github.ref_name }}
📝 事件: ${{ github.event_name }}
👤 触发者: ${{ github.actor }}

🔗 查看详情: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
EOF
          )
          
          # 发送消息到 Telegram
          curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_TOKEN}/sendMessage" \
            -H "Content-Type: application/json" \
            -d "{
              \"chat_id\": \"${TELEGRAM_CHAT_ID }\",
              \"text\": $(echo "$MESSAGE" | jq -Rs .),
              \"parse_mode\": \"Markdown\",
              \"disable_web_page_preview\": true
            }"

方案 B:使用 GitHub Action 组件(推荐生产使用)

name: Telegram Notification with Action

on:
  push:
    branches: [main, master]
  pull_request:
    types: [opened, closed, reopened]

jobs:
  notify:
    runs-on: ubuntu-latest
    steps:
      - name: Send Telegram Message
        uses: appleboy/telegram-action@master
        with:
          to: ${{ secrets.TELEGRAM_CHAT_ID }}
          token: ${{ secrets.TELEGRAM_TOKEN }}
          message: |
            🔔 GitHub Actions 事件
            
            📦 Repository: ${{ github.repository }}
            🌿 Branch: ${{ github.ref_name }}
            📝 Event: ${{ github.event_name }}
            👤 Actor: ${{ github.actor }}
            
            Commit Message:
            ${{ github.event.head_commit.message }}
          
          format: markdown
          
          # 添加按钮(可选)
          inline_keyboard: |
            [查看提交](${{ github.event.head_commit.url }})
            [查看工作流](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})

步骤 5:测试验证

5.1 提交并推送

git add .github/workflows/telegram-notify.yml
git commit -m "Add Telegram notification workflow"
git push origin main

5.2 查看执行结果

  1. 进入 GitHub 仓库的 Actions 标签
  2. 找到 Telegram Notification 工作流
  3. 查看执行日志

预期输出:

Run curl -s -X POST ...
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   567  100   419  100   148    892    315 --:--:-- --:--:-- --:--:--  1205
{"ok":true,"result":{"message_id":123,"..."}}

5.3 检查 Telegram

打开 Telegram,确认收到通知消息:

🔔 GitHub Actions 事件通知

📦 仓库: myusername/my-repo
🌿 分支: main
📝 事件: push
👤 触发者: myusername

🔗 查看详情: https://github.com/...

常见问题与排查

问题 1:401 Unauthorized

错误信息:

{"ok":false,"error_code":401,"description":"Unauthorized"}

原因:Token 错误或过期

解决方案

  1. 重新从 @BotFather 获取 Token
  2. 更新 GitHub Secrets

问题 2:400 Bad Request - chat not found

错误信息:

{"ok":false,"error_code":400,"description":"Bad Request: chat not found"}

原因:Chat ID 错误或 Bot 未加入群组

解决方案

  1. 确认 Chat ID 正确(个人为正数,群组为负数)
  2. 如果是群组,确保 Bot 已被添加到群组
  3. 确保已向 Bot 发送过至少一条消息

问题 3:消息格式错误

错误信息:

{"ok":false,"error_code":400,"description":"Bad Request: can't parse message text"}

原因:Markdown 格式错误,如未转义的字符

解决方案

  • 使用 parse_mode: "HTML" 替代 Markdown
  • 或使用 jq 正确转义特殊字符

问题 4:网络超时

错误信息:

curl: (28) Failed to connect to api.telegram.org port 443

原因:GitHub Actions 运行环境网络问题

解决方案

  1. 添加重试机制
  2. 使用 timeout 参数

改进版本(带重试):

- name: Send Telegram Notification (with retry)
  run: |
    for i in {1..3}; do
      curl -s -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_TOKEN }}/sendMessage" \
        -H "Content-Type: application/json" \
        -d '{"chat_id":"${{ secrets.TELEGRAM_CHAT_ID }}","text":"Test"}' && break
      echo "Attempt $i failed, retrying..."
      sleep 5
    done

进阶配置

条件触发

只在特定条件下发送通知:

- name: Send Notification on Failure
  if: failure()  # 只在失败时触发
  uses: appleboy/telegram-action@master
  with:
    to: ${{ secrets.TELEGRAM_CHAT_ID }}
    token: ${{ secrets.TELEGRAM_TOKEN }}
    message: "❌ 构建失败!"

- name: Send Notification on Success
  if: success()  # 只在成功时触发
  uses: appleboy/telegram-action@master
  with:
    to: ${{ secrets.TELEGRAM_CHAT_ID }}
    token: ${{ secrets.TELEGRAM_TOKEN }}
    message: "✅ 构建成功!"

富媒体消息

发送图片或文件:

- name: Send Screenshot
  uses: appleboy/telegram-action@master
  with:
    to: ${{ secrets.TELEGRAM_CHAT_ID }}
    token: ${{ secrets.TELEGRAM_TOKEN }}
    photo: ./screenshots/test-result.png
    caption: "测试结果截图"

安全最佳实践

  1. 永远不要在代码中硬编码 Token
  2. 永远不要在日志中打印 Token
  3. 定期轮换 Token(通过 @BotFather 重新生成)
  4. 限制 Bot 权限:只授予必要的权限
  5. 使用 Environment Secrets:生产环境使用 Environment 级别的 Secrets

总结

恭喜你!现在你已经成功实现了 GitHub Actions 与 Telegram Bot 的集成。

关键要点回顾:

  • ✅ GitHub Actions 可以调用 Telegram API 发送消息
  • ❌ 无法直接发送 Slash Command(技术限制)
  • ✅ 可以通过消息内容实现类似的触发逻辑
  • 🔐 始终使用 Secrets 保护敏感信息

如需更多自定义功能,可参考 Telegram Bot API 官方文档