importrequestsimportargparseimporttimeimportre# Could be none or personal access token https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-apiGITHUB_TOKEN="<your_github_token>"# On how to get webhooks token https://api.slack.com/messaging/webhooksSLACK_WEBHOOK="https://hooks.slack.com/services/XXXXXXXXXXX/YYYYYYYYYY/ZZZZZZZZZZZZZZ"WAIT_DURATION_SEC=600defparse_args():parser=argparse.ArgumentParser(description='Check if a GitHub pull request was merged and send a Slack message.')parser.add_argument('pr_url',help='GitHub pull request URL.')returnparser.parse_args()defparse_pr_url(pr_url):"""
Parses the PR URL and returns the owner, repository, and PR number.
Example URL: https://github.com/owner/repo/pull/123
"""pattern=r'https?://github\.com/(?P<owner>[^/]+)/(?P<repo>[^/]+)/pull/(?P<pr_number>\d+)'match=re.match(pattern,pr_url)ifmatch:returnmatch.group('owner'),match.group('repo'),int(match.group('pr_number'))else:raiseValueError('Invalid GitHub pull request URL.')defcheck_if_pr_merged(owner,repo,pr_number,github_token=None):url=f'https://api.github.com/repos/{owner}/{repo}/pulls/{pr_number}'headers={'Accept':'application/vnd.github.v3+json'}ifgithub_token:headers['Authorization']=f'token {github_token}'response=requests.get(url,headers=headers)ifresponse.status_code==200:pr_data=response.json()returnpr_data.get('merged',False)else:print(f'Error fetching PR data: {url}{response.status_code}{response.reason}')returnFalsedefsend_slack_message(slack_webhook_url,message):payload={'text':message}response=requests.post(slack_webhook_url,json=payload)ifresponse.status_code!=200:print(f'Error sending Slack message: {slack_webhook_url}{response.status_code}{response.reason}')defmain():args=parse_args()try:owner,repo,pr_number=parse_pr_url(args.pr_url)exceptValueErrorase:print(e)returnprint(f"Monitoring PR #{pr_number} in repository '{owner}/{repo}' for merge status.")whileTrue:is_merged=check_if_pr_merged(owner,repo,pr_number,GITHUB_TOKEN)ifis_merged:message=f'Pull request {args.pr_url} has been merged.'send_slack_message(SLACK_WEBHOOK,message)breakelse:time.sleep(WAIT_DURATION_SEC)if__name__=='__main__':main()
保存脚本并进行别名后,您可以使用
1
ntfslk https://github.com/owner/repo/pull/123 &
将其置于后台,当扫描到 PR 合入时就会收到消息。
如果您需要提及频道中的某个人,请在<@userID>。您可以在简介->“三个点”->复制成员 ID 中找到用户 ID 或成员 ID。