Пример #1
0
async def add_my_skill(session: CommandSession):
    group_id = session.event.group_id
    session_type = session.event.detail_type
    if session_type == 'group':
        if not has_command_permissions(group_id):
            await session.send('本群组没有执行命令的权限呢QAQ')
            log.logger.info(f'{__name__}: 群组: {group_id} 没有命令权限, 已中止命令执行')
            return
    elif session_type == 'private':
        await session.send('本命令不支持在私聊中使用QAQ')
        log.logger.info(
            f'{__name__}: 用户: {session.event.user_id} 在{session_type}中使用了命令, 已中止命令执行'
        )
        return
    else:
        log.logger.info(
            f'{__name__}: 用户: {session.event.user_id} 在{session_type}环境中使用了命令, 已中止命令执行'
        )
        return
    __user_qq = session.event.user_id
    __skill_list = await query_skill_list()
    skill_name = session.get('skill_name',
                             prompt='请输入你想设置的技能名称: ',
                             arg_filters=[
                                 controllers.handle_cancellation(session),
                                 validators.not_empty('输入不能为空')
                             ])
    if skill_name not in __skill_list:
        session.finish('没有这个技能哦, 请重新设置~')
    skill_level = session.get('skill_level',
                              prompt='请输入你想设置的技能等级: \n可设置等级有"普通"、"熟练"、"专业"',
                              arg_filters=[
                                  controllers.handle_cancellation(session),
                                  validators.not_empty('输入不能为空'),
                                  validators.match_regex(r'^(普通|熟练|专业)$',
                                                         '没有这个技能等级, 请重新输入~',
                                                         fullmatch=True)
                              ])
    try:
        __result = await add_user_skill_in_db(user_qq=__user_qq,
                                              skill_name=skill_name,
                                              skill_level=skill_level)
        if __result:
            await session.send(f'为你新增了技能: 【{skill_name}/{skill_level}】')
            log.logger.info(
                f'{__name__}: 群组: {group_id}, 用户: {__user_qq} 成功新增了自己的技能')
        else:
            await session.send('添加失败, 发生了意外的错误QAQ')
            log.logger.info(
                f'{__name__}: 群组: {group_id}, 用户: {__user_qq} 新增技能失败, add_user_skill_in_db错误'
            )
    except Exception as e:
        log.logger.warning(
            f'{__name__}: 群组: {group_id}, 用户: {__user_qq} 试图使用命令add_my_skill时发生了错误: {e}'
        )
Пример #2
0
async def announce(session: CommandSession):
    __group_id = session.get('group_id', prompt='请输入你想通知的群号: ',
                             arg_filters=[controllers.handle_cancellation(session),
                                          validators.not_empty('输入不能为空'),
                                          validators.match_regex(r'^\d+$', '格式不对, 请重新输入~', fullmatch=True)])
    __group_id = int(__group_id)
    if __group_id == 0:
        __announce_text = session.get('announce_text', prompt='【全局公告】请输入你想发布的公告内容: ',
                                      arg_filters=[controllers.handle_cancellation(session),
                                                   validators.not_empty('输入不能为空')])
        for group_id in query_all_notice_groups():
            try:
                await session.bot.send_group_msg(group_id=group_id, message=__announce_text)
                log.logger.info(f'{__name__}: 已向群组: {__group_id} 发送通知')
            except Exception as e:
                log.logger.error(f'{__name__}: 向群组: {__group_id} 发送通知失败, error info: {e}')
                continue
        return
    elif __group_id == 1:
        __announce_text = session.get('announce_text', prompt='【命令组公告】请输入你想发布的公告内容: ',
                                      arg_filters=[controllers.handle_cancellation(session),
                                                   validators.not_empty('输入不能为空')])
        for group_id in query_all_command_groups():
            try:
                await session.bot.send_group_msg(group_id=group_id, message=__announce_text)
                log.logger.info(f'{__name__}: 已向群组: {__group_id} 发送通知')
            except Exception as e:
                log.logger.error(f'{__name__}: 向群组: {__group_id} 发送通知失败, error info: {e}')
                continue
        return
    elif __group_id == 9:
        __announce_text = session.get('announce_text', prompt='【管理组公告】请输入你想发布的公告内容: ',
                                      arg_filters=[controllers.handle_cancellation(session),
                                                   validators.not_empty('输入不能为空')])
        for group_id in query_all_admin_groups():
            try:
                await session.bot.send_group_msg(group_id=group_id, message=__announce_text)
                log.logger.info(f'{__name__}: 已向群组: {__group_id} 发送通知')
            except Exception as e:
                log.logger.error(f'{__name__}: 向群组: {__group_id} 发送通知失败, error info: {e}')
                continue
        return
    elif __group_id not in query_all_notice_groups():
        log.logger.info(f'{__name__}: 群组: {__group_id} 没有通知权限, 无法发送通知')
        await session.send('群组未配置通知权限!')
        return
    __announce_text = session.get('announce_text', prompt='请输入你想发布的公告内容: ',
                                  arg_filters=[controllers.handle_cancellation(session),
                                               validators.not_empty('输入不能为空')])
    try:
        await session.bot.send_group_msg(group_id=__group_id, message=__announce_text)
        log.logger.info(f'{__name__}: 已向群组: {__group_id} 发送通知')
    except Exception as e:
        log.logger.error(f'{__name__}: 向群组: {__group_id} 发送通知失败, error info: {e}')
