bot增加定时任务,设置每天零点执行定时任务

This commit is contained in:
floraachy 2023-04-21 09:51:08 +08:00
parent 7f25f040a2
commit b66f07d7d7
6 changed files with 145 additions and 52 deletions

46
bot/bot_excute.py Normal file
View File

@ -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()

View File

@ -65,11 +65,12 @@ class MyBot:
if __name__ == '__main__': 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 from bot.generate_jwt import generate_jwt_token
jwt_token = generate_jwt_token(bot) jwt_token = generate_jwt_token(bot)
mybot = MyBot(host) mybot = MyBot(host)
bot_installer_id = 85589
access_token = mybot.get_access_token(bot_installer_id, jwt_token) access_token = mybot.get_access_token(bot_installer_id, jwt_token)
print(access_token, bot_installer_id) print(access_token, bot_installer_id)
res = mybot.get_bot_installed_project(bot_installer_id, access_token) res = mybot.get_bot_installed_project(bot_installer_id, access_token)

View File

@ -10,4 +10,5 @@ bot = {
"private_key": os.path.join(CONFIG_DIR, "private_key.txt") "private_key": os.path.join(CONFIG_DIR, "private_key.txt")
} }
bot_installer_id = 85589 GLOBAL_VAR = {
}

32
main.py Normal file
View File

@ -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)

View File

@ -9,24 +9,36 @@ import requests
req_data = { req_data = {
"ref": "refs/heads/master", "ref": "refs/heads/master",
"before": "6c0fabcf749fdcf4b31b79d5195ff0acb751ef82", "before": "6c22220fabcf749fdcf4b31b79d5195ff0acb751ef82",
"after": "29f9413d42affe9f31e910782b24bb73aaec1540", "after": "29f3333339413d42affe9f31e910782b24bb73aaec1540",
"commits1": [ "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": { "repository": {
"full_name": "floraachy/bot", "full_name": "floraachy/123123123",
},
"pusher": {
"id": 42384,
"login": "floraachy",
"created": "2022-11-16T09:40:11+08:00",
} }
} }
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.status_code)
print(res.json()) print(res.text)
# print(res.json())

View File

@ -1,11 +1,6 @@
from flask import Flask, request, jsonify # 使用 jsonify 工具函数响应JSON 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 loguru import logger
from config.path import LOG_DIR from config.config import GLOBAL_VAR
import os
app = Flask(__name__) app = Flask(__name__)
@ -24,49 +19,55 @@ def welcome():
# @app.route('/mybot', methods=['GET','POST']), 表示同时支持GET和POST # @app.route('/mybot', methods=['GET','POST']), 表示同时支持GET和POST
@app.route('/mybot', methods=['GET', 'POST']) @app.route('/mybot/', methods=['GET', 'POST'])
def get_webhook_info(): def get_webhook_info():
try: try:
logger.debug(f"fullpath: {request.full_path}")
# 如果POST数据是form格式解析POST数据request.form 例如request.form.get('name') # 如果POST数据是form格式解析POST数据request.form 例如request.form.get('name')
# 如果POST的数据是JSON格式request.json会自动将json数据转换成Python类型字典或者列表 # 如果POST的数据是JSON格式request.json会自动将json数据转换成Python类型字典或者列表
payload = request.json 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(): if "commits" in payload.keys():
logger.info("---------request.json中存在commits---------") logger.info("---------request.json中存在commits---------")
# 根据webhook请求内容 获取仓库的名称
repository = payload.get("repository") repository = payload.get("repository")
project = repository.get("full_name") project = repository.get("full_name")
commit_id = payload.get("after")[:10] # 根据webhook请求内容 获取本次推送的分支
branch = payload.get("ref").split("/")[-1] branch = payload.get("ref").split("/")[-1]
author = payload.get("pusher").get("login") # 根据webhook请求内容获取当次push过来的commits信息
timestamp = payload.get("pusher").get("created")
commits = payload.get("commits") commits = payload.get("commits")
# 通过bot的私钥获取jwt_token # 根据commits信息获取每次提交的message
jwt_token = generate_jwt_token(bot) commits_info = []
# 通过jwt_token生成bot的access_token for commit in commits:
my_bot = MyBot(host) commits_info.append(
access_token = my_bot.get_access_token(bot_installer_id, jwt_token) f"{commit['author']['name']}/{commit['author']['email']}{commit['timestamp']}在提交了代码。"
# 利用bot去请求创建发行版接口 f"commit_id是{commit['id'][:10]} || commit内容是{commit['message']}")
gitlink = GitLinkApi(host) # 收集这些关键信息作为全局变量,留待定时任务处理时需要
req_data = { if not GLOBAL_VAR.get(project):
"tag_name": f"{commit_id}", GLOBAL_VAR[project] = {}
"name": f"{author}{timestamp}提交了代码,触发发行版的自动创建", if GLOBAL_VAR[project].get("bot_installer_id"):
"body": f"{commits}", GLOBAL_VAR[project]["commits_info"] = GLOBAL_VAR[project]["commits_info"] + commits_info
"target_commitish": branch else:
} GLOBAL_VAR[project] = {
# 调用接口创建发行版 "bot_installer_id": bot_installer_id,
res = gitlink.create_version(project=project, token=access_token, req_data=req_data) "commits_info": commits_info,
"branch": branch
}
logger.debug(f"从服务获取的全局变量:{type(GLOBAL_VAR)}|| {GLOBAL_VAR}")
result = jsonify({ result = jsonify({
"code": 0, "code": 0,
"msg": "success", "msg": "success",
"payload": request.json, "payload": request.json,
# "result": res "installer_id": bot_installer_id
}, 200) }, 200)
else: else:
result = jsonify({ result = jsonify({
"code": 1, "code": 1,
"msg": "failed", "msg": "没有检测到commits信息bot无法进行处理",
"payload": request.json }, 400)
}, 201)
except Exception as e: except Exception as e:
result = jsonify({ result = jsonify({
"code": -1, "code": -1,
@ -75,8 +76,8 @@ def get_webhook_info():
return result return result
if __name__ == '__main__': # if __name__ == '__main__':
logger.add(os.path.join(LOG_DIR, "mybot_all.log"), enqueue=True, encoding="utf-8", # 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}") # 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/ # # 0.0.0.0代表电脑所有的IP。以上我们绑定了8080端口, 启动服务后我们访问的网址将是: http://127.0.0.1:8080/
app.run(host="0.0.0.0", port=8070, debug=False) # app.run(host="0.0.0.0", port=8070, debug=False)