Skip to content

Commit

Permalink
🔖 Update to v1.3.1
Browse files Browse the repository at this point in the history
  • Loading branch information
omg-xtao committed Mar 12, 2023
1 parent 00a45fe commit 2b37f95
Show file tree
Hide file tree
Showing 59 changed files with 1,607 additions and 1,174 deletions.
31 changes: 20 additions & 11 deletions pagermaid/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,37 @@

from coloredlogs import ColoredFormatter
from datetime import datetime, timezone
from logging import getLogger, StreamHandler, CRITICAL, INFO, basicConfig, DEBUG, Formatter, FileHandler
from logging import (
getLogger,
StreamHandler,
CRITICAL,
INFO,
basicConfig,
DEBUG,
Formatter,
FileHandler,
)
from os import getcwd

from pagermaid.config import Config
from pagermaid.scheduler import scheduler
import pyromod.listen
from pyrogram import Client

pgm_version = "1.3.0"
pgm_version_code = 1300
pgm_version = "1.3.1"
pgm_version_code = 1301
CMD_LIST = {}
module_dir = __path__[0]
working_dir = getcwd()
# solve same process
read_context = {}
help_messages = {}
hook_functions: Dict[str, Set[Callable[[], Awaitable[None]]]] = {
"startup": set(), "shutdown": set(), "command_pre": set(), "command_post": set(), "process_error": set(),
"startup": set(),
"shutdown": set(),
"command_pre": set(),
"command_post": set(),
"process_error": set(),
"load_plugins_finished": set(),
}
all_permissions = []
Expand Down Expand Up @@ -51,6 +64,7 @@

with contextlib.suppress(ImportError):
import uvloop # noqa

uvloop.install()

if not scheduler.running:
Expand All @@ -68,16 +82,11 @@


async def log(message):
logs.info(
message.replace('`', '\"')
)
logs.info(message.replace("`", '"'))
if not Config.LOG:
return
try:
await bot.send_message(
Config.LOG_ID,
message
)
await bot.send_message(Config.LOG_ID, message)
except Exception:
Config.LOG = False
Config.LOG_ID = "me"
9 changes: 6 additions & 3 deletions pagermaid/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@


async def main():
logs.info(lang('platform') + platform + lang('platform_load'))
logs.info(lang("platform") + platform + lang("platform_load"))

try:
await start_client(bot)
Expand All @@ -35,7 +35,9 @@ async def main():
try:
import_module(f"pagermaid.modules.{module_name}")
except BaseException as exception:
logs.info(f"{lang('module')} {module_name} {lang('error')}: {type(exception)}: {exception}")
logs.info(
f"{lang('module')} {module_name} {lang('error')}: {type(exception)}: {exception}"
)
for plugin_name in plugin_list.copy():
try:
import_module(f"plugins.{plugin_name}")
Expand All @@ -45,11 +47,12 @@ async def main():
plugin_manager.load_local_plugins()

await process_exit(start=True, _client=bot)
logs.info(lang('start'))
logs.info(lang("start"))
await Hook.load_success_exec()
await Hook.startup()

await idle()
await bot.stop()


bot.run(main())
9 changes: 3 additions & 6 deletions pagermaid/common/alias.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,12 @@ def get_all_alias_dict(self):

def get_all_alias_text(self) -> str:
texts = []
texts.extend(
f'`{i.command}` > `{i.alias}`'
for i in self.alias_list
)
return '\n'.join(texts)
texts.extend(f"`{i.command}` > `{i.alias}`" for i in self.alias_list)
return "\n".join(texts)

@staticmethod
def save():
with open(f"data{sep}alias.json", 'w', encoding="utf-8") as f:
with open(f"data{sep}alias.json", "w", encoding="utf-8") as f:
json_dump(Config.alias_dict, f)

@staticmethod
Expand Down
4 changes: 3 additions & 1 deletion pagermaid/common/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async def wrapped(*args, **kw):
nonlocal cache_data
bound = inspect.signature(func).bind(*args, **kw)
bound.apply_defaults()
ins_key = '|'.join([f'{k}_{v}' for k, v in bound.arguments.items()])
ins_key = "|".join([f"{k}_{v}" for k, v in bound.arguments.items()])
data: Cache = cache_data.get(ins_key, Cache(value=None, time=None))
now = datetime.datetime.now()
if (not data.time) or ((now - data.time) > ttl):
Expand All @@ -31,5 +31,7 @@ async def wrapped(*args, **kw):
except Exception as e:
raise e
return data.value

return wrapped

return wrap
23 changes: 13 additions & 10 deletions pagermaid/common/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from pagermaid.common.cache import cache
from pagermaid.utils import client

plugins_path = Path('plugins')
plugins_path = Path("plugins")


class LocalPlugin(BaseModel):
Expand Down Expand Up @@ -57,11 +57,11 @@ class RemotePlugin(LocalPlugin):
...

async def install(self) -> bool:
html = await client.get(f'{Config.GIT_SOURCE}{self.name}/main.py')
html = await client.get(f"{Config.GIT_SOURCE}{self.name}/main.py")
if html.status_code == 200:
self.remove()
with open(plugins_path / f"{self.name}.py", mode="wb") as f:
f.write(html.text.encode('utf-8'))
f.write(html.text.encode("utf-8"))
return True
return False