Пример #3
0
async def add_skill(session: CommandSession):
    group_id = session.event.group_id
    session_type = session.event.detail_type
    if session_type == 'group':
        if not has_command_permissions(group_id):
            await session.send('本群组没有执行命令的权限呢QAQ')
            log.logger.info(f'{__name__}: 群组: {group_id} 没有命令权限, 已中止命令执行')
            return
    elif session_type == 'private':
        await session.send('本命令不支持在私聊中使用QAQ')
        log.logger.info(
            f'{__name__}: 用户: {session.event.user_id} 在{session_type}中使用了命令, 已中止命令执行'
        )
        return
    else:
        log.logger.info(
            f'{__name__}: 用户: {session.event.user_id} 在{session_type}环境中使用了命令, 已中止命令执行'
        )
        return
    # 从会话状态(session.state)中获取信息, 如果当前不存在, 则询问用户
    skill_name = session.get('skill_name',
                             prompt='即将向可用技能列表中添加技能, 开始新增技能向导~\n请输入技能名称: ',
                             arg_filters=[
                                 controllers.handle_cancellation(session),
                                 validators.not_empty('输入不能为空')
                             ])
    skill_description = session.get(
        'skill_description',
        prompt='请输入技能描述: ',
        arg_filters=[
            controllers.handle_cancellation(session),
            validators.not_empty('输入不能为空')
        ])
    try:
        __result = await add_skill_to_db(skill_name, skill_description)
        if __result:
            await session.send(
                f'已添加技能【{skill_name}】\n\n技能描述: \n{skill_description}')
            log.logger.info(
                f'{__name__}: 群组: {group_id}, 用户: {session.event.user_id} 添加技能成功'
            )
        else:
            await session.send('添加失败, 这个技能好像已经在技能列表中了~')
            log.logger.info(
                f'{__name__}: 群组: {group_id}, 用户: {session.event.user_id} 试图添加技能失败, 技能已在技能列表中'
            )
    except Exception as e:
        log.logger.warning(
            f'{__name__}: 群组: {group_id}, 用户: {session.event.user_id} 试图使用命令add_skill时发生了错误: {e}'
        )
Пример #4
0
async def trace_moe(session: CommandSession):

    url = session.get('url',
                      prompt='请提供番剧截图哦',
                      arg_filters=[
                          handle_cancellation(session), extract_image_urls,
                          not_empty('没收到图片哦,再发一次')
                      ])

    # 获取信息
    await session.send("开始搜索咯,稍等哦", at_sender=True)
    try:
        success, Fan_drama_info = await fan_search(url)
    except Exception:
        print(
            "/////////////////////////\n{}\n/////////////////////////".format(
                traceback.format_exc()))
        await session.send("搜索过程出现问题,错误报告已打印", at_sender=True)
    else:
        if success:
            # 向用户发送结果
            await session.finish(
                "\n相似度:{0[0]:.2%}\n原名:{0[1]}\n中文译名:{0[2]}\n中文别名:{0[3]}\n匹配画面出于第 {0[4]} 番\nAnilist站ID:{0[5]}\nMyanimelist站ID:{0[6]}\n首发时间:{0[7]}\n是否完结:{0[8]}"
                .format(Fan_drama_info),
                at_sender=True)
        else:
            await session.finish(Fan_drama_info, at_sender=True)
Пример #5
0
async def tex(session: CommandSession):
    if session.is_first_run:
        stripped_text = session.current_arg_text.strip()
        if stripped_text:
            session.state['tex_code'] = stripped_text

    tex_code = session.get('tex_code',
                           prompt='请发送你想要生成图片的 TeX 公式',
                           arg_filters=[
                               extractors.extract_text,
                               str.strip,
                               validators.not_empty('公式不能为空,请重新发送~'),
                           ])

    await session.send('正在生成,请稍后……')
    resp = await requests.post(LATEX2PNG_API_URL,
                               data={
                                   'latex': tex_code,
                                   'res': '600',
                                   'color': '000000'
                               })
    if not resp.ok:
        session.finish('服务暂时不可用,请稍后再试')

    html = await resp.text
    m = re.search(r'latex_[0-9a-z]+\.png', html)
    if not m:
        session.finish('生成公式图片失败,请稍后再试')

    session.finish(
        MessageSegment.image(LATEX2PNG_IMAGE_URL_FORMAT.format(m.group(0))) +
        '\n' + ZHIHU_TEX_SVG_URL_FORMAT.format(quote_plus(tex_code)))
Пример #6
0
async def guess_number(session: CommandSession):

    a = 0  # correct digit
    b = 0  # correct digit in wrong place

    print('target = ', session.state.get('target'))

    async def custom_validator(value):
        s = set(list(value))
        if len(value) != len(s):
            raise ValidateError('请不要輸入重复数字~')
        return value

    while not session.state['bingo'] and session.state['current_tries']:
        parm = 'guess' + str(session.state['current_tries'])
        guess = session.get(
            parm,
            prompt="请做出你的猜测",
            arg_filters=[
                extractors.extract_text,  # 提取纯文本部分
                str.strip,  # 去掉两边的空白
                validators.not_empty(),
                validators.match_regex(r'[0-9]{5}', '必须为5位数字'),
                custom_validator,
                # validators.ensure_true(lambda x: 9999 < int(x) < 100000, '必须猜测10000 ~ 99999中的数字')
            ],
            at_sender=True)

        guess_time = "这是第" + str(session.state['total_chances'] + 1 -
                                 session.state['current_tries']) + '次猜测:\n'
        for i in range(len(session.state.get('target'))):
            if guess[i] == session.state.get('target')[i]:
                a += 1
        for c in guess:
            if c in session.state.get('target'):
                b += 1
        b -= a
        # b = random.randint(1, 4)
        if a == session.state['length']:
            res = guess_time
            res += "恭喜你回答正确!\n"
            res += '你也可以百度搜索‘1A2B’获取移动端程式,祝您游戏愉快~'
            await session.send(res)
            session.state['bingo'] = True
            return
        res = guess_time
        res += "结果是:"
        res += str(a) + 'A ' + str(b) + 'B'
        await session.send(res)
        session.state['current_tries'] -= 1
        a = b = 0

        if session.state['current_tries'] == 0:
            res = guess_time
            res += "抱歉,挑战失败,正确答案是"
            res += session.state.get('target')
            res += '\n你也可以百度搜索‘1A2B’获取移动端程式,祝您游戏愉快~'
            await session.send(res)
    return
