Skip to content

Commit

Permalink
Merge pull request #103 from AmiyaBot/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
vivien8261 authored Jul 11, 2024
2 parents 7a1c209 + 1914c99 commit ce81ec3
Show file tree
Hide file tree
Showing 8 changed files with 82 additions and 39 deletions.
17 changes: 17 additions & 0 deletions amiyabot/builtin/message/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import re
import abc
import copy
import asyncio

from typing import Callable, Optional, Union, List, Tuple, Any
Expand Down Expand Up @@ -148,6 +149,22 @@ async def wait_channel(

return None

def copy(self):
bot = self.bot
instance = self.instance

self.bot = None
self.instance = None

new_data = copy.deepcopy(self)
new_data.bot = bot
new_data.instance = instance

self.bot = bot
self.instance = instance

return new_data


class MessageMatch:
@staticmethod
Expand Down
20 changes: 13 additions & 7 deletions amiyabot/factory/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import contextlib

from amiyabot import log
from amiyabot.util import temp_sys_path, extract_zip, import_module
from amiyabot.util import temp_sys_path, extract_zip, import_module, delete_module
from amiyabot.builtin.lib.timedTask import TasksControl, Task
from amiyabot.builtin.lib.browserService import BrowserLaunchConfig

Expand Down Expand Up @@ -299,12 +299,18 @@ def uninstall_plugin(self, plugin_id: str, remove: bool = False):

self.plugins[plugin_id].uninstall()

if remove and self.plugins[plugin_id].path:
for item in self.plugins[plugin_id].path:
if os.path.isdir(item):
shutil.rmtree(item)
else:
os.remove(item)
if self.plugins[plugin_id].path:
delete_module(
os.path.basename(
self.plugins[plugin_id].path[-1],
)
)
if remove:
for item in self.plugins[plugin_id].path:
if os.path.isdir(item):
shutil.rmtree(item)
else:
os.remove(item)

del self.plugins[plugin_id]

Expand Down
17 changes: 4 additions & 13 deletions amiyabot/factory/implemented.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import re

from typing import List
from contextlib import contextmanager
from dataclasses import dataclass
from amiyabot.util import remove_prefix_once
from amiyabot.builtin.message import Message, MessageMatch, Verify, Equal
Expand Down Expand Up @@ -42,16 +41,6 @@ def func():

return func

@classmethod
@contextmanager
def restore_data(cls, result: Verify, data: Message):
if result.on_selected:
result.on_selected()
yield
if result.on_selected:
data.text_prefix = ''
data.set_text(data.text_original, set_original=False)

async def verify(self, data: Message):
result = Verify(False)

Expand Down Expand Up @@ -103,8 +92,10 @@ async def verify(self, data: Message):

# 执行自定义校验并修正其返回值
if self.custom_verify:
with self.restore_data(result, data):
res = await self.custom_verify(data)
if result.on_selected:
result.on_selected()

res = await self.custom_verify(data)

if isinstance(res, bool) or res is None:
result.result = bool(res)
Expand Down
2 changes: 1 addition & 1 deletion amiyabot/handler/messageHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ async def choice_handlers(data: Message, handlers: List[MessageHandlerItem], wai
candidate.append((Verify(True, waiter.level), waiter))

for item in handlers:
check = await item.verify(data)
check = await item.verify(data.copy())
if check:
candidate.append((check, item))

Expand Down
37 changes: 23 additions & 14 deletions amiyabot/log/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import sys
import logging

from typing import Optional
from typing import Optional, Dict
from concurrent_log_handler import ConcurrentRotatingFileHandler
from amiyabot.util import argv

Expand All @@ -17,25 +17,34 @@ class LogHandlers:
level = logging.DEBUG if debug_mode else logging.INFO
formatter = logging.Formatter(f'%(asctime)s [%(name)9s][%(levelname)9s]%(message)s')
stream_handler: Optional[logging.StreamHandler] = None
file_handlers: Dict[str, ConcurrentRotatingFileHandler] = {}

@classmethod
def get_stream_handler(cls):
def set_stream_handler(cls, logger: logging.Logger):
if not cls.stream_handler:
cls.stream_handler = logging.StreamHandler(stream=sys.stdout)
cls.stream_handler.setFormatter(cls.formatter)
cls.stream_handler.setLevel(cls.level)

return cls.stream_handler
if cls.stream_handler not in logger.handlers:
logger.addHandler(cls.stream_handler)

@classmethod
def get_file_handler(cls, save_path: str, save_filename: str):
file_handler = ConcurrentRotatingFileHandler(
filename=os.path.join(save_path, f'{save_filename}.log'),
encoding='utf-8',
maxBytes=LOG_FILE_MAX_BYTES,
backupCount=LOG_FILE_BACKUP_COUNT,
)
file_handler.setFormatter(cls.formatter)
file_handler.setLevel(cls.level)

return file_handler
def set_file_handler(cls, logger: logging.Logger, save_path: str, save_filename: str):
file_path = os.path.join(save_path, f'{save_filename}.log')
if file_path not in cls.file_handlers:
file_handler = ConcurrentRotatingFileHandler(
filename=file_path,
encoding='utf-8',
maxBytes=LOG_FILE_MAX_BYTES,
backupCount=LOG_FILE_BACKUP_COUNT,
)
file_handler.setFormatter(cls.formatter)
file_handler.setLevel(cls.level)

cls.file_handlers[file_path] = file_handler
else:
file_handler = cls.file_handlers[file_path]

if file_handler not in logger.handlers:
logger.addHandler(file_handler)
5 changes: 3 additions & 2 deletions amiyabot/log/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ def __init__(self, name: str, save_path: str = LOG_FILE_SAVE_PATH, save_filename

self.__logger = logging.getLogger(name=name)
self.__logger.setLevel(LogHandlers.level)
self.__logger.addHandler(LogHandlers.get_stream_handler())
self.__logger.addHandler(LogHandlers.get_file_handler(save_path, save_filename))

LogHandlers.set_stream_handler(self.__logger)
LogHandlers.set_file_handler(self.__logger, save_path, save_filename)

@classmethod
def use(cls, logger_cls):
Expand Down
11 changes: 9 additions & 2 deletions amiyabot/network/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import requests

from io import BytesIO
from typing import Dict, Optional
from amiyabot import log

default_headers = {
Expand All @@ -10,7 +11,13 @@
}


def download_sync(url: str, headers=None, stringify=False, progress=False, **kwargs):
def download_sync(
url: str,
headers: Optional[Dict[str, str]] = None,
stringify: bool = False,
progress: bool = False,
**kwargs,
):
try:
stream = requests.get(url, headers={**default_headers, **(headers or {})}, stream=True, timeout=30, **kwargs)
container = BytesIO()
Expand Down Expand Up @@ -39,7 +46,7 @@ def download_sync(url: str, headers=None, stringify=False, progress=False, **kwa
log.error(e, desc='download error:')


async def download_async(url, headers=None, stringify=False, **kwargs):
async def download_async(url, headers: Optional[Dict[str, str]] = None, stringify: bool = False, **kwargs):
async with log.catch('download error:', ignore=[requests.exceptions.SSLError]):
async with aiohttp.ClientSession(trust_env=True) as session:
async with session.get(url, headers={**default_headers, **(headers or {})}, **kwargs) as res:
Expand Down
12 changes: 12 additions & 0 deletions amiyabot/util/systemUtils.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,18 @@ def reload_submodules(parent):
return importlib.import_module(path)


def delete_module(module_name: str):
if module_name in sys.modules:
to_delete = [module_name]

for name in sys.modules:
if name.startswith(module_name + '.'):
to_delete.append(name)

for name in to_delete:
del sys.modules[name]


def append_sys_path(path: str):
if path not in sys.path:
sys.path.append(path)
Expand Down

0 comments on commit ce81ec3

Please sign in to comment.