Beispiel #1
0
def ctx_id2event(ctx_id: str):
    if ctx_id.startswith("/group/"):
        return Event(group_id=ctx_id.replace("/group/", "").split("/")[0])
    if ctx_id.startswith("/discuss/"):
        return Event(discuss_id=ctx_id.replace("/discuss/", "").split("/")[0])
    if ctx_id.startswith("/user/"):
        return Event(user_id=ctx_id.replace("/user/", "").split("/")[0])
    return Event()
Beispiel #2
0
 def test1(self):
     event = Event.from_payload(self.payload)
     bot = SearchBot()
     self.assertTrue(bot.match(event, event.message))
     result = call_async_func(bot.reply(event))
     print(result)
     self.assertTrue(len(result) > 20)
Beispiel #3
0
async def handle_message(bot: NoneBot, event: CQEvent) -> None:
    _log_message(event)

    assert isinstance(event.message, Message)
    if not event.message:
        event.message.append(MessageSegment.text(''))

    coros = []
    for preprocessor in _message_preprocessors:
        coros.append(preprocessor(bot, event))
    if coros:
        await asyncio.wait(coros)

    raw_to_me = event.get('to_me', False)
    _check_at_me(bot, event)
    _check_calling_me_nickname(bot, event)
    event['to_me'] = raw_to_me or event['to_me']

    while True:
        try:
            handled = await handle_command(bot, event)
            break
        except SwitchException as e:
            # we are sure that there is no session existing now
            event['message'] = e.new_message
            event['to_me'] = True
    if handled:
        logger.info(f'Message {event.message_id} is handled as a command')
        return

    handled = await handle_natural_language(bot, event)
    if handled:
        logger.info(f'Message {event.message_id} is handled '
                    f'as natural language')
        return
Beispiel #4
0
def qq2event(qq: int):
    return Event(
        user_id=qq,
        message_type="private",
        post_type="message",
        sub_type="friend",
        to_me=True,
    )
async def _():
    for tsk in _tasks['data']:
        #构造Event对象event
        event = Event(tsk['event'])
        event.message = Message(tsk['event']['message'])  #构造消息段对象
        hour = tsk['hour']
        minute = tsk['minute']
        id = tsk['id']
        try:
            job = add_cron_job(task,
                               id=id,
                               hour=hour,
                               minute=minute,
                               args=[event])
            global _running_jobs
            _running_jobs.append(job)
        except ValueError as ex:
            sv.logger.error(f'添加定时任务时出现异常{ex}')
Beispiel #6
0
async def send(bot: NoneBot,
               event: CQEvent,
               message: Message_T,
               *,
               ensure_private: bool = False,
               ignore_failure: bool = True,
               **kwargs) -> Any:
    """Send a message ignoring failure by default."""
    try:
        if ensure_private:
            event = event.copy()
            event['message_type'] = 'private'
        return await bot.send(event, message, **kwargs)
    except CQHttpError:
        if not ignore_failure:
            raise
        return None
Beispiel #7
0
async def handle_message(bot: NoneBot, event: CQEvent) -> None:
    """INTERNAL API"""
    _log_message(event)

    assert isinstance(event.message, Message)
    if not event.message:
        event.message.append(MessageSegment.text(''))  # type: ignore

    raw_to_me = event.get('to_me', False)
    _check_at_me(bot, event)
    _check_calling_me_nickname(bot, event)
    event['to_me'] = raw_to_me or event['to_me']

    coros = []
    plugin_manager = PluginManager()
    for preprocessor in MessagePreprocessorManager.preprocessors:
        coros.append(preprocessor.func(bot, event, plugin_manager))
    if coros:
        try:
            await asyncio.gather(*coros)
        except CanceledException as e:
            logger.info(
                f'Message {event["message_id"]} is ignored: {e.reason}')
            return

    while True:
        try:
            handled = await handle_command(bot, event,
                                           plugin_manager.cmd_manager)
            break
        except SwitchException as e:
            # we are sure that there is no session existing now
            event['message'] = e.new_message
            event['to_me'] = True
    if handled:
        logger.info(f'Message {event.message_id} is handled as a command')
        return

    handled = await handle_natural_language(bot, event,
                                            plugin_manager.nlp_manager)
    if handled:
        logger.info(f'Message {event.message_id} is handled '
                    f'as natural language')
        return

    logger.debug(f'Message {event.message_id} was not handled')
