2018-06-15 06:58:24 +08:00
|
|
|
import os
|
|
|
|
import importlib
|
|
|
|
import logging
|
|
|
|
import re
|
|
|
|
import asyncio
|
|
|
|
from typing import Any
|
|
|
|
|
|
|
|
from aiocqhttp import CQHttp
|
|
|
|
from aiocqhttp.message import Message
|
|
|
|
|
2018-06-27 22:05:12 +08:00
|
|
|
from .message import handle_message
|
|
|
|
from .notice import handle_notice
|
|
|
|
from .logger import logger
|
2018-06-15 06:58:24 +08:00
|
|
|
|
|
|
|
|
|
|
|
def create_bot(config_object: Any = None):
|
|
|
|
if config_object is None:
|
|
|
|
from . import default_config as config_object
|
|
|
|
|
|
|
|
kwargs = {k.lower(): v for k, v in config_object.__dict__.items()
|
|
|
|
if k.isupper() and not k.startswith('_')}
|
|
|
|
|
|
|
|
bot = CQHttp(message_class=Message, **kwargs)
|
|
|
|
bot.config = config_object
|
|
|
|
if bot.config.DEBUG:
|
|
|
|
logger.setLevel(logging.DEBUG)
|
|
|
|
else:
|
|
|
|
logger.setLevel(logging.INFO)
|
|
|
|
bot.asgi.debug = bot.config.DEBUG
|
|
|
|
|
|
|
|
@bot.on_message
|
|
|
|
async def _(ctx):
|
2018-06-27 22:05:12 +08:00
|
|
|
asyncio.ensure_future(handle_message(bot, ctx))
|
2018-06-15 06:58:24 +08:00
|
|
|
|
|
|
|
@bot.on_notice
|
|
|
|
async def _(ctx):
|
2018-06-27 22:05:12 +08:00
|
|
|
asyncio.ensure_future(handle_notice(bot, ctx))
|
2018-06-15 06:58:24 +08:00
|
|
|
|
|
|
|
@bot.on_request
|
|
|
|
async def _(ctx):
|
2018-06-27 22:05:12 +08:00
|
|
|
pass
|
|
|
|
# asyncio.ensure_future(plugin.handle_request(bot, ctx))
|
2018-06-15 06:58:24 +08:00
|
|
|
|
|
|
|
return bot
|
|
|
|
|
|
|
|
|
|
|
|
_plugins = set()
|
|
|
|
|
|
|
|
|
2018-06-26 10:25:11 +08:00
|
|
|
def load_plugins(plugin_dir: str, module_prefix: str):
|
|
|
|
for name in os.listdir(plugin_dir):
|
|
|
|
path = os.path.join(plugin_dir, name)
|
2018-06-15 06:58:24 +08:00
|
|
|
if os.path.isfile(path) and \
|
2018-06-26 10:25:11 +08:00
|
|
|
(name.startswith('_') or not name.endswith('.py')):
|
2018-06-15 06:58:24 +08:00
|
|
|
continue
|
|
|
|
if os.path.isdir(path) and \
|
2018-06-26 10:25:11 +08:00
|
|
|
(name.startswith('_') or not os.path.exists(
|
2018-06-15 06:58:24 +08:00
|
|
|
os.path.join(path, '__init__.py'))):
|
|
|
|
continue
|
|
|
|
|
2018-06-26 10:25:11 +08:00
|
|
|
m = re.match(r'([_A-Z0-9a-z]+)(.py)?', name)
|
2018-06-15 06:58:24 +08:00
|
|
|
if not m:
|
|
|
|
continue
|
|
|
|
|
2018-06-26 10:25:11 +08:00
|
|
|
mod_name = f'{module_prefix}.{m.group(1)}'
|
2018-06-15 06:58:24 +08:00
|
|
|
try:
|
|
|
|
_plugins.add(importlib.import_module(mod_name))
|
|
|
|
logger.info('Succeeded to import "{}"'.format(mod_name))
|
|
|
|
except ImportError:
|
|
|
|
logger.warning('Failed to import "{}"'.format(mod_name))
|
2018-06-26 10:25:11 +08:00
|
|
|
|
|
|
|
|
|
|
|
def load_builtin_plugins():
|
|
|
|
plugin_dir = os.path.join(os.path.dirname(__file__), 'plugins')
|
|
|
|
load_plugins(plugin_dir, 'none.plugins')
|
2018-06-27 22:05:12 +08:00
|
|
|
|
|
|
|
|
|
|
|
from .command import on_command
|
|
|
|
from .notice import on_notice
|