Пример #7
0
async def ship_map (session: CommandSession):
    key = session.get('key', prompt='请输入索引信息', arg_filters=[extract_text, not_empty('索引不能为空哦')])
    time_key = reto.r2n(key, [r"\d*?\-\d"])
    if time_key:
        info = await al_query_name(time_key)
    else:
        info = await al_query_coordinate(key.upper())

    await session.finish(info, at_sender=True)
Пример #8
0
async def search_pic(session: CommandSession):
    img_url: str = session.get('img_url',
                               prompt='请发送要搜索的图片',
                               arg_filters=[
                                   controllers.handle_cancellation(session),
                                   extractors.extract_image_urls,
                                   validators.not_empty('请发送图片')
                               ])[0]
    await session.send(await do_search(img_url), at_sender=True)
Пример #9
0
async def music(session: CommandSession):
    keyword = session.get('keyword',
                          prompt='想听什么歌呢亲亲',
                          arg_filters=[
                              extractors.extract_text, str.strip,
                              validators.not_empty('歌名不能为空呢亲亲,请重新发送')
                          ])
    song_id = await search_song_id_netease(keyword)
    if song_id is None:
        session.finish('没有找到这首歌呢亲亲')
    session.finish(MessageSegment.music('163', song_id))
Пример #10
0
async def subscribe(session: CommandSession):
    message = session.get(
        "message",
        prompt=f"你想订阅什么内容呢?(请输入序号,也可输入 `取消、不` 等语句取消):\n{get_subscribe_lst()}",
        arg_filters=[
            controllers.handle_cancellation(session),
            str.lstrip,
            validators.not_empty("请输入有效内容哦~"),
        ],
    )
    await handle_message(session.event, message)
Пример #11
0
async def heavycherry_boat_name_query(session: CommandSession):
    key = session.get('key',
                      prompt='需要查询的船名',
                      arg_filters=[extract_text,
                                   not_empty('输入不能为空哦')])

    info = await code_name(key)
    if info[0]:
        await session.finish("{}".format(info[1]), at_sender=True)
    else:
        await session.finish("数据库中查无此船", at_sender=True)
Пример #12
0
async def music(session: CommandSession):
    keyword = session.get('keyword', prompt='你想听什么歌呢?',
                          arg_filters=[
                              extractors.extract_text,
                              str.strip,
                              validators.not_empty('歌名不能为空哦,请重新发送')
                          ])
    song_id = await search_song_id(keyword)
    if song_id is None:
        session.finish('很抱歉,貌似没有找到这首歌呢')
    session.finish(MessageSegment.music('qq', song_id))
Пример #13
0
async def pixivision_sub(session: CommandSession):
    group_id = session.event.group_id
    session_type = session.event.detail_type
    if session_type == 'group':
        if not has_command_permissions(group_id):
            await session.send('本群组没有执行命令的权限呢QAQ')
            log.logger.info(f'{__name__}: 群组: {group_id} 没有命令权限, 已中止命令执行')
            return
    elif session_type == 'private':
        await session.send('本命令不支持在私聊中使用QAQ')
        log.logger.info(
            f'{__name__}: 用户: {session.event.user_id} 在{session_type}中使用了命令, 已中止命令执行'
        )
        return
    else:
        log.logger.info(
            f'{__name__}: 用户: {session.event.user_id} 在{session_type}环境中使用了命令, 已中止命令执行'
        )
        return
    mode = session.get('mode',
                       prompt='Pixivision\n【订阅】or【取消订阅】?',
                       arg_filters=[
                           controllers.handle_cancellation(session),
                           validators.not_empty('输入不能为空'),
                           validators.match_regex(r'^(订阅|取消订阅)$',
                                                  '指令不对哦, 请重新输入~',
                                                  fullmatch=True)
                       ])
    if mode == '订阅':
        __is_success = await add_pixivsion_sub_to_db(group_id=group_id)
        if not __is_success:
            await session.send('发生了意料之外的错误QAQ')
            log.logger.warning(
                f'{__name__}: 群组: {group_id}, 用户: {session.event.user_id} '
                f'试图订阅pixivision时发生了错误, 向数据库写入群组订阅失败.')
            return
        await session.send(f'已订阅Pixivision!')
        log.logger.info(
            f'{__name__}: 群组: {group_id}, 用户: {session.event.user_id} 订阅了pixivision.'
        )
    elif mode == '取消订阅':
        __is_success = await clean_group_pixivsion_sub_in_db(group_id=group_id)
        if not __is_success:
            await session.send('发生了意料之外的错误QAQ')
            log.logger.warning(
                f'{__name__}: 群组: {group_id}, 用户: {session.event.user_id} '
                f'试图取消订阅pixivision时发生了错误, 向数据库写入群组订阅失败.')
            return
        await session.send(f'已取消Pixivision订阅!')
        log.logger.info(
            f'{__name__}: 群组: {group_id}, 用户: {session.event.user_id} 取消了pixivision订阅.'
        )
