bot增加定时任务,设置每天零点执行定时任务
This commit is contained in:
parent
7f25f040a2
commit
b66f07d7d7
|
@ -0,0 +1,46 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# @Time : 2023/4/8 0:07
|
||||
# @Author : Flora.Chen
|
||||
# @File : bot_excute.py
|
||||
# @Software: PyCharm
|
||||
# @Desc:
|
||||
from api.gitlink_api import GitLinkApi
|
||||
from config.config import GLOBAL_VAR
|
||||
from bot.generate_jwt import generate_jwt_token
|
||||
from bot.mybot import MyBot
|
||||
from loguru import logger
|
||||
from datetime import datetime
|
||||
|
||||
now_time = datetime.now().strftime("%Y-%m-%d@%H-%M-%S")
|
||||
|
||||
|
||||
def create_version(host, bot):
|
||||
logger.debug("开始进入create_version方法")
|
||||
logger.debug(f"create_version全局变量-:{type(GLOBAL_VAR)}|| {GLOBAL_VAR}")
|
||||
if GLOBAL_VAR:
|
||||
global_var_copy = GLOBAL_VAR
|
||||
# 通过bot的私钥获取jwt_token
|
||||
jwt_token = generate_jwt_token(bot)
|
||||
logger.debug(f"jwt_token:{jwt_token}")
|
||||
# 通过jwt_token生成bot的access_token
|
||||
my_bot = MyBot(host)
|
||||
for key, value in GLOBAL_VAR.items():
|
||||
logger.debug(f"value={value}")
|
||||
bot_installer_id = value.get("bot_installer_id")
|
||||
access_token = my_bot.get_access_token(bot_installer_id, jwt_token)
|
||||
logger.debug(
|
||||
f"bot_id:{bot.get('bot_id')}, project: {key}, access_token:{access_token}")
|
||||
# 利用bot去请求创建发行版接口
|
||||
gitlink = GitLinkApi(host)
|
||||
req_data = {
|
||||
"tag_name": f"{now_time}",
|
||||
"name": f"{now_time}: bot触发创建",
|
||||
"body": f"bot检测到过去24小时仓库有推送,触发发行版的自动创建\n{value.get('commits_info')}",
|
||||
"target_commitish": value.get('branch')
|
||||
}
|
||||
logger.debug(f"请求接口的参数:{req_data}")
|
||||
# 调用接口创建发行版
|
||||
res = gitlink.create_version(project=key, token=access_token, req_data=req_data)
|
||||
logger.debug(f"创建发行版的响应数据::{res}")
|
||||
GLOBAL_VAR.clear()
|
||||
|
|
@ -65,11 +65,12 @@ class MyBot:
|
|||
|
||||
|
||||
if __name__ == '__main__':
|
||||
from config.config import host, bot, bot_installer_id
|
||||
from config.config import host, bot
|
||||
from bot.generate_jwt import generate_jwt_token
|
||||
|
||||
jwt_token = generate_jwt_token(bot)
|
||||
mybot = MyBot(host)
|
||||
bot_installer_id = 85589
|
||||
access_token = mybot.get_access_token(bot_installer_id, jwt_token)
|
||||
print(access_token, bot_installer_id)
|
||||
res = mybot.get_bot_installed_project(bot_installer_id, access_token)
|
||||
|
|
|
@ -10,4 +10,5 @@ bot = {
|
|||
"private_key": os.path.join(CONFIG_DIR, "private_key.txt")
|
||||
}
|
||||
|
||||
bot_installer_id = 85589
|
||||
GLOBAL_VAR = {
|
||||
}
|
||||
|
|
|
@ -0,0 +1,32 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# @Time : 2023/4/8 23:46
|
||||
# @Author : Flora.Chen
|
||||
# @File : main.py
|
||||
# @Software: PyCharm
|
||||
# @Desc:
|
||||
|
||||
import schedule
|
||||
from config.config import host, bot
|
||||
from bot.bot_excute import create_version
|
||||
from server import app
|
||||
from loguru import logger
|
||||
from config.path import LOG_DIR
|
||||
import os
|
||||
from flask_apscheduler import APScheduler
|
||||
|
||||
scheduler = APScheduler()
|
||||
|
||||
|
||||
# 定义一个定时任务:通过cron的形式来定时启动任务, 每天的xx:xx:xx时刻执行一次函数
|
||||
@scheduler.task('cron', id='do_job', day='*', hour='00', minute='00', second='00')
|
||||
def do_job():
|
||||
create_version(host, bot)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
logger.add(os.path.join(LOG_DIR, "mybot_all.log"), enqueue=True, encoding="utf-8",
|
||||
format="{time:YYYY-MM-DD HH:mm:ss} {level} From {module}.{function} : {message}")
|
||||
scheduler.init_app(app)
|
||||
scheduler.start()
|
||||
# 0.0.0.0代表电脑所有的IP。以上我们绑定了8080端口, 启动服务后我们访问的网址将是: http://127.0.0.1:8080/
|
||||
app.run(debug=True, host="0.0.0.0", port=8070)
|
|
@ -9,24 +9,36 @@ import requests
|
|||
|
||||
req_data = {
|
||||
"ref": "refs/heads/master",
|
||||
"before": "6c0fabcf749fdcf4b31b79d5195ff0acb751ef82",
|
||||
"after": "29f9413d42affe9f31e910782b24bb73aaec1540",
|
||||
"commits1": [
|
||||
|
||||
"before": "6c22220fabcf749fdcf4b31b79d5195ff0acb751ef82",
|
||||
"after": "29f3333339413d42affe9f31e910782b24bb73aaec1540",
|
||||
"commits": [
|
||||
{
|
||||
"id": "a96b8a2222247f9c1cb8882a966cbae239e09c8abc4b0",
|
||||
"message": "xixixha222hahah",
|
||||
"author": {
|
||||
"name": "floraachy",
|
||||
"email": "flower@qq.com",
|
||||
"username": ""
|
||||
},
|
||||
"timestamp": "2023-04-07T17:28:28+08:00"
|
||||
},
|
||||
{
|
||||
"id": "b1122222f9c1cb8882a966cbae239e09c8abc4b0",
|
||||
"message": "bbaba22222babab1",
|
||||
"author": {
|
||||
"name": "flora",
|
||||
"email": "flower@gitlink.com",
|
||||
"username": ""
|
||||
},
|
||||
"timestamp": "2023-04-07T17:28:28+08:00"
|
||||
},
|
||||
],
|
||||
"repository": {
|
||||
"full_name": "floraachy/bot",
|
||||
},
|
||||
"pusher": {
|
||||
"id": 42384,
|
||||
"login": "floraachy",
|
||||
"created": "2022-11-16T09:40:11+08:00",
|
||||
"full_name": "floraachy/123123123",
|
||||
}
|
||||
|
||||
}
|
||||
res = requests.post("http://127.0.0.1:8070/mybot", json=req_data)
|
||||
res = requests.post("http://127.0.0.1:8070/mybot/?installer_id=85589", json=req_data)
|
||||
|
||||
print(res.status_code)
|
||||
print(res.json())
|
||||
|
||||
|
||||
print(res.text)
|
||||
# print(res.json())
|
||||
|
|
71
server.py
71
server.py
|
@ -1,11 +1,6 @@
|
|||
from flask import Flask, request, jsonify # 使用 jsonify 工具函数响应JSON
|
||||
from api.gitlink_api import GitLinkApi
|
||||
from config.config import host, bot, bot_installer_id
|
||||
from bot.generate_jwt import generate_jwt_token
|
||||
from bot.mybot import MyBot
|
||||
from loguru import logger
|
||||
from config.path import LOG_DIR
|
||||
import os
|
||||
from config.config import GLOBAL_VAR
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
|
@ -24,49 +19,55 @@ def welcome():
|
|||
|
||||
|
||||
# @app.route('/mybot', methods=['GET','POST']), 表示同时支持GET和POST,
|
||||
@app.route('/mybot', methods=['GET', 'POST'])
|
||||
@app.route('/mybot/', methods=['GET', 'POST'])
|
||||
def get_webhook_info():
|
||||
try:
|
||||
logger.debug(f"fullpath: {request.full_path}")
|
||||
# 如果POST数据是form格式,解析POST数据:request.form, 例如:request.form.get('name')
|
||||
# 如果POST的数据是JSON格式,request.json会自动将json数据转换成Python类型(字典或者列表)
|
||||
payload = request.json
|
||||
logger.info(f"获取webhook信息成功:{type(payload)}|| {payload}")
|
||||
logger.info(f"获取webhook信息-请求内容:{type(payload)}|| {payload}")
|
||||
# 从地址中获取bot_installer_id
|
||||
bot_installer_id = dict(request.args).get("installer_id")
|
||||
logger.info(f"获取webhook信息-地址栏参数:{type(bot_installer_id)}|| {bot_installer_id}")
|
||||
if "commits" in payload.keys():
|
||||
logger.info("---------request.json中存在commits---------")
|
||||
# 根据webhook请求内容 获取仓库的名称
|
||||
repository = payload.get("repository")
|
||||
project = repository.get("full_name")
|
||||
commit_id = payload.get("after")[:10]
|
||||
# 根据webhook请求内容 获取本次推送的分支
|
||||
branch = payload.get("ref").split("/")[-1]
|
||||
author = payload.get("pusher").get("login")
|
||||
timestamp = payload.get("pusher").get("created")
|
||||
# 根据webhook请求内容,获取当次push过来的commits信息
|
||||
commits = payload.get("commits")
|
||||
# 通过bot的私钥获取jwt_token
|
||||
jwt_token = generate_jwt_token(bot)
|
||||
# 通过jwt_token生成bot的access_token
|
||||
my_bot = MyBot(host)
|
||||
access_token = my_bot.get_access_token(bot_installer_id, jwt_token)
|
||||
# 利用bot去请求创建发行版接口
|
||||
gitlink = GitLinkApi(host)
|
||||
req_data = {
|
||||
"tag_name": f"{commit_id}",
|
||||
"name": f"{author}于{timestamp}提交了代码,触发发行版的自动创建",
|
||||
"body": f"{commits}",
|
||||
"target_commitish": branch
|
||||
}
|
||||
# 调用接口创建发行版
|
||||
res = gitlink.create_version(project=project, token=access_token, req_data=req_data)
|
||||
# 根据commits信息获取每次提交的message
|
||||
commits_info = []
|
||||
for commit in commits:
|
||||
commits_info.append(
|
||||
f"{commit['author']['name']}/{commit['author']['email']}于{commit['timestamp']}在提交了代码。"
|
||||
f"commit_id是{commit['id'][:10]} || commit内容是:{commit['message']}")
|
||||
# 收集这些关键信息作为全局变量,留待定时任务处理时需要
|
||||
if not GLOBAL_VAR.get(project):
|
||||
GLOBAL_VAR[project] = {}
|
||||
if GLOBAL_VAR[project].get("bot_installer_id"):
|
||||
GLOBAL_VAR[project]["commits_info"] = GLOBAL_VAR[project]["commits_info"] + commits_info
|
||||
else:
|
||||
GLOBAL_VAR[project] = {
|
||||
"bot_installer_id": bot_installer_id,
|
||||
"commits_info": commits_info,
|
||||
"branch": branch
|
||||
}
|
||||
logger.debug(f"从服务获取的全局变量:{type(GLOBAL_VAR)}|| {GLOBAL_VAR}")
|
||||
result = jsonify({
|
||||
"code": 0,
|
||||
"msg": "success",
|
||||
"payload": request.json,
|
||||
# "result": res
|
||||
"installer_id": bot_installer_id
|
||||
}, 200)
|
||||
else:
|
||||
result = jsonify({
|
||||
"code": 1,
|
||||
"msg": "failed",
|
||||
"payload": request.json
|
||||
}, 201)
|
||||
"msg": "没有检测到commits信息,bot无法进行处理",
|
||||
}, 400)
|
||||
except Exception as e:
|
||||
result = jsonify({
|
||||
"code": -1,
|
||||
|
@ -75,8 +76,8 @@ def get_webhook_info():
|
|||
return result
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
logger.add(os.path.join(LOG_DIR, "mybot_all.log"), enqueue=True, encoding="utf-8",
|
||||
format="{time:YYYY-MM-DD HH:mm:ss} {level} From {module}.{function} : {message}")
|
||||
# 0.0.0.0代表电脑所有的IP。以上我们绑定了8080端口, 启动服务后我们访问的网址将是: http://127.0.0.1:8080/
|
||||
app.run(host="0.0.0.0", port=8070, debug=False)
|
||||
# if __name__ == '__main__':
|
||||
# logger.add(os.path.join(LOG_DIR, "mybot_all.log"), enqueue=True, encoding="utf-8",
|
||||
# format="{time:YYYY-MM-DD HH:mm:ss} {level} From {module}.{function} : {message}")
|
||||
# # 0.0.0.0代表电脑所有的IP。以上我们绑定了8080端口, 启动服务后我们访问的网址将是: http://127.0.0.1:8080/
|
||||
# app.run(host="0.0.0.0", port=8070, debug=False)
|
||||
|
|
Loading…
Reference in New Issue