update code

This commit is contained in:
hibiki
2021-08-17 23:17:08 +08:00
parent 3c6a365718
commit 1996f0d96a
73 changed files with 1501 additions and 1163 deletions
+36 -84
View File
@@ -1,11 +1,11 @@
from aiohttp.client_exceptions import ClientConnectorError
from nonebot.adapters.cqhttp import Bot
from utils.user_agent import get_user_agent
from utils.utils import get_local_proxy, get_bot
from utils.utils import get_local_proxy
from utils.image_utils import CreateImg
from configs.path_config import IMAGE_PATH
from typing import List
from bs4.element import Tag
from services.log import logger
from bs4 import BeautifulSoup
from pathlib import Path
import ujson as json
import nonebot
@@ -24,8 +24,7 @@ if str(platform.system()).lower() == "windows":
driver = nonebot.get_driver()
version_url = "https://github.com/HibiKier/zhenxun_bot/releases"
main_url = "https://github.com/HibiKier/zhenxun_bot"
release_url = "https://api.github.com/repos/HibiKier/zhenxun_bot/releases/latest"
_version_file = Path() / "__version__"
zhenxun_latest_tar_gz = Path() / "zhenxun_latest_file.tar.gz"
@@ -33,30 +32,24 @@ temp_dir = Path() / "temp"
backup_dir = Path() / "backup"
@driver.on_startup
def init():
@driver.on_bot_connect
async def remind(bot: Bot):
if str(platform.system()).lower() != "windows":
restart = Path() / "restart.sh"
env_file = Path() / ".env.dev"
if not restart.exists() and env_file.exists():
with open(env_file, "r", encoding="utf8") as ef:
data = ef.readlines()
port = [x.split("=")[1].strip() for x in data if "port" in x.lower()][0]
if not restart.exists():
with open(restart, "w", encoding="utf8") as f:
f.write(
"pid=$(netstat -tunlp | grep " + port + " | awk '{print $7}')\n"
f"pid=$(netstat -tunlp | grep "
+ str(bot.config.port)
+ " | awk '{print $7}')\n"
"pid=${pid%/*}\n"
"kill -9 $pid\n"
"sleep 3\n"
"python3 bot.py"
)
os.system("chmod +x ./restart.sh")
logger.info("已自动生成 restart.sh(重启) 文件,请检查是否与本地指令符合...")
@driver.on_bot_connect
async def remind(bot: Bot):
is_restart_file = Path() / 'is_restart'
logger.info("已自动生成 restart.sh(重启) 文件,请检查脚本是否与本地指令符合...")
is_restart_file = Path() / "is_restart"
if is_restart_file.exists():
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
@@ -72,9 +65,11 @@ async def check_update(bot: Bot) -> int:
_version = (
open(_version_file, "r", encoding="utf8").readline().split(":")[-1].strip()
)
latest_version, tar_gz_url = await get_latest_version()
if latest_version and tar_gz_url:
data = await get_latest_version_data()
if data:
latest_version = data["name"]
if _version != latest_version:
tar_gz_url = data["tarball_url"]
logger.info(f"检测真寻已更新,当前版本:{_version},最新版本:{latest_version}")
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
@@ -88,22 +83,22 @@ async def check_update(bot: Bot) -> int:
)
logger.info("真寻更新完毕,清理文件完成....")
logger.info("开始获取真寻更新日志.....")
update_info = await get_updated_info()
if update_info:
logger.info("获取真寻更新日志成功...开始发送日志...")
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"真寻更新完成,版本:{_version} -> {latest_version}\n"
f"更新日志:\n"
f"{update_info}",
)
else:
logger.warning("获取真寻更新日志失败...")
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"真寻更新完成,版本:{_version} -> {latest_version}\n"
f"获取真寻更新日志失败...",
)
update_info = data["body"]
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"真寻更新完成,版本:{_version} -> {latest_version}\n"
f"更新日期:{data['created_at']}\n"
f"更新日志:\n"
f"{update_info}",
)
width = 0
height = len(update_info.split('\n')) * 24
for m in update_info.split('\n'):
if len(m) * 20 > width:
width = len(m) * 17
A = CreateImg(800, height, font_size=20)
A.text((10, 10), update_info)
A.save(f'{IMAGE_PATH}/update_info.png')
return 200
else:
logger.warning(f"下载真寻最新版本失败...版本号:{latest_version}")
@@ -187,29 +182,16 @@ def _file_handle(latest_version: str):
# 获取最新版本号
async def get_latest_version() -> "str, str":
async def get_latest_version_data() -> dict:
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
for _ in range(3):
try:
async with session.get(version_url, proxy=get_local_proxy()) as res:
async with session.get(release_url, proxy=get_local_proxy()) as res:
if res.status == 200:
soup = BeautifulSoup(await res.text(), "lxml")
div = soup.find("div", {"class": "release-entry"})
latest_version = (
div.find(
"div", {"class": "f1 flex-auto min-width-0 text-normal"}
)
.find("a")
.text
)
tar_gz_url = div.find_all(
"a", {"class": "d-flex flex-items-center"}
)[-1].get("href")
tar_gz_url = f"https://github.com{tar_gz_url}"
return latest_version, tar_gz_url
return await res.json()
except (TimeoutError, ClientConnectorError):
pass
return "", ""
return {}
# 下载文件
@@ -236,33 +218,3 @@ def check_old_lines(lines: List[str], line: str) -> str:
if len(l) > len(line):
return l
return line
async def get_updated_info() -> str:
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
for _ in range(3):
try:
async with session.get(main_url, proxy=get_local_proxy()) as res:
soup = BeautifulSoup(await res.text(), "lxml")
children_list = list(soup.find("article").children)
children_list = [x for x in children_list if x != "\n"]
for i, children in enumerate(children_list):
a = children.find("a")
if a and isinstance(a, Tag) and a.get("href") == "#更新":
update_info = ""
tmp_children_list = children_list[i:]
tmp_children_list = [
x for x in tmp_children_list if "ul" in str(x)
]
for j, chi in enumerate(tmp_children_list):
if "ul" in str(chi):
update_time = children_list[i:][j + 1].text
update_info += f"更新日期:{update_time}\n"
ul = children_list[i:][j + 2]
break
for li in ul.find_all("li"):
update_info += f"\t● {li.text}\n"
return update_info
except (TimeoutError, ClientConnectorError):
pass
return ""