Пример #14
0
async def this_is_wisdom(session: CommandSession):
    url = session.get('url',
                      prompt='请提供图片素材哦',
                      arg_filters=[
                          handle_cancellation(session), extract_image_urls,
                          not_empty('没收到图片哦,再发一次')
                      ])
    text = session.get('text',
                       prompt='请输入文案文本',
                       arg_filters=[
                           handle_cancellation(session), extract_text,
                           not_empty('没收到文案哦,再发一次')
                       ])
    # 获取信息
    await session.send("稍等哦,正在生成", at_sender=True)
    img = await getimg(url[0])
    if img:
        photo = await Wisdom(img, text)
        info = await up_img(photo)
    else:
        info = "图片下载失败"
    await session.finish(info, at_sender=True)
Пример #15
0
async def music(session: CommandSession):
    keyword = session.get(
        "keyword",
        prompt="歌名?",
        arg_filters=[
            extractors.extract_text,
            str.strip,
            validators.not_empty("歌名不能为空哦,请重新发送"),
        ],
    )
    song_id = await search_song_id(keyword)
    if song_id is None:
        session.finish("很抱歉,貌似没有找到这首歌")
    session.finish(MessageSegment.music("qq", song_id))
Пример #16
0
async def img_saucenao(session: CommandSession):
    url = session.get('url',
                      prompt='要识别的图片是哪张呢?',
                      arg_filters=[
                          handle_cancellation(session), extract_image_urls,
                          not_empty('没收到图片哦,再发一次')
                      ])
    # 获取信息
    success, info = await QRCode_decoding(url)
    if success:
        await session.finish("识别成功\n{}\n{}\n{}\n{}\n{}".format(*info),
                             at_sender=True)
    else:
        await session.finish(info, at_sender=True)
Пример #17
0
async def vision_porn(session: CommandSession):

    url = session.get(
        'url', prompt='要鉴定的图片是哪张呢?', 
        arg_filters=[
            handle_cancellation(session), 
            extract_image_urls, 
            not_empty('没收到图片哦,再发一次')
            ]
        )

    # 获取信息
    comment = await vision_img(url)
    await session.finish(comment, at_sender=True)
Пример #18
0
async def enter_phantom(session: CommandSession):

    url_A = session.get('url_A',
                        prompt='请提供第一张图片',
                        arg_filters=[
                            handle_cancellation(session), extract_image_urls,
                            not_empty('没收到图片哦,再发一次')
                        ])
    url_B = session.get('url_B',
                        prompt='请提供第二张图片',
                        arg_filters=[
                            handle_cancellation(session), extract_image_urls,
                            not_empty('没收到图片哦,再发一次')
                        ])
    await session.send("开始生成咯,稍等呢", at_sender=True)
    # 获取信息
    img_A, img_B = await getimg(url_A[0]), await getimg(url_B[0])
    if img_A and img_B:
        photo = await phantom(img_A, img_B)
        info = await up_img(photo)
    else:
        info = "图片下载失败"
    await session.finish(info, at_sender=True)
Пример #19
0
async def set_my_status(session: CommandSession):
    group_id = session.event.group_id
    session_type = session.event.detail_type
    if session_type == 'group':
        if not has_command_permissions(group_id):
            await session.send('本群组没有执行命令的权限呢QAQ')
            log.logger.info(f'{__name__}: 群组: {group_id} 没有命令权限, 已中止命令执行')
            return
    elif session_type == 'private':
        await session.send('本命令不支持在私聊中使用QAQ')
        log.logger.info(
            f'{__name__}: 用户: {session.event.user_id} 在{session_type}中使用了命令, 已中止命令执行'
        )
        return
    else:
        log.logger.info(
            f'{__name__}: 用户: {session.event.user_id} 在{session_type}环境中使用了命令, 已中止命令执行'
        )
        return
    __user_qq = session.event.user_id
    __status = session.get('status',
                           prompt='请输入你想设置的状态: \n可选"空闲"、"工作"',
                           arg_filters=[
                               controllers.handle_cancellation(session),
                               validators.not_empty('输入不能为空'),
                               validators.match_regex(r'^(空闲|工作)$',
                                                      '没有这个状态, 请重新输入~',
                                                      fullmatch=True)
                           ])
    if __status == '空闲':
        __status = 0
    elif __status == '工作':
        __status = 2
    try:
        __result = await set_my_status_in_db(user_qq=__user_qq,
                                             user_status=__status)
        if __result:
            await session.send(f'为你设置了状态: 【{session.state["status"]}】')
            log.logger.info(
                f'{__name__}: 群组: {group_id}, 用户: {__user_qq} 为自己更新了状态')
        else:
            await session.send(f'添加失败, 发生了意外的错误QAQ\n您可能不在用户列表中, 请联系管理员处理')
            log.logger.info(
                f'{__name__}: 群组: {group_id}, 用户: {__user_qq} 设置状态失败, 用户不在用户列表中'
            )
    except Exception as e:
        log.logger.warning(
            f'{__name__}: 群组: {group_id}, 用户: {__user_qq} 试图使用命令set_my_status时发生了错误: {e}'
        )
