コード例 #1
0
ファイル: handler.py プロジェクト: Zhao-FlorenCE/CSC_Code
async def get_result(bot: Bot, event: Event, state: T_State):
    at = MessageSegment.at(event.get_user_id())
    if not state.get("content"):
        result = await get_help()
    elif str(state.get("content")).lower() == "list":
        plugin_set = nonebot.plugin.get_loaded_plugins()
        plugin_names = []
        for plugin in plugin_set:
            try:
                name = f'{plugin.name} | ' \
                    f'{plugin.module.__getattribute__("__help_plugin_name__")}'
            except:
                name = f'{plugin.name}'
            try:
                version = plugin.module.__getattribute__("__help_version__")
            except:
                version = ""
            plugin_names.append(f'{name} {version}')
        plugin_names.sort()
        newline_char = '\n'
        result = f'已加载插件:\n{newline_char.join(plugin_names)}'
    else:
        try:
            plugin = nonebot.plugin.get_plugin(state.get("content"))
        except AttributeError:
            plugin = None
        try:
            result = plugin.module.__getattribute__("__usage__")
        except:
            try:
                result = plugin.module.__doc__
            except AttributeError:
                result = f'{state.get("content")}插件不存在或未加载'
    await helper.finish(Message().append(at).append(
        MessageSegment.text(result)))
コード例 #2
0
ファイル: handler.py プロジェクト: XZhouQD/MirageBot
async def get_result(bot: Bot, event: Event, state: T_State):
    if state.get("content") in ('help', 'h'):
        at_user = MessageSegment.at(event.get_user_id())
        result = await get_help()
    else:
        at_user = MessageSegment.at(event.get_user_id())
        roll_result = await roll_dice(state.get("content"))
        result = MessageSegment.text(roll_result)
    await dice.finish(Message().append(at_user).append(result))
コード例 #3
0
ファイル: __init__.py プロジェクト: he0119/CoolQBot
async def add_sub_process(event: GroupMessageEvent, state: T_State):
    config = Config()
    config.add_subscribe(
        state.get("_user_id") or event.group_id,
        user_type="group",
        target=state["id"],
        target_name=state["name"],
        target_type=state["platform"],
        cats=state.get("cats", []),
        tags=state.get("tags", []),
    )

    await add_sub_cmd.finish("添加 {} 成功".format(state["name"]))
コード例 #4
0
 async def add_sub_process(event: Event, state: T_State):
     config = Config()
     user = state.get("target_user_info")
     assert isinstance(user, User)
     config.add_subscribe(
         # state.get("_user_id") or event.group_id,
         # user_type="group",
         user=user.user,
         user_type=user.user_type,
         target=state["id"],
         target_name=state["name"],
         target_type=state["platform"],
         cats=state.get("cats", []),
         tags=state.get("tags", []),
     )
     await add_sub.finish("添加 {} 成功".format(state["name"]))
コード例 #5
0
ファイル: TeamManager.py プロジェクト: LiXDL/MoyuBot
async def search_boss_first_receive(bot: cqhttp.Bot,
                                    event: cqhttp.GroupMessageEvent,
                                    state: typing.T_State):
    raw_message = event.get_message()
    arg_list, prior_id = None, None

    if len(raw_message) != 0:
        for segment in raw_message:
            if segment['type'] == 'at':
                #   checking for @message and extract qq_id from it as member_id
                prior_id = segment['data']['qq']
            else:
                arg_list = list(
                    map(
                        lambda x: str(x).strip(),
                        str(segment['data']['text']).strip().split(
                            plugin_config.separator)))

                if len(arg_list) < 1 or len(arg_list) > 2:
                    await add_team.finish(InteractionMessage.INVALID_ARG)
                elif len(arg_list) == 2:
                    state['team_id'] = arg_list[1]

        state['member_id'] = arg_list[0]

    state['member_id'] = prior_id if (prior_id is not None) else (state.get(
        'member_id', event.user_id))
コード例 #6
0
ファイル: matcher.py プロジェクト: SK-415/nonebot2
 async def _key_parser(bot: "Bot", event: "Event", state: T_State):
     if key in state and state.get("_skip_key"):
         del state["_skip_key"]
         return
     parser = args_parser or cls._default_parser
     if parser:
         # parser = cast(T_ArgsParser["Bot", "Event"], parser)
         await parser(bot, event, state)
     else:
         state[state["_current_key"]] = str(event.get_message())
コード例 #7
0
ファイル: RevueRecordManager.py プロジェクト: LiXDL/MoyuBot
async def add_record_first_receive(bot: cqhttp.Bot,
                                   event: cqhttp.GroupMessageEvent,
                                   state: typing.T_State):
    raw_args = str(event.get_message()).strip()
    arg_list = list(map(str.strip, raw_args.split(plugin_config.separator)))

    if len(arg_list) < 4 or len(arg_list) > 7:
        #   Not enough arguments have been provided
        await add_record.finish(InteractionMessage.INVALID_ARG_NUMBER)
    elif len(arg_list) > 4:
        #   turn, time, member_id might be provided
        for arg in arg_list[4:]:
            arg_check = _single_checker(arg)
            state[arg_check[0]] = arg_check[1]

    state['base_info'] = arg_list[0:4]
    state['turn'] = state.get('turn', plugin_config.default_revue_turn)
    state['time'] = state.get('time', int(time.time()))
    state['member_id'] = state.get('member_id', event.user_id)
