Create NoneBot class inheriting CQHttp

This commit is contained in:
Richard Chien 2018-07-04 09:28:31 +08:00
parent 2a2a7a2ae3
commit 030a31e63f
8 changed files with 44 additions and 36 deletions

View File

@ -8,19 +8,24 @@ from typing import Any
from aiocqhttp import CQHttp
from aiocqhttp.message import Message
from . import default_config
from .log import logger
from .message import handle_message
from .notice_request import handle_notice_or_request
def create_bot(config_object: Any = None) -> CQHttp:
class NoneBot(CQHttp):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.config = default_config
def create_bot(config_object: Any = None) -> NoneBot:
if config_object is None:
from . import default_config as config_object
config_object = default_config
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 = NoneBot(message_class=Message, **kwargs)
bot.config = config_object
if bot.config.DEBUG:
logger.setLevel(logging.DEBUG)
@ -28,6 +33,9 @@ def create_bot(config_object: Any = None) -> CQHttp:
logger.setLevel(logging.INFO)
bot.asgi.debug = bot.config.DEBUG
from .message import handle_message
from .notice_request import handle_notice_or_request
@bot.on_message
async def _(ctx):
asyncio.ensure_future(handle_message(bot, ctx))

View File

@ -5,10 +5,9 @@ from typing import (
Tuple, Union, Callable, Iterable, Dict, Any, Optional, Sequence
)
from aiocqhttp import CQHttp
from aiocqhttp.message import Message
from . import permission as perm
from . import NoneBot, permission as perm
from .expression import render
from .helpers import context_id
from .session import BaseSession
@ -159,7 +158,7 @@ class CommandSession(BaseSession):
__slots__ = ('cmd', 'current_key', 'current_arg', 'current_arg_text',
'current_arg_images', 'args', 'last_interaction')
def __init__(self, bot: CQHttp, ctx: Dict[str, Any], cmd: Command, *,
def __init__(self, bot: NoneBot, ctx: Dict[str, Any], cmd: Command, *,
current_arg: str = '', args: Optional[Dict[str, Any]] = None):
super().__init__(bot, ctx)
self.cmd = cmd # Command object
@ -227,7 +226,7 @@ class CommandSession(BaseSession):
return self.args.get(key, default)
def _new_command_session(bot: CQHttp,
def _new_command_session(bot: NoneBot,
ctx: Dict[str, Any]) -> Optional[CommandSession]:
"""
Create a new session for a command.
@ -236,7 +235,7 @@ def _new_command_session(bot: CQHttp,
and if succeeded, it then create a session for the command and return.
If the message is not a valid command, None will be returned.
:param bot: CQHttp instance
:param bot: NoneBot instance
:param ctx: message context
:return: CommandSession object or None
"""
@ -299,13 +298,13 @@ def _new_command_session(bot: CQHttp,
return CommandSession(bot, ctx, cmd, current_arg=''.join(cmd_remained))
async def handle_command(bot: CQHttp, ctx: Dict[str, Any]) -> bool:
async def handle_command(bot: NoneBot, ctx: Dict[str, Any]) -> bool:
"""
Handle a message as a command.
This function is typically called by "handle_message".
:param bot: CQHttp instance
:param bot: NoneBot instance
:param ctx: message context
:return: the message is handled as a command
"""
@ -329,7 +328,7 @@ async def handle_command(bot: CQHttp, ctx: Dict[str, Any]) -> bool:
return await _real_run_command(session, ctx_id, check_perm=check_perm)
async def call_command(bot: CQHttp, ctx: Dict[str, Any],
async def call_command(bot: NoneBot, ctx: Dict[str, Any],
name: Union[str, Tuple[str]],
args: Dict[str, Any]) -> bool:
"""
@ -342,7 +341,7 @@ async def call_command(bot: CQHttp, ctx: Dict[str, Any],
will be overridden, even if the command being called here does
not need further interaction (a.k.a asking the user for more info).
:param bot: CQHttp instance
:param bot: NoneBot instance
:param ctx: message context
:param name: command name
:param args: command args

View File

@ -1,8 +1,8 @@
from typing import Dict, Any, Union, List, Sequence, Callable
from aiocqhttp import CQHttp, Error as CQHttpError
from aiocqhttp import Error as CQHttpError
from . import expression
from . import NoneBot, expression
def context_id(ctx: Dict[str, Any]) -> str:
@ -19,7 +19,7 @@ def context_id(ctx: Dict[str, Any]) -> str:
return src
async def send(bot: CQHttp, ctx: Dict[str, Any],
async def send(bot: NoneBot, ctx: Dict[str, Any],
message: Union[str, Dict[str, Any], List[Dict[str, Any]]],
*, ignore_failure: bool = True) -> None:
"""
@ -43,7 +43,7 @@ async def send(bot: CQHttp, ctx: Dict[str, Any],
raise
async def send_expr(bot: CQHttp, ctx: Dict[str, Any],
async def send_expr(bot: NoneBot, ctx: Dict[str, Any],
expr: Union[str, Sequence[str], Callable],
**kwargs):
"""

View File

@ -1,14 +1,14 @@
from typing import Dict, Any
from aiocqhttp import CQHttp
from aiocqhttp.message import MessageSegment
from . import NoneBot
from .command import handle_command
from .log import logger
from .natural_language import handle_natural_language
async def handle_message(bot: CQHttp, ctx: Dict[str, Any]) -> None:
async def handle_message(bot: NoneBot, ctx: Dict[str, Any]) -> None:
if ctx['message_type'] != 'private':
# group or discuss
ctx['to_me'] = False

View File

@ -3,10 +3,9 @@ import re
from collections import namedtuple
from typing import Dict, Any, Iterable, Optional, Callable, Union
from aiocqhttp import CQHttp
from aiocqhttp.message import Message
from . import permission as perm
from . import NoneBot, permission as perm
from .command import call_command
from .log import logger
from .session import BaseSession
@ -53,7 +52,7 @@ def on_natural_language(keywords: Union[Optional[Iterable], Callable] = None,
class NLPSession(BaseSession):
__slots__ = ('msg', 'msg_text', 'msg_images')
def __init__(self, bot: CQHttp, ctx: Dict[str, Any], msg: str):
def __init__(self, bot: NoneBot, ctx: Dict[str, Any], msg: str):
super().__init__(bot, ctx)
self.msg = msg
tmp_msg = Message(msg)
@ -69,13 +68,13 @@ NLPResult = namedtuple('NLPResult', (
))
async def handle_natural_language(bot: CQHttp, ctx: Dict[str, Any]) -> bool:
async def handle_natural_language(bot: NoneBot, ctx: Dict[str, Any]) -> bool:
"""
Handle a message as natural language.
This function is typically called by "handle_message".
:param bot: CQHttp instance
:param bot: NoneBot instance
:param ctx: message context
:return: the message is handled as natural language
"""

View File

@ -1,8 +1,9 @@
from typing import Dict, Any, Optional, Callable, Union
from aiocqhttp import CQHttp, Error as CQHttpError
from aiocqhttp import Error as CQHttpError
from aiocqhttp.bus import EventBus
from . import NoneBot
from .log import logger
from .session import BaseSession
@ -34,14 +35,14 @@ on_request = _make_event_deco('request')
class NoticeSession(BaseSession):
__slots__ = ()
def __init__(self, bot: CQHttp, ctx: Dict[str, Any]):
def __init__(self, bot: NoneBot, ctx: Dict[str, Any]):
super().__init__(bot, ctx)
class RequestSession(BaseSession):
__slots__ = ()
def __init__(self, bot: CQHttp, ctx: Dict[str, Any]):
def __init__(self, bot: NoneBot, ctx: Dict[str, Any]):
super().__init__(bot, ctx)
async def approve(self, remark: str = ''):
@ -67,7 +68,7 @@ class RequestSession(BaseSession):
pass
async def handle_notice_or_request(bot: CQHttp, ctx: Dict[str, Any]) -> None:
async def handle_notice_or_request(bot: NoneBot, ctx: Dict[str, Any]) -> None:
post_type = ctx['post_type'] # "notice" or "request"
detail_type = ctx[f'{post_type}_type']
event = f'{post_type}.{detail_type}'

View File

@ -2,7 +2,9 @@ from collections import namedtuple
from typing import Dict, Any
from aiocache import cached
from aiocqhttp import CQHttp, Error as CQHttpError
from aiocqhttp import Error as CQHttpError
from . import NoneBot
PRIVATE_FRIEND = 0x0001
PRIVATE_GROUP = 0x0002
@ -42,12 +44,12 @@ _min_context_fields = (
_MinContext = namedtuple('MinContext', _min_context_fields)
async def check_permission(bot: CQHttp, ctx: Dict[str, Any],
async def check_permission(bot: NoneBot, ctx: Dict[str, Any],
permission_required: int) -> bool:
"""
Check if the context has the permission required.
:param bot: CQHttp instance
:param bot: NoneBot instance
:param ctx: message context
:param permission_required: permission required
:return: the context has the permission
@ -63,7 +65,7 @@ async def check_permission(bot: CQHttp, ctx: Dict[str, Any],
@cached(ttl=2 * 60) # cache the result for 2 minute
async def _check(bot: CQHttp, min_ctx: _MinContext,
async def _check(bot: NoneBot, min_ctx: _MinContext,
permission_required: int) -> bool:
permission = 0
if min_ctx.user_id in bot.config.SUPERUSERS:

View File

@ -1,14 +1,13 @@
from typing import Union, Callable, Dict, Any, List, Sequence
from aiocqhttp import CQHttp
from . import NoneBot
from .helpers import send, send_expr
class BaseSession:
__slots__ = ('bot', 'ctx')
def __init__(self, bot: CQHttp, ctx: Dict[str, Any]):
def __init__(self, bot: NoneBot, ctx: Dict[str, Any]):
self.bot = bot
self.ctx = ctx