🔖 Update to v1.1.3

This commit is contained in:
xtaodada 2022-06-27 21:42:24 +08:00
parent 5bb2d7a8ae
commit bdccfa0be2
Signed by: xtaodada
GPG Key ID: 4CBB3F4FA8C85659
6 changed files with 65 additions and 8 deletions

View File

@ -1,4 +1,6 @@
import contextlib import contextlib
from typing import Callable, Awaitable, Set
from coloredlogs import ColoredFormatter from coloredlogs import ColoredFormatter
from datetime import datetime, timezone from datetime import datetime, timezone
from logging import getLogger, StreamHandler, CRITICAL, INFO, basicConfig, DEBUG from logging import getLogger, StreamHandler, CRITICAL, INFO, basicConfig, DEBUG
@ -12,13 +14,15 @@ import pyromod.listen
from pyrogram import Client from pyrogram import Client
import sys import sys
pgm_version = "1.1.2" pgm_version = "1.1.3"
CMD_LIST = {} CMD_LIST = {}
module_dir = __path__[0] module_dir = __path__[0]
working_dir = getcwd() working_dir = getcwd()
# solve same process # solve same process
read_context = {} read_context = {}
help_messages = {} help_messages = {}
startup_functions: Set[Callable[[], Awaitable[None]]] = set()
shutdown_functions: Set[Callable[[], Awaitable[None]]] = set()
all_permissions = [] all_permissions = []
logs = getLogger(__name__) logs = getLogger(__name__)

View File

@ -5,6 +5,7 @@ from importlib import import_module
from pyrogram import idle from pyrogram import idle
from pagermaid import bot, logs, working_dir from pagermaid import bot, logs, working_dir
from pagermaid.hook import Hook
from pagermaid.modules import module_list, plugin_list from pagermaid.modules import module_list, plugin_list
from pagermaid.utils import lang, process_exit from pagermaid.utils import lang, process_exit
@ -29,8 +30,9 @@ async def main():
plugin_list.remove(plugin_name) plugin_list.remove(plugin_name)
await process_exit(start=True, _client=bot) await process_exit(start=True, _client=bot)
logs.info(lang('start')) logs.info(lang('start'))
await Hook.startup()
await idle() await idle()
await bot.stop() await bot.stop()

View File

@ -1,4 +1,5 @@
import casbin import casbin
from logging import CRITICAL
from shutil import copyfile from shutil import copyfile
from os import path as os_path from os import path as os_path
from re import findall from re import findall
@ -10,6 +11,7 @@ from pagermaid import all_permissions, module_dir
if not os_path.exists(f"data{os_path.sep}gm_policy.csv"): if not os_path.exists(f"data{os_path.sep}gm_policy.csv"):
copyfile(f"{module_dir}{os_path.sep}assets{os_path.sep}gm_policy.csv", f"data{os_path.sep}gm_policy.csv") copyfile(f"{module_dir}{os_path.sep}assets{os_path.sep}gm_policy.csv", f"data{os_path.sep}gm_policy.csv")
permissions = casbin.Enforcer(f"pagermaid{sep}assets{sep}gm_model.conf", f"data{sep}gm_policy.csv") permissions = casbin.Enforcer(f"pagermaid{sep}assets{sep}gm_model.conf", f"data{sep}gm_policy.csv")
permissions.logger.setLevel(CRITICAL)
class Permission: class Permission:

41
pagermaid/hook.py Normal file
View File

@ -0,0 +1,41 @@
import asyncio
from pagermaid import startup_functions, shutdown_functions, logs
class Hook:
@staticmethod
def on_startup():
"""
注册一个启动钩子
"""
def decorator(function):
startup_functions.add(function)
return function
return decorator
@staticmethod
def on_shutdown():
"""
注册一个关闭钩子
"""
def decorator(function):
shutdown_functions.add(function)
return function
return decorator
@staticmethod
async def startup():
if cors := [startup() for startup in startup_functions]:
try:
await asyncio.gather(*cors)
except Exception as exception:
logs.info(f"[startup]: {type(exception)}: {exception}")
@staticmethod
async def shutdown():
if cors := [shutdown() for shutdown in shutdown_functions]:
try:
await asyncio.gather(*cors)
except Exception as exception:
logs.info(f"[shutdown]: {type(exception)}: {exception}")