コード例 #8
0
ファイル: TeamManager.py プロジェクト: LiXDL/MoyuBot
async def search_boss_handler(bot: cqhttp.Bot, event: cqhttp.GroupMessageEvent,
                              state: typing.T_State):
    if state.get('team_id') is None:
        #   search for all teams belonging to a member
        search_result = await ds.tc.search_member(state.get('member_id'))
    else:
        #   search for given member_id and team_id
        search_result = await ds.tc.search_team(state.get('member_id'),
                                                state.get('team_id'))

    if search_result['error'] is not None:
        if bot.config.debug:
            await bot.send_private_msg(user_id=plugin_config.AUTHOR,
                                       message=search_result['func_info'])
            await bot.send_private_msg(user_id=plugin_config.AUTHOR,
                                       message=search_result['error'])
        await search_team.finish(InteractionMessage.ERROR_MESSAGE)
    else:
        teams = search_result['response']['result']
        if not teams:
            await search_team.finish(InteractionMessage.RECORD_LIST_EMPTY)

        if type(teams) is dict:
            await search_team.finish(
                message=InteractionMessage.RECORD_FIND_SUCCESS.format(
                    state.get('member_id')) + '\n' +
                InteractionMessage.RECORD_LIST_SUCCESS + '\n' +
                _info_format(teams))
        else:
            team_records = '\n'.join(map(_info_format, teams))
            await search_team.finish(
                message=InteractionMessage.RECORD_FIND_SUCCESS.format(
                    state.get('member_id')) + '\n' +
                InteractionMessage.RECORD_LIST_SUCCESS + '\n' + team_records)
コード例 #9
0
async def sub_add(bot: Bot, event: GroupMessageEvent, state: T_State) -> Result:
    group_id = event.group_id
    group = DBGroup(group_id=group_id)
    uid = state['uid']
    sub = DBSubscription(sub_type=2, sub_id=uid)
    _res = sub.add(up_name=state.get('up_name'), live_info='动态')
    if not _res.success():
        return _res
    _res = group.subscription_add(sub=sub)
    if not _res.success():
        return _res
    result = Result(error=False, info='Success', result=0)
    return result
コード例 #10
0
async def add_record_first_receive(bot: cqhttp.Bot,
                                   event: cqhttp.GroupMessageEvent,
                                   state: typing.T_State):
    raw_message = event.get_message()

    #   received arguments, parsing
    arg_list, prior_id = None, None
    for segment in raw_message:
        if segment['type'] == 'at':
            #   checking for @message and extract qq_id from it as member_id
            prior_id = segment['data']['qq']
        else:
            #   standard input arguments
            arg_list = list(
                map(
                    lambda x: str(x).strip(),
                    str(segment['data']['text']).strip().split(
                        plugin_config.separator)))

            if len(arg_list) < 4 or len(arg_list) > 7:
                await add_record.finish(InteractionMessage.INVALID_ARG)
            elif len(arg_list) > 4:
                #   turn, time, member_id might be provided
                for arg in arg_list:
                    arg_check = _single_checker(arg)
                    state[arg_check[0]] = arg_check[1]

    #   No arguments received
    if len(raw_message) == 0 or arg_list is None:
        await add_record.reject(prompt=InteractionMessage.REQUEST_ARG)

    #   all arguments should have been processed except the 4 basic ones
    #   base_info[0:4] should be corresponds to sequence, boss_id, team, damage
    state['base_info'] = arg_list[0:4]
    state['turn'] = state.get('turn', plugin_config.default_revue_turn)
    state['date_time'] = state.get('date_time', int(time.time()))
    state['member_id'] = prior_id if (prior_id is not None) else (state.get(
        'member_id', event.user_id))
コード例 #11
0
ファイル: __init__.py プロジェクト: MeetWq/mybot
async def _(
        bot: Bot,
        event: GroupMessageEvent,
        state: T_State = State(),
        reply: str = ArgPlainText(),
):
    topic: dict = state.get("topic", {})
    page: int = state.get("page", 1)
    reply_num = topic["replyCount"] + 1

    if reply == "结束":
        await show.finish("会话已结束")
    elif reply == "+":
        if reply_num - page * 10 <= 0:
            await show.reject("当前已是最后一页")
        page += 1
    elif reply == "-":
        if page == 1:
            await show.reject("当前已是第一页")
        page -= 1
    elif reply.isdigit():
        if not (1 <= int(reply) <= math.ceil(reply_num / 10)):
            await show.reject("请输入正确的页码")
        page = int(reply)
    else:
        await show.reject()

    try:
        posts = await print_posts(topic, page)
    except:
        logger.warning(traceback.format_exc())
        await show.finish("出错了,请稍后再试")

    state["page"] = page
    msgs = [await str_to_message(post) for post in posts]
    await send_forward_msg(bot, event, msgs)
    await show.reject()
