mirror of
https://github.com/nonebot/nonebot2.git
synced 2025-01-31 23:51:28 +08:00
Create NoneBot class inheriting CQHttp
This commit is contained in:
parent
2a2a7a2ae3
commit
030a31e63f
@ -8,19 +8,24 @@ from typing import Any
|
|||||||
from aiocqhttp import CQHttp
|
from aiocqhttp import CQHttp
|
||||||
from aiocqhttp.message import Message
|
from aiocqhttp.message import Message
|
||||||
|
|
||||||
|
from . import default_config
|
||||||
from .log import logger
|
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:
|
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()
|
kwargs = {k.lower(): v for k, v in config_object.__dict__.items()
|
||||||
if k.isupper() and not k.startswith('_')}
|
if k.isupper() and not k.startswith('_')}
|
||||||
|
|
||||||
bot = CQHttp(message_class=Message, **kwargs)
|
bot = NoneBot(message_class=Message, **kwargs)
|
||||||
bot.config = config_object
|
bot.config = config_object
|
||||||
if bot.config.DEBUG:
|
if bot.config.DEBUG:
|
||||||
logger.setLevel(logging.DEBUG)
|
logger.setLevel(logging.DEBUG)
|
||||||
@ -28,6 +33,9 @@ def create_bot(config_object: Any = None) -> CQHttp:
|
|||||||
logger.setLevel(logging.INFO)
|
logger.setLevel(logging.INFO)
|
||||||
bot.asgi.debug = bot.config.DEBUG
|
bot.asgi.debug = bot.config.DEBUG
|
||||||
|
|
||||||
|
from .message import handle_message
|
||||||
|
from .notice_request import handle_notice_or_request
|
||||||
|
|
||||||
@bot.on_message
|
@bot.on_message
|
||||||
async def _(ctx):
|
async def _(ctx):
|
||||||
asyncio.ensure_future(handle_message(bot, ctx))
|
asyncio.ensure_future(handle_message(bot, ctx))
|
||||||
|
@ -5,10 +5,9 @@ from typing import (
|
|||||||
Tuple, Union, Callable, Iterable, Dict, Any, Optional, Sequence
|
Tuple, Union, Callable, Iterable, Dict, Any, Optional, Sequence
|
||||||
)
|
)
|
||||||
|
|
||||||
from aiocqhttp import CQHttp
|
|
||||||
from aiocqhttp.message import Message
|
from aiocqhttp.message import Message
|
||||||
|
|
||||||
from . import permission as perm
|
from . import NoneBot, permission as perm
|
||||||
from .expression import render
|
from .expression import render
|
||||||
from .helpers import context_id
|
from .helpers import context_id
|
||||||
from .session import BaseSession
|
from .session import BaseSession
|
||||||
@ -159,7 +158,7 @@ class CommandSession(BaseSession):
|
|||||||
__slots__ = ('cmd', 'current_key', 'current_arg', 'current_arg_text',
|
__slots__ = ('cmd', 'current_key', 'current_arg', 'current_arg_text',
|
||||||
'current_arg_images', 'args', 'last_interaction')
|
'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):
|
current_arg: str = '', args: Optional[Dict[str, Any]] = None):
|
||||||
super().__init__(bot, ctx)
|
super().__init__(bot, ctx)
|
||||||
self.cmd = cmd # Command object
|
self.cmd = cmd # Command object
|
||||||
@ -227,7 +226,7 @@ class CommandSession(BaseSession):
|
|||||||
return self.args.get(key, default)
|
return self.args.get(key, default)
|
||||||
|
|
||||||
|
|
||||||
def _new_command_session(bot: CQHttp,
|
def _new_command_session(bot: NoneBot,
|
||||||
ctx: Dict[str, Any]) -> Optional[CommandSession]:
|
ctx: Dict[str, Any]) -> Optional[CommandSession]:
|
||||||
"""
|
"""
|
||||||
Create a new session for a command.
|
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.
|
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.
|
If the message is not a valid command, None will be returned.
|
||||||
|
|
||||||
:param bot: CQHttp instance
|
:param bot: NoneBot instance
|
||||||
:param ctx: message context
|
:param ctx: message context
|
||||||
:return: CommandSession object or None
|
: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))
|
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.
|
Handle a message as a command.
|
||||||
|
|
||||||
This function is typically called by "handle_message".
|
This function is typically called by "handle_message".
|
||||||
|
|
||||||
:param bot: CQHttp instance
|
:param bot: NoneBot instance
|
||||||
:param ctx: message context
|
:param ctx: message context
|
||||||
:return: the message is handled as a command
|
: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)
|
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]],
|
name: Union[str, Tuple[str]],
|
||||||
args: Dict[str, Any]) -> bool:
|
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
|
will be overridden, even if the command being called here does
|
||||||
not need further interaction (a.k.a asking the user for more info).
|
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 ctx: message context
|
||||||
:param name: command name
|
:param name: command name
|
||||||
:param args: command args
|
:param args: command args
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
from typing import Dict, Any, Union, List, Sequence, Callable
|
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:
|
def context_id(ctx: Dict[str, Any]) -> str:
|
||||||
@ -19,7 +19,7 @@ def context_id(ctx: Dict[str, Any]) -> str:
|
|||||||
return src
|
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]]],
|
message: Union[str, Dict[str, Any], List[Dict[str, Any]]],
|
||||||
*, ignore_failure: bool = True) -> None:
|
*, ignore_failure: bool = True) -> None:
|
||||||
"""
|
"""
|
||||||
@ -43,7 +43,7 @@ async def send(bot: CQHttp, ctx: Dict[str, Any],
|
|||||||
raise
|
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],
|
expr: Union[str, Sequence[str], Callable],
|
||||||
**kwargs):
|
**kwargs):
|
||||||
"""
|
"""
|
||||||
|
@ -1,14 +1,14 @@
|
|||||||
from typing import Dict, Any
|
from typing import Dict, Any
|
||||||
|
|
||||||
from aiocqhttp import CQHttp
|
|
||||||
from aiocqhttp.message import MessageSegment
|
from aiocqhttp.message import MessageSegment
|
||||||
|
|
||||||
|
from . import NoneBot
|
||||||
from .command import handle_command
|
from .command import handle_command
|
||||||
from .log import logger
|
from .log import logger
|
||||||
from .natural_language import handle_natural_language
|
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':
|
if ctx['message_type'] != 'private':
|
||||||
# group or discuss
|
# group or discuss
|
||||||
ctx['to_me'] = False
|
ctx['to_me'] = False
|
||||||
|
@ -3,10 +3,9 @@ import re
|
|||||||
from collections import namedtuple
|
from collections import namedtuple
|
||||||
from typing import Dict, Any, Iterable, Optional, Callable, Union
|
from typing import Dict, Any, Iterable, Optional, Callable, Union
|
||||||
|
|
||||||
from aiocqhttp import CQHttp
|
|
||||||
from aiocqhttp.message import Message
|
from aiocqhttp.message import Message
|
||||||
|
|
||||||
from . import permission as perm
|
from . import NoneBot, permission as perm
|
||||||
from .command import call_command
|
from .command import call_command
|
||||||
from .log import logger
|
from .log import logger
|
||||||
from .session import BaseSession
|
from .session import BaseSession
|
||||||
@ -53,7 +52,7 @@ def on_natural_language(keywords: Union[Optional[Iterable], Callable] = None,
|
|||||||
class NLPSession(BaseSession):
|
class NLPSession(BaseSession):
|
||||||
__slots__ = ('msg', 'msg_text', 'msg_images')
|
__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)
|
super().__init__(bot, ctx)
|
||||||
self.msg = msg
|
self.msg = msg
|
||||||
tmp_msg = Message(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.
|
Handle a message as natural language.
|
||||||
|
|
||||||
This function is typically called by "handle_message".
|
This function is typically called by "handle_message".
|
||||||
|
|
||||||
:param bot: CQHttp instance
|
:param bot: NoneBot instance
|
||||||
:param ctx: message context
|
:param ctx: message context
|
||||||
:return: the message is handled as natural language
|
:return: the message is handled as natural language
|
||||||
"""
|
"""
|
||||||
|
@ -1,8 +1,9 @@
|
|||||||
from typing import Dict, Any, Optional, Callable, Union
|
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 aiocqhttp.bus import EventBus
|
||||||
|
|
||||||
|
from . import NoneBot
|
||||||
from .log import logger
|
from .log import logger
|
||||||
from .session import BaseSession
|
from .session import BaseSession
|
||||||
|
|
||||||
@ -34,14 +35,14 @@ on_request = _make_event_deco('request')
|
|||||||
class NoticeSession(BaseSession):
|
class NoticeSession(BaseSession):
|
||||||
__slots__ = ()
|
__slots__ = ()
|
||||||
|
|
||||||
def __init__(self, bot: CQHttp, ctx: Dict[str, Any]):
|
def __init__(self, bot: NoneBot, ctx: Dict[str, Any]):
|
||||||
super().__init__(bot, ctx)
|
super().__init__(bot, ctx)
|
||||||
|
|
||||||
|
|
||||||
class RequestSession(BaseSession):
|
class RequestSession(BaseSession):
|
||||||
__slots__ = ()
|
__slots__ = ()
|
||||||
|
|
||||||
def __init__(self, bot: CQHttp, ctx: Dict[str, Any]):
|
def __init__(self, bot: NoneBot, ctx: Dict[str, Any]):
|
||||||
super().__init__(bot, ctx)
|
super().__init__(bot, ctx)
|
||||||
|
|
||||||
async def approve(self, remark: str = ''):
|
async def approve(self, remark: str = ''):
|
||||||
@ -67,7 +68,7 @@ class RequestSession(BaseSession):
|
|||||||
pass
|
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"
|
post_type = ctx['post_type'] # "notice" or "request"
|
||||||
detail_type = ctx[f'{post_type}_type']
|
detail_type = ctx[f'{post_type}_type']
|
||||||
event = f'{post_type}.{detail_type}'
|
event = f'{post_type}.{detail_type}'
|
||||||
|
@ -2,7 +2,9 @@ from collections import namedtuple
|
|||||||
from typing import Dict, Any
|
from typing import Dict, Any
|
||||||
|
|
||||||
from aiocache import cached
|
from aiocache import cached
|
||||||
from aiocqhttp import CQHttp, Error as CQHttpError
|
from aiocqhttp import Error as CQHttpError
|
||||||
|
|
||||||
|
from . import NoneBot
|
||||||
|
|
||||||
PRIVATE_FRIEND = 0x0001
|
PRIVATE_FRIEND = 0x0001
|
||||||
PRIVATE_GROUP = 0x0002
|
PRIVATE_GROUP = 0x0002
|
||||||
@ -42,12 +44,12 @@ _min_context_fields = (
|
|||||||
_MinContext = namedtuple('MinContext', _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:
|
permission_required: int) -> bool:
|
||||||
"""
|
"""
|
||||||
Check if the context has the permission required.
|
Check if the context has the permission required.
|
||||||
|
|
||||||
:param bot: CQHttp instance
|
:param bot: NoneBot instance
|
||||||
:param ctx: message context
|
:param ctx: message context
|
||||||
:param permission_required: permission required
|
:param permission_required: permission required
|
||||||
:return: the context has the permission
|
: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
|
@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_required: int) -> bool:
|
||||||
permission = 0
|
permission = 0
|
||||||
if min_ctx.user_id in bot.config.SUPERUSERS:
|
if min_ctx.user_id in bot.config.SUPERUSERS:
|
||||||
|
@ -1,14 +1,13 @@
|
|||||||
from typing import Union, Callable, Dict, Any, List, Sequence
|
from typing import Union, Callable, Dict, Any, List, Sequence
|
||||||
|
|
||||||
from aiocqhttp import CQHttp
|
from . import NoneBot
|
||||||
|
|
||||||
from .helpers import send, send_expr
|
from .helpers import send, send_expr
|
||||||
|
|
||||||
|
|
||||||
class BaseSession:
|
class BaseSession:
|
||||||
__slots__ = ('bot', 'ctx')
|
__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.bot = bot
|
||||||
self.ctx = ctx
|
self.ctx = ctx
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user