-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_webhook.py
More file actions
352 lines (284 loc) · 12.8 KB
/
github_webhook.py
File metadata and controls
352 lines (284 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# Copyright 2025 AptS-1547
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
GitHub Webhook 路由模块
本模块用于处理 GitHub Webhook 事件,并将其转发到配置的 OneBot 目标。
作者:AptS:1547
版本:0.1.0-alpha
日期:2025-04-17
本程序遵循 Apache License 2.0 许可证
"""
import logging
from fastapi import APIRouter, Request, HTTPException
from app.core import GitHubWebhookHandler
from app.botclient import BotClient
from app.models import MessageSegment
from app.models.config import get_settings
router = APIRouter()
logger = logging.getLogger(__name__)
config = get_settings()
@router.post("")
async def github_webhook(request: Request):
"""处理 GitHub webhook 请求"""
# TODO: 为了后期使用自定义模版,作为临时过渡,需要完全重构
onebot_client = BotClient.get_client("onebot")
if not onebot_client:
logger.error("OneBot 客户端未初始化,无法处理请求")
raise HTTPException(status_code=503, detail="OneBot 客户端未初始化")
content_type = request.headers.get("Content-Type")
if content_type != "application/json":
logger.info("收到非 JSON 格式的请求,忽略")
return {"status": "ignored", "message": "只处理 application/json 格式的请求"}
event_type = request.headers.get("X-GitHub-Event", "")
if not event_type:
logger.info("缺少 X-GitHub-Event 头,忽略")
return {"status": "ignored", "message": "缺少 X-GitHub-Event 头"}
payload = await request.json()
if not payload:
logger.info("请求体为空,忽略")
return {"status": "ignored", "message": "请求体为空"}
try:
await GitHubWebhookHandler.verify_signature(
request,
config.GITHUB_WEBHOOK,
request.headers.get("X-Hub-Signature-256")
)
except HTTPException as e:
logger.info("签名验证失败: %s", e.detail)
return {"status": "ignored", "message": f"签名验证失败: {e.detail}"}
repo_name = payload.get("repository", {}).get("full_name")
# 根据事件类型获取分支/PR/Issue信息用于匹配
match_info = {}
if event_type == "push":
match_info["branch"] = payload.get("ref", "").replace("refs/heads/", "")
matched_webhook = GitHubWebhookHandler.find_matching_webhook(
repo_name,
match_info.get("branch", ""),
event_type,
config.GITHUB_WEBHOOK
)
if not matched_webhook:
logger.info("找不到匹配的 webhook 配置: 仓库 %s, 事件类型 %s", repo_name, event_type)
return {"status": "ignored", "message": "找不到匹配的 webhook 配置"}
message = None
# 处理不同类型的事件
if event_type == "push":
push_data = GitHubWebhookHandler.extract_push_data(payload)
logger.info("发现新的 push 事件,来自 %s 仓库", push_data["repo_name"])
logger.info("分支: %s,推送者: %s,提交数量: %s",
push_data["branch"],
push_data["pusher"],
push_data["commit_count"])
message = format_github_push_message(
repo_name=push_data["repo_name"],
branch=push_data["branch"],
pusher=push_data["pusher"],
commit_count=push_data["commit_count"],
commits=push_data["commits"]
)
elif event_type == "pull_request":
pr_data = GitHubWebhookHandler.extract_pull_request_data(payload)
logger.info("发现新的 pull_request 事件,来自 %s 仓库", pr_data["repo_name"])
logger.info("PR #%s, 操作: %s, 用户: %s",
pr_data["pull_request_number"],
pr_data["action"],
pr_data["user"])
message = format_github_pull_request_message(
repo_name=pr_data["repo_name"],
action=pr_data["action"],
pull_request=pr_data["pull_request"],
user=pr_data["user"]
)
elif event_type == "issues":
issue_data = GitHubWebhookHandler.extract_issue_data(payload)
logger.info("发现新的 issue 事件,来自 %s 仓库", issue_data["repo_name"])
logger.info("Issue #%s, 操作: %s, 用户: %s",
issue_data["issue_number"],
issue_data["action"],
issue_data["user"])
message = format_github_issue_message(
repo_name=issue_data["repo_name"],
action=issue_data["action"],
issue=issue_data["issue"],
user=issue_data["user"]
)
elif event_type == "release":
release_data = GitHubWebhookHandler.extract_release_data(payload)
logger.info("发现新的 release 事件,来自 %s 仓库", release_data["repo_name"])
logger.info("版本: %s, 操作: %s, 用户: %s",
release_data["release_tag"],
release_data["action"],
release_data["user"])
message = format_github_release_message(
repo_name=release_data["repo_name"],
action=release_data["action"],
release=release_data["release"],
user=release_data["user"]
)
elif event_type == "issue_comment":
comment_data = GitHubWebhookHandler.extract_issue_comment_data(payload)
logger.info("发现新的 issue_comment 事件,来自 %s 仓库", comment_data["repo_name"])
logger.info("Issue #%s, 操作: %s, 用户: %s",
comment_data["issue_number"],
comment_data["action"],
comment_data["user"])
message = format_github_issue_comment_message(
repo_name=comment_data["repo_name"],
action=comment_data["action"],
comment=comment_data["comment"],
issue_number=comment_data["issue_number"],
user=comment_data["user"]
)
else:
logger.info("收到 %s 事件,但尚未实现处理逻辑", event_type)
return {"status": "ignored", "message": f"暂不处理 {event_type} 类型的事件"}
if message:
# 向配置的所有 OneBot 目标发送通知
for target in matched_webhook.ONEBOT:
logger.info("正在发送消息到 QQ %s %s", target.type, target.id)
await onebot_client.send_message(target.type, target.id, message)
return {"status": "success", "message": f"处理 {event_type} 事件成功"}
return {"status": "failed", "message": "处理事件时发生错误"}
def format_github_push_message(repo_name, branch, pusher, commit_count, commits):
"""格式化 GitHub 推送消息"""
message = [
MessageSegment.text("📢 GitHub 推送通知\n"),
MessageSegment.text(f"仓库:{repo_name}\n"),
MessageSegment.text(f"分支:{branch}\n"),
MessageSegment.text(f"推送者:{pusher}\n"),
MessageSegment.text(f"提交数量:{commit_count}\n\n"),
MessageSegment.text("最新提交:\n")
]
# 最多展示3条最新提交
for commit in commits[:3]:
short_id = commit["id"][:7]
commit_message = commit["message"].split("\n")[0] # 只取第一行
author = commit.get("author", {}).get("name", "未知")
message.append(MessageSegment.text(f"[{short_id}] {commit_message} (by {author})\n"))
return message
def format_github_pull_request_message(repo_name, action, pull_request, user):
"""格式化 GitHub Pull Request 消息"""
# 针对不同动作定制消息内容
action_text = {
"opened": "创建了",
"closed": "关闭了" if not pull_request.get("merged") else "合并了",
"reopened": "重新打开了",
"assigned": "被分配了",
"unassigned": "被取消分配了",
"review_requested": "请求审核",
"review_request_removed": "取消审核请求",
"labeled": "被添加了标签",
"unlabeled": "被移除了标签",
"synchronize": "同步了",
}.get(action, action)
message = [
MessageSegment.text(f"📢 GitHub Pull Request {action_text}\n"),
MessageSegment.text(f"仓库:{repo_name}\n"),
MessageSegment.text(f"PR #{pull_request.get('number')}: {pull_request.get('title')}\n"),
MessageSegment.text(f"用户:{user}\n"),
MessageSegment.text(f"状态:{pull_request.get('state')}\n")
]
# 添加分支信息
base = pull_request.get("base", {}).get("ref", "")
head = pull_request.get("head", {}).get("ref", "")
if base and head:
message.append(MessageSegment.text(f"目标分支:{base} ← {head}\n"))
# 添加链接
if pull_request.get("html_url"):
message.append(MessageSegment.text(f"链接:{pull_request.get('html_url')}\n"))
return message
def format_github_issue_message(repo_name, action, issue, user):
"""格式化 GitHub Issue 消息"""
# 针对不同动作定制消息内容
action_text = {
"opened": "创建了",
"closed": "关闭了",
"reopened": "重新打开了",
"assigned": "被分配了",
"unassigned": "被取消分配了",
"labeled": "被添加了标签",
"unlabeled": "被移除了标签",
}.get(action, action)
message = [
MessageSegment.text(f"📢 GitHub Issue {action_text}\n"),
MessageSegment.text(f"仓库:{repo_name}\n"),
MessageSegment.text(f"Issue #{issue.get('number')}: {issue.get('title')}\n"),
MessageSegment.text(f"用户:{user}\n"),
MessageSegment.text(f"状态:{issue.get('state')}\n")
]
# 添加标签信息
labels = issue.get("labels", [])
if labels:
label_names = [label.get("name", "") for label in labels]
message.append(MessageSegment.text(f"标签:{', '.join(label_names)}\n"))
# 添加链接
if issue.get("html_url"):
message.append(MessageSegment.text(f"链接:{issue.get('html_url')}\n"))
return message
def format_github_release_message(repo_name, action, release, user):
"""格式化 GitHub Release 消息"""
# 针对不同动作定制消息内容
action_text = {
"published": "发布了",
"created": "创建了",
"edited": "编辑了",
"deleted": "删除了",
"prereleased": "预发布了",
"released": "正式发布了",
}.get(action, action)
tag_name = release.get("tag_name", "")
name = release.get("name", tag_name) if release.get("name") else tag_name
message = [
MessageSegment.text(f"📢 GitHub Release {action_text}\n"),
MessageSegment.text(f"仓库:{repo_name}\n"),
MessageSegment.text(f"版本:{name} ({tag_name})\n"),
MessageSegment.text(f"发布者:{user}\n")
]
# 添加预发布信息
if release.get("prerelease"):
message.append(MessageSegment.text("类型:预发布\n"))
# 添加发布时间
if release.get("published_at"):
published_time = release.get("published_at")
message.append(MessageSegment.text(f"发布时间:{published_time}\n"))
# 添加链接
if release.get("html_url"):
message.append(MessageSegment.text(f"链接:{release.get('html_url')}\n"))
return message
def format_github_issue_comment_message(repo_name, action, comment, issue_number, user):
"""格式化 GitHub Issue/PR 评论消息"""
# 针对不同动作定制消息内容
action_text = {
"created": "发表了",
"edited": "编辑了",
"deleted": "删除了",
}.get(action, action)
# 判断是PR还是Issue
issue_type = "PR" if comment.get("pull_request") else "Issue"
message = [
MessageSegment.text(f"📢 GitHub {issue_type}评论 {action_text}\n"),
MessageSegment.text(f"仓库:{repo_name}\n"),
MessageSegment.text(f"{issue_type} #{issue_number}\n"),
MessageSegment.text(f"用户:{user}\n")
]
# 添加评论内容预览
body = comment.get("body", "")
if body and action != "deleted":
# 截取评论内容,最多显示100个字符
preview = body[:100] + "..." if len(body) > 100 else body
preview = preview.replace("\n", " ")
message.append(MessageSegment.text(f"内容:{preview}\n"))
# 添加链接
if comment.get("html_url"):
message.append(MessageSegment.text(f"链接:{comment.get('html_url')}\n"))
return message