Beispiel #8
0
async def send(bot: NoneBot,
               event: CQEvent,
               message: Message_T,
               *,
               ensure_private: bool = False,
               ignore_failure: bool = True,
               **kwargs) -> Any:
    """
    发送消息到指定事件的上下文中。

    参数:
        bot: NoneBot 对象
        event: 事件对象
        message (nonebot.typing.Message_T): 要发送的消息内容
        ensure_private: 确保消息发送到私聊,对于群组和讨论组消息上下文,会私聊发送者
        ignore_failure: 发送失败时忽略 `CQHttpError` 异常
        kwargs: 其它传入 `CQHttp.send()` 的命名参数

    返回:
        Any {version}`1.1.0+`: 返回 CQHTTP 插件发送消息接口的调用返回值,具体见 aiocqhttp 的 [API 调用](https://aiocqhttp.nonebot.dev/#/what-happened#api-%E8%B0%83%E7%94%A8)

    异常:
        CQHttpError: 发送失败时抛出,实际由 [aiocqhttp] 抛出,等价于 `aiocqhttp.Error`

    用法:
        ```python
        await send(bot, event, 'hello')
        ```
    """
    try:
        if ensure_private:
            event = event.copy()
            event['message_type'] = 'private'
        return await bot.send(event, message, **kwargs)
    except CQHttpError:
        if not ignore_failure:
            raise
        return None
Beispiel #9
0
async def can_send_word(event: Event, message, kwargs):
    if silent_.is_silent():
        event.clear()
Beispiel #10
0
def replace_event_msg(event: Event, msg: str):
    new_event = Event.from_payload(event)
    new_event["message"] = Message(msg)
    new_event["raw_message"] = msg
    return new_event
Beispiel #11
0
def qq2event(qq: int):
    return Event(user_id=qq)
Beispiel #12
0
async def handle_message(bot: NoneBot, event: CQEvent) -> None:
    _log_message(event)

    assert isinstance(event.message, Message)
    if not event.message:
        event.message.append(MessageSegment.text(''))  # type: ignore

    # 检查是否是对我说话
    # 但不在这里终止,因为还可能是会话未结束。
    raw_to_me = event.get('to_me', False)
    _check_at_me(bot, event)
    _check_calling_me_nickname(bot, event)
    event['to_me'] = raw_to_me or event['to_me']

    plugin_manager = PluginManager()
    while True:
        try:
            handled = await handle_regexp(bot, event,
                                          plugin_manager.regexp_manager)
            break
        except SwitchException as e:
            event['message'] = e.new_message
            event['to_me'] = True

    if handled:
        logger.info(
            f'Message {event.message_id} is handled as a regular expression command.'
        )
        return

    # 过一遍预处理器(好像没用到过)
    coros = []
    for preprocessor in _message_preprocessors:
        coros.append(preprocessor(bot, event, plugin_manager))
    if coros:
        try:
            await asyncio.gather(*coros)
        except CanceledException:
            logger.info(f'Message {event["message_id"]} is ignored')
            return

    # 处理命令,如果中途被 Switch 则继续处理。
    # 此处命令还未被识别

    while True:
        try:
            handled = await handle_command(bot, event,
                                           plugin_manager.cmd_manager)
            break
        except SwitchException as e:
            # we are sure that there is no session existing now
            event['message'] = e.new_message
            event['to_me'] = True
    if handled:
        logger.info(f'Message {event.message_id} is handled as a command')
        return

    handled = await handle_natural_language(bot, event,
                                            plugin_manager.nlp_manager)
    if handled:
        logger.info(f'Message {event.message_id} is handled '
                    f'as natural language')
        return