Пример #20
0
async def music(session: CommandSession):
    #args = session.current_arg_text.strip(' ',1)
    #if not args[0]:
    keyword = session.get('keyword',
                          prompt='你想听什么歌呢?',
                          arg_filters=[
                              extractors.extract_text, str.strip,
                              validators.not_empty('歌名不能为空哦,请重新发送')
                          ])
    #else:
    #    keyword = args[0]
    song_id = await search_song_id(keyword)
    if song_id is None:
        await session.send('没有找到这首歌呢', at_sender=True)
    else:
        await session.send(MessageSegment.music('qq', song_id), at_sender=True)
Пример #21
0
async def subscribe(session: CommandSession):
    message = session.get(
        "message",
        prompt=f"你想订阅什么内容呢?(请输入序号,也可输入 `取消、不` 等语句取消):\n{get_subscribe_str()}",
        arg_filters=[
            controllers.handle_cancellation(session),
            str.strip,
            validators.not_empty("请输入有效内容哦~"),
        ],
    )
    SubC = judge_sub(message)
    if not SubC:
        session.finish("输入序号有误!")

    _, msg = await SubC.add_sub(session.event, message)
    session.finish(msg)
Пример #22
0
async def gomoku(session: CommandSession):

    if not __enabled__:
        logger.warning("Gomoku plugin is disabled due to the failure of loading clib. See https://233a344a455.github.io/DeltaBot/setup.html#gomoku%E6%A8%A1%E5%9D%97-%E4%BA%94%E5%AD%90%E6%A3%8B-%E5%AE%89%E8%A3%85.")
        await session.send('插件未启用!')
        return

    await session.send("游戏开始!\n"
                       "玩家黑棋,机器人白棋\n"
                       "落子格式: 例如'e9'或'E9'\n"
                       "字母在前数字在后,不分大小写")

    g = GomokuGame(clib, context_id(session.ctx, use_hash=True))
    await session.send(MessageSegment.image(g.get_img()))
    await asyncio.sleep(0.5)
    while True:
        inp = await session.aget('input', force_update=True, prompt="请玩家落子",
                                 arg_filters=[
                                     str.strip,
                                     not_empty(message="输入不能为空!请重新输入"),
                                     handle_cancellation(session),
                                     match_regex(r'[a-oA-O](1[0-5]|[1-9])', fullmatch=True,
                                                 message="无效的输入!请重新输入\n落子格式: 例如'e9'或'E9',"
                                                         "字母在前数字在后,不分大小写\n【发送'取消'结束游戏】")])
        x, y = re.match(r'([a-oA-O])(1[0-5]|[1-9])', inp).groups()
        x, y = ALPHABET.index(x.upper()), int(y) - 1
        if not g.set_chess(x, y, USER):
            await session.send(f"位置'{inp}'已存在旗子,请重新输入")
            continue

        sco = -g.estimate()
        g.update_display()
        if sco > 1e6:
            await session.send("恭喜!你赢了" + MessageSegment.image(g.get_img()))
            return

        x, y = g.search()
        g.set_chess(x, y, BOT)
        g.display.draw_chess(x, y, BOT, high_lighted=True)
        sco = -g.estimate()
        if sco < -1e6:
            await session.send("你输啦 ~\(≧▽≦)/~" + MessageSegment.image(g.get_img()))
            return

        await session.send(f"估计分数: {sco}" + MessageSegment.image(g.get_img()))
        await asyncio.sleep(0.8)
Пример #23
0
async def construction_info(session: CommandSession):
    key = session.get('key',
                      prompt='请输入索引信息',
                      arg_filters=[extract_text,
                                   not_empty('索引不能为空哦')]).replace(':', ':')
    time_key = reto.r2n(key, [r"\d\:\d\d"])
    if time_key:
        info = await al_query_name(time_key)
    else:
        info = await al_query_time(key.upper())
    if len(info) >= 4500:
        info = info.split("\n")
        num = len(info) // 100
        await session.send("每页至多100条,共计{}页".format(num + 1), at_sender=True)
        for i in range(0, num):
            k = "\n".join(info[i * 100:(i + 1) * 100])
            await session.send(k)
        else:
            k = "\n".join(info[num * 100:])
            await session.finish(k)
    else:
        await session.finish(info, at_sender=True)
Пример #24
0
async def music(session: CommandSession):
    # 和炸毛互动
    if session.ctx['message_type'] == 'group' and \
            session.bot.config.GROUPS_TO_PLAY_WITH_ZHAMAO and \
            session.ctx['group_id'] in \
            session.bot.config.GROUPS_TO_PLAY_WITH_ZHAMAO and \
            not session.state.get('from_nlp'):
        ts = int(time.time() / 30)
        if ts % 2 == 1:  # 奇数炸毛发,nana附和
            await asyncio.sleep(2)
            session.finish('炸毛哥哥已经回复你啦~')

    keyword = session.get('keyword',
                          prompt='你想听什么歌呢?',
                          arg_filters=[
                              extractors.extract_text, str.strip,
                              validators.not_empty('歌名不能为空哦,请重新发送')
                          ])
    song_id = await search_song_id(keyword)
    if song_id is None:
        session.finish('没有找到这首歌呢')
    session.finish(MessageSegment.music('qq', song_id))