Expand All @@ -76,11 +76,11 @@ def __init__(self):
def load_local_version_map(self):
if not os.path.exists(plugins_path / "version.json"):
return
with open(plugins_path / "version.json", 'r', encoding="utf-8") as f:
with open(plugins_path / "version.json", "r", encoding="utf-8") as f:
self.version_map = json.load(f)

def save_local_version_map(self):
with open(plugins_path / "version.json", 'w', encoding="utf-8") as f:
with open(plugins_path / "version.json", "w", encoding="utf-8") as f:
json.dump(self.version_map, f, indent=4)

def get_local_version(self, name: str) -> Optional[float]:
Expand Down Expand Up @@ -116,15 +116,17 @@ def disable_plugin(self, name: str) -> bool:
def load_local_plugins(self) -> List[LocalPlugin]:
self.load_local_version_map()
self.plugins = []
for plugin in os.listdir('plugins'):
if plugin.endswith('.py') or plugin.endswith('.py.disabled'):
plugin = plugin[:-12] if plugin.endswith('.py.disabled') else plugin[:-3]
for plugin in os.listdir("plugins"):
if plugin.endswith(".py") or plugin.endswith(".py.disabled"):
plugin = (
plugin[:-12] if plugin.endswith(".py.disabled") else plugin[:-3]
)
self.plugins.append(
LocalPlugin(
name=plugin,
installed=self.get_plugin_install_status(plugin),
status=self.get_plugin_load_status(plugin),
version=self.get_local_version(plugin)
version=self.get_local_version(plugin),
)
)
return self.plugins
Expand All @@ -140,7 +142,8 @@ async def _load_remote_plugins(self) -> List[RemotePlugin]:
RemotePlugin(
**plugin,
status=False,
) for plugin in plugin_list
)
for plugin in plugin_list
]
self.remote_plugins = plugins
self.remote_version_map = {}
Expand Down
13 changes: 11 additions & 2 deletions pagermaid/common/reload.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,14 @@

import pagermaid.config
import pagermaid.modules
from pagermaid import read_context, bot, help_messages, all_permissions, hook_functions, logs
from pagermaid import (
read_context,
bot,
help_messages,
all_permissions,
hook_functions,
logs,
)
from pagermaid.common.plugin import plugin_manager
from pagermaid.hook import Hook
from pagermaid.utils import lang
Expand Down Expand Up @@ -32,7 +39,9 @@ async def reload_all():
if module_name in loaded_plugins:
importlib.reload(module)
except BaseException as exception:
logs.info(f"{lang('module')} {module_name} {lang('error')}: {type(exception)}: {exception}")
logs.info(
f"{lang('module')} {module_name} {lang('error')}: {type(exception)}: {exception}"
)
for plugin_name in pagermaid.modules.plugin_list.copy():
try:
plugin = importlib.import_module(f"plugins.{plugin_name}")
Expand Down
16 changes: 8 additions & 8 deletions pagermaid/common/status.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ class Status(BaseModel):
async def human_time_duration(seconds) -> str:
parts = {}
time_units = (
('%m', 60 * 60 * 24 * 30),
('%d', 60 * 60 * 24),
('%H', 60 * 60),
('%M', 60),
('%S', 1)
("%m", 60 * 60 * 24 * 30),
("%d", 60 * 60 * 24),
("%H", 60 * 60),
("%M", 60),
("%S", 1),
)
for unit, div in time_units:
amount, seconds = divmod(int(seconds), div)
Expand All @@ -48,7 +48,7 @@ async def get_status() -> Status:
return Status(
version=pgm_version,
run_time=uptime,
cpu_percent=f'{cpu_percent}%',
ram_percent=f'{ram_stat.percent}%',
swap_percent=f'{swap_stat.percent}%',
cpu_percent=f"{cpu_percent}%",
ram_percent=f"{ram_stat.percent}%",
swap_percent=f"{swap_stat.percent}%",
)
10 changes: 5 additions & 5 deletions pagermaid/common/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ async def run_eval(cmd: str, message=None, only_result: bool = False) -> str:
async def aexec(code, event, client):
exec(
(
(
("async def __aexec(e, client): " + "\n msg = message = e")
+ "\n reply = message.reply_to_message if message else None"
)
+ "\n chat = e.chat if e else None"
(
("async def __aexec(e, client): " + "\n msg = message = e")
+ "\n reply = message.reply_to_message if message else None"
)
+ "\n chat = e.chat if e else None"
)
+ "".join(f"\n {x}" for x in code.split("\n"))
)
Expand Down
6 changes: 3 additions & 3 deletions pagermaid/common/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@


async def update(force: bool = False):
await execute('git fetch --all')
await execute("git fetch --all")
if force:
await execute('git reset --hard origin/master')
await execute('git pull --all')
await execute("git reset --hard origin/master")
await execute("git pull --all")
await execute(f"{executable} -m pip install --upgrade -r requirements.txt")
await execute(f"{executable} -m pip install -r requirements.txt")
Loading

0 comments on commit 2b37f95

Please sign in to comment.