コード例 #12
0
async def _parse_group_idx(state: T_State, event_msg: str = EventPlainText()):
    if not isinstance(state["group_idx"], Message):
        return
    group_number_idx: Optional[dict[int, int]] = state.get("group_number_idx")
    assert group_number_idx
    try:
        assert event_msg != "取消", "userAbort"
        idx = int(event_msg)
        assert idx in group_number_idx.keys(), "idxNotInList"
        state["group_idx"] = idx
    except AssertionError as AE:
        errType = AE.args[0]
        if errType == "userAbort":
            await group_manage_matcher.finish("已取消")
        elif errType == "idxNotInList":
            await group_manage_matcher.reject("请输入正确序号")
コード例 #13
0
ファイル: __init__.py プロジェクト: hailong-z/nonebot2_miya
async def sub_add(bot: Bot, event: GroupMessageEvent,
                  state: T_State) -> Result:
    group_id = event.group_id
    group = DBGroup(group_id=group_id)
    room_id = state['room_id']
    sub = DBSubscription(sub_type=1, sub_id=room_id)
    _res = sub.add(up_name=state.get('up_name'), live_info='直播间')
    if not _res.success():
        return _res
    _res = group.subscription_add(sub=sub)
    if not _res.success():
        return _res
    # 添加直播间时需要刷新全局监控列表
    # 执行一次初始化
    await init_live_info()
    result = Result(error=False, info='Success', result=0)
    return result
コード例 #14
0
ファイル: __init__.py プロジェクト: MeetWq/mybot
async def _(
        bot: Bot,
        event: GroupMessageEvent,
        state: T_State = State(),
        confirm: str = ArgPlainText(),
):
    board_name: str = state.get("board_name", "")
    if confirm not in ["y", "Y", "yes", "Yes", "是"]:
        await cc98.finish()
    try:
        topics = await get_topics(board_name)
        msgs = await print_topics(topics)
    except:
        logger.warning(traceback.format_exc())
        await cc98.finish("出错了,请稍后再试")

    await send_forward_msg(bot, event, msgs)
コード例 #15
0
ファイル: __init__.py プロジェクト: he0119/CoolQBot
async def _(event: GroupMessageEvent, state: T_State):
    config: Config = Config()
    sub_list = config.list_subscribe(
        state.get("_user_id") or event.group_id, "group")
    res = ["订阅的帐号为:"]
    for sub in sub_list:
        temp = "{} {} {}".format(sub["target_type"], sub["target_name"],
                                 sub["target"])
        platform = platform_manager[sub["target_type"]]
        if platform.categories:
            temp += " [{}]".format(", ".join(
                map(lambda x: platform.categories[x], sub["cats"])))
        if platform.enable_tag:
            temp += " {}".format(", ".join(sub["tags"]))
        res.append(temp)
    if len(res) == 1:
        res = "当前无订阅"
    else:
        res = "\n".join(res)
    await query_sub_cmd.finish(Message(await parse_text(res)))
コード例 #16
0
ファイル: TeamManager.py プロジェクト: LiXDL/MoyuBot
async def add_team_first_receive(bot: cqhttp.Bot,
                                 event: cqhttp.GroupMessageEvent,
                                 state: typing.T_State):
    raw_message = event.get_message()
    arg_list, prior_id = None, None

    if len(raw_message) != 0:
        for segment in raw_message:
            if segment['type'] == 'at':
                #   checking for @message and extract qq_id from it as member_id
                prior_id = segment['data']['qq']
            else:
                arg_list = list(
                    map(
                        lambda x: str(x).strip(),
                        str(segment['data']['text']).strip().split(
                            plugin_config.separator)))

                if len(arg_list) < 1 or len(arg_list) > 2:
                    await add_team.finish(InteractionMessage.INVALID_ARG)
                elif len(arg_list) == 2:
                    state['member_id'] = arg_list[1]
    else:
        await add_team.reject(prompt=InteractionMessage.REQUEST_ARG)

    state['member_id'] = prior_id if (prior_id is not None) else (state.get(
        'member_id', event.user_id))
    state['team_id'] = int(arg_list[0])

    #   check if there is already a team belongs to the given member
    team_existence = await ds.tc.search_team(state['member_id'],
                                             state['team_id'])
    if team_existence['response']['result']:
        await add_team.finish(InteractionMessage.RECORD_ALREADT_EXIST)
    else:
        state['team_list'] = []
        state['us_list'] = []
        await add_team.pause(prompt=InteractionMessage.REPEATE_ADD_TEAM_CARD)
コード例 #17
0
 async def _check_user_info(state: T_State):
     if not state.get("target_user_info"):
         await matcher.finish(
             "No target_user_info set, this shouldn't happen, please issue")