Пример #25
0
async def img_saucenao(session: CommandSession):

    url = session.get(
        'url', prompt='要搜索的图片是哪张呢?', 
        arg_filters=[
            handle_cancellation(session), 
            extract_image_urls, 
            not_empty('没收到图片哦,再发一次')
            ]
        )

    # 获取信息
    success, img_info = await get_img(url)
    if success:
        # 向用户发送结果
        await session.finish("\n相似度: {info}作品链接: {url[0]}\n画师主页: {url[1]}\n其他相关链接{url[2]}\n预览图: {thumbnail}".format(**img_info), at_sender=True)
    else:
        #info = await ascii2d_api(url)
        info = False
        img_info += """,转用ascii2d引擎搜索
ascii2d引擎搜索结果:
色彩搜索:
最相似来源结果:{0[0]}
作品名:{0[1]}
该作品链接:{0[2]}
作者名:{0[3]}
该作者链接:{0[4]}
预览图:{0[5]}
\n######\n
特征搜索:
最相似来源结果:{1[0]}
作品名:{1[1]}
该作品链接:{1[2]}
作者名:{1[3]}
该作者链接:{1[4]}
预览图:{1[5]}""".format(*info) if info else "\n所有引擎均未成功匹配"
        await session.finish(img_info, at_sender=True)
Пример #26
0
async def roll(session: CommandSession):
    group_id = session.event.group_id
    session_type = session.event.detail_type
    if session_type == 'group':
        if not has_command_permissions(group_id):
            await session.send('本群组没有执行命令的权限呢QAQ')
            log.logger.info(f'{__name__}: 群组: {group_id} 没有命令权限, 已中止命令执行')
            return
    elif session_type == 'private':
        await session.send('本命令不支持在私聊中使用QAQ')
        log.logger.info(
            f'{__name__}: 用户: {session.event.user_id} 在{session_type}中使用了命令, 已中止命令执行'
        )
        return
    else:
        log.logger.info(
            f'{__name__}: 用户: {session.event.user_id} 在{session_type}环境中使用了命令, 已中止命令执行'
        )
        return
    dice_num = session.get('dice_num',
                           prompt='请输入骰子个数: ',
                           arg_filters=[
                               controllers.handle_cancellation(session),
                               validators.not_empty('输入不能为空'),
                               validators.match_regex(r'^\d+$',
                                                      '只能是数字哦, 请重新输入~',
                                                      fullmatch=True)
                           ])
    dice_side = session.get('dice_side',
                            prompt='请输入骰子面数: ',
                            arg_filters=[
                                controllers.handle_cancellation(session),
                                validators.not_empty('输入不能为空'),
                                validators.match_regex(r'^\d+$',
                                                       '只能是数字哦, 请重新输入~',
                                                       fullmatch=True)
                            ])
    try:
        # 初始化随机种子
        random_seed = hash(
            str([
                session.event.user_id, session.event.group_id,
                datetime.datetime.now()
            ]))
        random.seed(random_seed)
        # 加入一个趣味的机制
        if random.randint(1, 101) == 100:
            await session.send(f'【彩蛋】骰子之神似乎不看好你, 你掷出的骰子全部消失了')
            return
        dice_num = int(dice_num)
        dice_side = int(dice_side)
        if dice_num < 0 or dice_side < 0:
            await session.send(f'【错误】你掷出了不存在的骰子, 只有上帝知道结果是多少')
            return
        dice_result = 0
        for i in range(dice_num):
            this_dice_result = random.choice(range(dice_side)) + 1
            dice_result += this_dice_result
        await session.send(f'你掷出了{dice_num}个{dice_side}面骰子, 点数为【{dice_result}】'
                           )
        log.logger.info(
            f'{__name__}: 群组: {group_id}, 用户: {session.event.user_id} '
            f'Roll了一次{dice_num}d{dice_side}, 结果为{dice_result}')
        return
    except Exception as e:
        await session.send(f'【错误】不知道发生了什么, 你掷出的骰子全部裂开了')
        log.logger.error(
            f'{__name__}: 群组: {group_id}, 用户: {session.event.user_id} Roll时发生了错误: {e}'
        )
        return
Пример #27
0
async def subscribe(session: CommandSession):
    message = session.get('message',
                          prompt='你想订阅什么内容呢?',
                          arg_filters=[validators.not_empty('请输入有效内容哦~')])

    hour = session.state.get('hour')
    minute = session.state.get('minute')
    if hour is None or minute is None:
        time = session.get('time',
                           prompt='你希望我在每天的什么时候给你推送呢?\n'
                           '(请使用24小时制,并使用阿拉伯数字表示小时和分钟)')
        m = re.match(r'(?P<hour>\d{1,2})[.::](?P<minute>\d{1,2})', time)
        if not m:
            m = re.match(
                r'(?P<hour>\d{1,2})\s*[点时]\s*'
                r'(?:(?P<minute>\d{1,2}|半|一刻)\s*[分]?)?', time)

        if m:
            hour = int(m.group('hour'))
            session.state['hour'] = hour
            try:
                minute = int(m.group('minute') or 0)
            except ValueError:
                if m.group('minute') == '半':
                    minute = 30
                elif m.group('minute') == '一刻':
                    minute = 15
            session.state['minute'] = minute
        else:
            del session.state['time']
            session.pause('时间格式不对啦,请重新发送')

    repeat = session.get('repeat',
                         prompt='是否希望我在推送消息的时候重复你上面发的消息内容呢?(请回答是或否)',
                         arg_filters=[
                             extractors.extract_text,
                             converters.simple_chinese_to_bool,
                             validators.ensure_true(lambda x: x is not None,
                                                    '我听不懂呀,请用是或否再回答一次呢')
                         ])

    escaped_message = message.replace('\\', '\\\\').replace('"', '\\"')
    if repeat:
        switch_arg = f'--repeat "{escaped_message}"'
    else:
        switch_arg = f'"{escaped_message}"'

    try:
        job = await scheduler.add_scheduled_commands(
            ScheduledCommand('switch', switch_arg),
            job_id=scheduler.make_job_id(
                PLUGIN_NAME, context_id(session.ctx),
                (random_string(1, string.ascii_lowercase) +
                 random_string(7, string.ascii_lowercase + string.digits))),
            ctx=session.ctx,
            trigger='cron',
            hour=hour,
            minute=minute,
            replace_existing=False)
        session.finish(f'订阅成功啦,下次推送时间 '
                       f'{job.next_run_time.strftime("%Y-%m-%d %H:%M")}')
    except scheduler.JobIdConflictError:
        session.finish('订阅失败,有可能只是运气不好哦,请稍后重试~')
