2022-09-08 01:08:37 +00:00
|
|
|
from abc import ABC, abstractmethod
|
2022-10-12 13:39:47 +00:00
|
|
|
from typing import Callable
|
2022-09-08 01:08:37 +00:00
|
|
|
|
|
|
|
from utils.log import logger
|
|
|
|
|
2022-10-10 11:07:28 +00:00
|
|
|
__all__ = ["Service", "init_service"]
|
2022-09-08 01:08:37 +00:00
|
|
|
|
|
|
|
|
|
|
|
class Service(ABC):
|
|
|
|
@abstractmethod
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
"""初始化"""
|
|
|
|
|
|
|
|
async def start(self):
|
|
|
|
"""启动 service"""
|
|
|
|
|
|
|
|
async def stop(self):
|
|
|
|
"""关闭 service"""
|
|
|
|
|
|
|
|
|
2022-10-12 13:39:47 +00:00
|
|
|
def init_service(func: Callable):
|
2022-09-08 01:08:37 +00:00
|
|
|
from core.bot import bot
|
2022-10-10 11:07:28 +00:00
|
|
|
|
2022-09-08 01:08:37 +00:00
|
|
|
if bot.is_running:
|
|
|
|
try:
|
|
|
|
service = bot.init_inject(func)
|
|
|
|
logger.success(f'服务 "{service.__class__.__name__}" 初始化成功')
|
|
|
|
bot.add_service(service)
|
|
|
|
except Exception as e: # pylint: disable=W0703
|
2022-10-10 11:07:28 +00:00
|
|
|
logger.exception(f"来自{func.__module__}的服务初始化失败:{e}")
|
2022-09-08 01:08:37 +00:00
|
|
|
return func
|