iT邦幫忙

2025 iThome 鐵人賽

DAY 11
0
自我挑戰組

用 Discord Bot 玩轉 DevOps系列 第 11

用BOT查詢最近一次 commit 訊息

  • 分享至 

  • xImage
  •  

繼作天讓 Bot 學會了查詢 CI/CD 建置狀態,今天要讓 Bot 能夠告訴我最近一次提交的 commit message,如此一來,不用切換到 GitHub 就能快速了解最新變更

在以下情境中都適用這個功能 :

  • 部署完成後,快速確認這次上了什麼功能
  • 建置失敗時,馬上看到最近誰提交了什麼
  • 團隊晨會時,直接問 Bot 昨晚的進度

修改部分程式碼內容如下:

def get_latest_commit():
    """獲取最近一次的 commit 資訊"""
    try:
        if not GH_TOKEN:
            return "❌ GitHub Token 未設定"
        
        headers = {
            'Authorization': f'token {GH_TOKEN}',
            'Accept': 'application/vnd.github.v3+json'
        }
        
        url = f'https://api.github.com/repos/{GITHUB_OWNER}/{GITHUB_REPO}/commits'
        params = {'per_page': 1}
        
        print(f"🌐 正在請求 GitHub Commits API: {url}")
        
        response = requests.get(url, headers=headers, params=params)
        response.raise_for_status()
        
        commits = response.json()
        
        if not commits:
            return "📭 尚未有任何 commit 記錄"
        
        commit_data = commits[0]
        return format_commit_message(commit_data)
        
    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 404:
            return "❌ 找不到倉庫"
        elif e.response.status_code == 403:
            return "❌ 權限不足"
        else:
            return f"❌ HTTP 錯誤: {e.response.status_code}"
    except Exception as e:
        return f"❌ 獲取 commit 資訊時出錯: {str(e)}"
    """格式化 commit 訊息"""
    # 取得基本資訊
    sha_short = commit_data['sha'][:7]
    message = commit_data['commit']['message']
    author_name = commit_data['commit']['author']['name']
    commit_date = commit_data['commit']['author']['date']
    
    # 取得 GitHub 使用者名稱(安全處理)
    github_username = commit_data['author']['login'] if commit_data.get('author') else author_name
    
    # 處理 commit 訊息
    first_line = message.split('\n')[0]
    if len(first_line) > 100:
        first_line = first_line[:97] + "..."
    
    # 格式化時間
    dt = datetime.fromisoformat(commit_date.replace('Z', '+00:00'))
    formatted_time = dt.strftime("%m/%d %H:%M")
    
    # 建立 GitHub 連結
    commit_url = f"https://github.com/{GITHUB_OWNER}/{GITHUB_REPO}/commit/{commit_data['sha']}"
    
    return (f"📝 **最近一次 Commit**\n"
            f"**訊息**: {first_line}\n"
            f"**作者**: {author_name} (@{github_username})\n"
            f"**時間**: {formatted_time}\n"
            f"**Commit ID**: `{sha_short}`\n"
            f"**詳細資訊**: [查看 commit]({commit_url})")
@bot.command()
async def last_commit(ctx):
    """查詢最近一次的 commit 訊息"""
    print(f"📨 收到 last_commit 指令來自 {ctx.author}")
    wait_msg = await ctx.send("🔄 正在查詢最新 commit...")
    commit_info = get_latest_commit()
    await wait_msg.edit(content=commit_info)
    print(f"✅ 已回覆 commit 資訊")

回到discord
https://ithelp.ithome.com.tw/upload/images/20250924/20169329qkq6t6CqkH.png


上一篇
用BOT查詢最近一次 build 狀態
下一篇
用BOT查看所有 pipeline 狀態
系列文
用 Discord Bot 玩轉 DevOps13
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言