PaiGram/plugins/system/update.py

68 lines
2.4 KiB
Python
Raw Normal View History

2022-10-08 03:06:25 +00:00
import asyncio
import os
2022-10-08 03:06:25 +00:00
from sys import executable
from aiofiles import open as async_open
from telegram import Message, Update
from telegram.error import NetworkError
from telegram.ext import CallbackContext
from core.plugin import Plugin, handler
from utils.helpers import execute
from utils.log import logger
2023-01-07 08:00:32 +00:00
try:
import ujson as jsonlib
except ImportError:
import json as jsonlib
current_dir = os.getcwd()
UPDATE_DATA = os.path.join(current_dir, "data", "update.json")
class UpdatePlugin(Plugin):
2022-10-08 03:06:25 +00:00
def __init__(self):
self.lock = asyncio.Lock()
2022-10-08 03:06:25 +00:00
async def initialize(self) -> None:
if os.path.exists(UPDATE_DATA):
async with async_open(UPDATE_DATA) as file:
2023-01-07 08:00:32 +00:00
data = jsonlib.loads(await file.read())
try:
reply_text = Message.de_json(data, self.application.telegram.bot)
await reply_text.edit_text("重启成功")
except NetworkError as exc:
logger.error("编辑消息出现错误 %s", exc.message)
except jsonlib.JSONDecodeError:
logger.error("JSONDecodeError")
except KeyError as exc:
logger.error("编辑消息出现错误", exc_info=exc)
os.remove(UPDATE_DATA)
@handler.command("update", block=False, admin=True)
async def update(self, update: Update, context: CallbackContext):
user = update.effective_user
message = update.effective_message
args = self.get_args(context)
logger.info("用户 %s[%s] update命令请求", user.full_name, user.id)
if self.lock.locked():
2022-10-08 03:06:25 +00:00
await message.reply_text("程序正在更新 请勿重复操作")
2022-10-08 03:14:03 +00:00
return
async with self.lock:
2022-10-08 03:06:25 +00:00
reply_text = await message.reply_text("正在更新")
2022-12-25 13:26:08 +00:00
logger.info("正在更新代码")
2022-10-08 03:06:25 +00:00
await execute("git fetch --all")
if len(args) > 0:
await execute("git reset --hard origin/main")
await execute("git pull --all")
await execute("git submodule update")
if len(args) > 1:
2024-06-04 11:35:23 +00:00
await execute(f"{executable} -m pdm install")
2022-12-25 13:26:08 +00:00
logger.info("更新成功 正在重启")
2022-10-08 03:06:25 +00:00
await reply_text.edit_text("更新成功 正在重启")
async with async_open(UPDATE_DATA, mode="w", encoding="utf-8") as file:
2022-10-08 03:06:25 +00:00
await file.write(reply_text.to_json())
raise SystemExit