View File

@ -19,6 +19,7 @@ from pagermaid.group_manager import Permission
from pagermaid.single_utils import Message, AlreadyInConversationError, TimeoutConversationError from pagermaid.single_utils import Message, AlreadyInConversationError, TimeoutConversationError
from pagermaid.utils import lang, attach_report, sudo_filter, alias_command, get_permission_name, process_exit from pagermaid.utils import lang, attach_report, sudo_filter, alias_command, get_permission_name, process_exit
from pagermaid.utils import client as httpx_client from pagermaid.utils import client as httpx_client
from pagermaid.hook import Hook
secret_generator = secrets.SystemRandom() secret_generator = secrets.SystemRandom()
@ -137,18 +138,21 @@ def listener(**args):
logs.warning( logs.warning(
"Please Don't Send Commands In The Same Conversation.." "Please Don't Send Commands In The Same Conversation.."
) )
await message.edit(lang("conversation_already_in_error")) with contextlib.suppress(BaseException):
await message.edit(lang("conversation_already_in_error"))
except TimeoutConversationError: except TimeoutConversationError:
logs.warning( logs.warning(
"Conversation Timed out while processing commands.." "Conversation Timed out while processing commands.."
) )
await message.edit(lang("conversation_timed_out_error")) with contextlib.suppress(BaseException):
await message.edit(lang("conversation_timed_out_error"))
except UserNotParticipant: except UserNotParticipant:
pass pass
except ContinuePropagation as e: except ContinuePropagation as e:
raise ContinuePropagation from e raise ContinuePropagation from e
except SystemExit: except SystemExit:
await process_exit(start=False, _client=client, message=message) await process_exit(start=False, _client=client, message=message)
await Hook.shutdown()
sys.exit(0) sys.exit(0)
except BaseException: except BaseException:
exc_info = sys.exc_info()[1] exc_info = sys.exc_info()[1]
@ -213,14 +217,17 @@ def raw_listener(filter_s):
logs.warning( logs.warning(
"Please Don't Send Commands In The Same Conversation.." "Please Don't Send Commands In The Same Conversation.."
) )
await message.edit(lang("conversation_already_in_error")) with contextlib.suppress(BaseException):
await message.edit(lang("conversation_already_in_error"))
except TimeoutConversationError: except TimeoutConversationError:
logs.warning( logs.warning(
"Conversation Timed out while processing commands.." "Conversation Timed out while processing commands.."
) )
await message.edit(lang("conversation_timed_out_error")) with contextlib.suppress(BaseException):
await message.edit(lang("conversation_timed_out_error"))
except SystemExit: except SystemExit:
await process_exit(start=False, _client=client, message=message) await process_exit(start=False, _client=client, message=message)
await Hook.shutdown()
sys.exit(0) sys.exit(0)
except UserNotParticipant: except UserNotParticipant:
pass pass

View File

@ -2,7 +2,7 @@ import importlib
import pagermaid.config import pagermaid.config
import pagermaid.modules import pagermaid.modules
from pagermaid import bot, logs, help_messages, all_permissions from pagermaid import bot, logs, help_messages, all_permissions, startup_functions, shutdown_functions
from pagermaid.listener import listener from pagermaid.listener import listener
from pagermaid.utils import lang, Message from pagermaid.utils import lang, Message
@ -17,8 +17,9 @@ def reload_all():
importlib.reload(pagermaid.config) importlib.reload(pagermaid.config)
help_messages.clear() help_messages.clear()
all_permissions.clear() all_permissions.clear()
startup_functions.clear()
shutdown_functions.clear()
importlib.reload(pagermaid.modules)
for module_name in pagermaid.modules.module_list: for module_name in pagermaid.modules.module_list:
try: try:
module = importlib.import_module(f"pagermaid.modules.{module_name}") module = importlib.import_module(f"pagermaid.modules.{module_name}")