Пример #28
0
async def set_group_permissions(session: CommandSession):
    try:
        __group_id = session.event.group_id
        __group_info = await session.bot.get_group_info(group_id=__group_id)
    except Exception as e:
        log.logger.warning(
            f'{__name__}: 用户{session.event.user_id} 使用命令set_group_permissions时发生错误: {e}, 该命令需要在群组中使用'
        )
        session.finish('请在群组内使用该命令!')
        return

    noitce_permissions = session.get(
        'noitce_permissions',
        prompt='是否配置【通知】权限?',
        arg_filters=[
            controllers.handle_cancellation(session),
            validators.not_empty('输入不能为空'),
            validators.match_regex(r'^(是|否)$', '请输入【是】或【否】', fullmatch=True)
        ])
    command_permissions = session.get(
        'command_permissions',
        prompt='是否配置【命令】权限?',
        arg_filters=[
            controllers.handle_cancellation(session),
            validators.not_empty('输入不能为空'),
            validators.match_regex(r'^(是|否)$', '请输入【是】或【否】', fullmatch=True)
        ])
    admin_permissions = session.get(
        'admin_permissions',
        prompt='是否配置【管理命令】权限?',
        arg_filters=[
            controllers.handle_cancellation(session),
            validators.not_empty('输入不能为空'),
            validators.match_regex(r'^(是|否)$', '请输入【是】或【否】', fullmatch=True)
        ])
    # 转换权限值
    if noitce_permissions == '是':
        noitce_permissions = 1
    elif noitce_permissions == '否':
        noitce_permissions = 0

    if command_permissions == '是':
        command_permissions = 1
    elif command_permissions == '否':
        command_permissions = 0

    if admin_permissions == '是':
        admin_permissions = 1
    elif admin_permissions == '否':
        admin_permissions = 0

    try:
        # 重新设置权限
        __is_success = \
            await set_group_permissions_to_db(group_id=__group_id, noitce_permissions=noitce_permissions,
                                              command_permissions=command_permissions,
                                              admin_permissions=admin_permissions)
        if not __is_success:
            await session.send('发生了意料之外的错误OvO')
            log.logger.warning(
                f'{__name__}: 用户{session.event.user_id} 使用set_group_permissions'
                f'更新群组: {session.event.group_id} 时发生错误, 数据库操作失败, 错误信息见日志.')
            return
        await session.send('已成功配置本群组权限~')
        log.logger.info(
            f'{__name__}: 用户{session.event.user_id} 使用set_group_permissions'
            f'配置了群组: {session.event.group_id} 的群组权限')
    except Exception as e:
        log.logger.warning(
            f'{__name__}: 用户{session.event.user_id} 使用命令set_group_permissions时发生错误: {e}, 设置群组权限失败'
        )
Пример #29
0
async def new_dy_sub(session: CommandSession):
    group_id = session.event.group_id
    session_type = session.event.detail_type
    if session_type == 'group':
        if not has_command_permissions(group_id):
            await session.send('本群组没有执行命令的权限呢QAQ')
            log.logger.info(f'{__name__}: 群组: {group_id} 没有命令权限, 已中止命令执行')
            return
    elif session_type == 'private':
        await session.send('本命令不支持在私聊中使用QAQ')
        log.logger.info(f'{__name__}: 用户: {session.event.user_id} 在{session_type}中使用了命令, 已中止命令执行')
        return
    else:
        log.logger.info(f'{__name__}: 用户: {session.event.user_id} 在{session_type}环境中使用了命令, 已中止命令执行')
        return
    # 从会话状态(session.state)中获取sub_id, 如果当前不存在, 则询问用户
    __sub_id = session.get('sub_id', prompt='请输入想要订阅的UP的UID: ',
                           arg_filters=[controllers.handle_cancellation(session),
                                        validators.not_empty('输入不能为空'),
                                        validators.match_regex(r'^\d+$', 'UID格式不对哦, 请重新输入~',
                                                               fullmatch=True)])
    # 获取UP的信息
    __up_info = await get_user_info(__sub_id)
    if __up_info['status'] == 'error':
        await session.send('似乎并没有这个UP呀QAQ')
        log.logger.info(f'{__name__}: 群组: {group_id}, 用户: {session.event.user_id} 添加动态订阅失败, '
                        f'没有找到该UID: {__sub_id} 对应的UP')
        return
    else:
        __up_name = __up_info['name']
        __sub_check = session.get('check', prompt=f'即将订阅【{__up_name}】的动态!\n确认吗?\n\n【是/否】',
                                  arg_filters=[controllers.handle_cancellation(session),
                                               validators.not_empty('输入不能为空'),
                                               validators.match_regex(r'^[是否]$', '输入不对哦, 请重新输入~',
                                                                      fullmatch=True)])
        if __sub_check == '否':
            await session.send('那就不订阅好了QAQ')
            log.logger.info(f'{__name__}: 群组: {group_id}, 用户: {session.event.user_id} 已取消添加动态订阅, 操作中止')
            return
        elif __sub_check == '是':
            try:
                # 首先更新动态订阅信息
                is_sub_dy_success = await add_dy_sub_to_db(sub_id=__sub_id, up_name=__up_name)
                if not is_sub_dy_success:
                    await session.send('发生了意料之外的错误QAQ')
                    log.logger.warning(f'{__name__}: 群组: {group_id}, 用户: {session.event.user_id} '
                                       f'试图添加: {__sub_id} 动态订阅时发生了错误, 更新订阅信息失败.')
                    return
                # 然后添加群组订阅
                is_add_group_sub_success = await add_group_dy_sub_to_db(sub_id=__sub_id, group_id=group_id)
                if not is_add_group_sub_success:
                    await session.send('发生了意料之外的错误QAQ')
                    log.logger.warning(f'{__name__}: 群组: {group_id}, 用户: {session.event.user_id} '
                                       f'试图添加: {__sub_id} 动态订阅时发生了错误, 向数据库写入群组订阅失败.')
                    return
                # 添加动态订阅时需要刷新该up的动态到数据库中
                __dy_info = await get_dynamic_info(__sub_id)
                for num in range(len(__dy_info)):
                    dy_id = __dy_info[num]['id']
                    dy_type = __dy_info[num]['type']
                    content = __dy_info[num]['content']
                    # 想数据库中写入动态信息
                    is_add_dy_info_success = \
                        await add_dy_info_to_db(user_id=__sub_id, dynamic_id=dy_id,
                                                dynamic_type=dy_type, content=content)
                    if not is_add_dy_info_success:
                        log.logger.warning(f'{__name__}: 群组: {group_id}, 用户: {session.event.user_id} '
                                           f'试图添加: {__sub_id} 动态订阅时发生了错误, 向数据库写入动态{dy_id}信息失败, 已跳过.')
                await session.send(f'已成功的订阅【{__up_name}】的动态!')
                log.logger.info(f'{__name__}: 群组: {group_id}, 用户: {session.event.user_id} '
                                f'已成功添加: {__up_name} 的动态订阅')
            except Exception as e:
                await session.send('订阅成功,但在更新动态时发生了未知的错误QAQ')
                log.logger.error(f'{__name__}: 群组: {group_id}, 用户: {session.event.user_id} '
                                 f'试图添加: {__sub_id} 动态订阅时发生了错误, error info: {e}.')
Пример #30
0
async def lottery(session: CommandSession):
    group_id = session.event.group_id
    session_type = session.event.detail_type
    if session_type == 'group':
        if not has_command_permissions(group_id):
            await session.send('本群组没有执行命令的权限呢QAQ')
            log.logger.info(f'{__name__}: 群组: {group_id} 没有命令权限, 已中止命令执行')
            return
    elif session_type == 'private':
        await session.send('本命令不支持在私聊中使用QAQ')
        log.logger.info(
            f'{__name__}: 用户: {session.event.user_id} 在{session_type}中使用了命令, 已中止命令执行'
        )
        return
    else:
        log.logger.info(
            f'{__name__}: 用户: {session.event.user_id} 在{session_type}环境中使用了命令, 已中止命令执行'
        )
        return
    # 初始化随机种子
    random_seed = hash(
        str([
            session.event.user_id, session.event.group_id,
            datetime.datetime.now()
        ]))
    random.seed(random_seed)

    people_num = session.get('people_num',
                             prompt='请输入抽奖的人数: ',
                             arg_filters=[
                                 controllers.handle_cancellation(session),
                                 validators.not_empty('输入不能为空'),
                                 validators.match_regex(r'^\d+$',
                                                        '只能是数字哦, 请重新输入~',
                                                        fullmatch=True)
                             ])
    people_num = int(people_num)

    group_user_list = await session.bot.get_group_member_list(group_id=group_id
                                                              )
    group_user_name_list = []

    for user_info in group_user_list:
        __user_qq = user_info['user_id']
        __user_group_info = await session.bot.get_group_member_info(
            group_id=group_id, user_id=__user_qq)
        __user_group_nickmane = __user_group_info['card']
        if not __user_group_nickmane:
            __user_group_nickmane = __user_group_info['nickname']
        group_user_name_list.append(__user_group_nickmane)

    if people_num > len(group_user_name_list):
        await session.send(f'抽奖人数大于群成员人数了QAQ, 请重新设置人数哦~')
        return

    lottery_result = random.sample(group_user_name_list, k=people_num)

    msg = ''
    for item in lottery_result:
        msg += f'\n【{item}】'
    await session.send(f'抽奖人数: 【{people_num}】\n以下是中奖名单:\n{msg}')
    log.logger.info(
        f'{__name__}: 群组: {group_id}, 用户: {session.event.user_id} 进行了一次抽奖')
    return