Example #1
0
 def confirm_waiter(waiter_group: Group, waiter_member: Member,
                    waiter_message: MessageChain):
     if all([
             waiter_group.id == group.id,
             waiter_member.id == member.id
     ]):
         if re.match(r"[是否]", waiter_message.asDisplay()):
             return waiter_message.asDisplay()
         else:
             return ""
Example #2
0
 async def handle(app: Ariadne, message: MessageChain, group: Group,
                  member: Member):
     if re.match(pattern, message.asDisplay()):
         if not await user_permission_require(group, member, 2):
             return MessageItem(
                 MessageChain.create([Plain(text="你没有权限,爬!")]), Normal())
         image_type = re.findall(r"添加(.*?)图片.*(\[图片].*)+",
                                 message.asDisplay(), re.S)[0][0]
         if image_type not in legal_type:
             return MessageItem(
                 MessageChain.create([
                     Plain(
                         text=f"非法图片类型!\n合法image_type:{'、'.join(legal_type)}"
                     )
                 ]), QuoteSource())
         if path := image_paths.get(image_type):
             if os.path.exists(path):
                 try:
                     await ImageAdder.add_image(path, message.get(Image))
                 except:
                     logger.error(traceback.format_exc())
                     return MessageItem(
                         MessageChain.create(
                             [Plain(text="出错了呐~请查看日志/控制台输出!")]), Normal())
                 return MessageItem(
                     MessageChain.create([
                         Plain(
                             text=f"保存成功!共保存了{len(message.get(Image))}张图片!")
                     ]), Normal())
             else:
                 return MessageItem(
                     MessageChain.create([
                         Image(
                             path=
                             f"{os.getcwd()}/statics/error/path_not_exists.png"
                         )
                     ]), QuoteSource())
         else:
             return MessageItem(
                 MessageChain.create([Plain(text=f"无{image_type}项!请检查配置!")
                                      ]), QuoteSource())
Example #3
0
 async def wait_for_chain(chain: MessageChain, i_sender: Member):
     if i_sender.id == sender.id and i_sender.group.id == sender.group.id:
         await chain.download_binary()
         chain = chain.include(Plain, Image)
         if chain:
             if chain.asDisplay() != "取消":
                 id: int = db.add_cave(sender.name, chain)
                 await app.sendMessage(group,
                                       MessageChain([f"添加成功,ID: {id}"]))
         else:
             await app.sendMessage(group, MessageChain(["请发送图片或文本"]))
         return True
Example #4
0
    async def handle(app: Ariadne, message: MessageChain, group: Group, member: Member):
        if message.asDisplay() == "搜番":
            await update_user_call_count_plus(group, member, UserCalledCount.search, "search")
            if not await group_setting.get_setting(group.id, Setting.bangumi_search):
                return MessageItem(MessageChain.create([Plain(text="搜番功能未开启呐~请联系管理员哦~")]), Normal())
            try:
                await app.sendGroupMessage(group, MessageChain.create([
                    At(member.id), Plain("请在30秒内发送要搜索的图片呐~")
                ]))
            except AccountMuted:
                logger.error(f"Bot 在群 <{group.name}> 被禁言,无法发送!")
                return None

            image_get = None
            message_received = None

            @Waiter.create_using_function([GroupMessage])
            def waiter(
                    event: GroupMessage, waiter_group: Group,
                    waiter_member: Member, waiter_message: MessageChain
            ):
                nonlocal image_get
                nonlocal message_received
                if time.time() - start_time < 30:
                    if all([
                        waiter_group.id == group.id,
                        waiter_member.id == member.id,
                        len(waiter_message[Image]) == len(waiter_message.__root__) - 1
                    ]):
                        image_get = True
                        message_received = waiter_message
                        return event
                else:
                    logger.warning("等待用户超时!BangumiSearchHandler进程推出!")
                    return event

            inc = InterruptControl(bcc)
            start_time = time.time()
            await inc.wait(waiter)
            if image_get:
                logger.success("收到用户图片,启动搜索进程!")
                try:
                    await app.sendGroupMessage(
                        group,
                        await BangumiSearcher.search_bangumi(message_received[Image][0]),
                        quote=message_received[Source][0]
                    )
                except AccountMuted:
                    logger.error(f"Bot 在群 <{group.name}> 被禁言,无法发送!")
                    pass
            return None
        else:
            return None
 async def handle(app: Ariadne, message: MessageChain, group: Group,
                  member: Member):
     if message.asDisplay().startswith("/fake "):
         content = "".join(i.text for i in message.get(Plain))[6:]
         if not message.has(At):
             return MessageItem(MessageChain.create([Plain(text="未指定目标!")]),
                                Normal())
         sender = message.get(At)[0]
         forward_nodes = [
             ForwardNode(
                 senderId=sender.target,
                 time=datetime.now(),
                 senderName=(await app.getMember(group,
                                                 sender.target)).name,
                 messageChain=MessageChain.create(Plain(text=content)),
             )
         ]
         return MessageItem(
             MessageChain.create(Forward(nodeList=forward_nodes)), Normal())
async def bot_manager_handler(app: Ariadne, message: MessageChain,
                              group: Group, member: Member):
    message_text = message.asDisplay()
    if message_text.startswith("setting -set "):
        msg = await execute_setting_update(group, member, message_text)
    elif re.match(r"user -grant @[1-9][0-9]{4,14} .*", message_text):
        msg = await execute_grant_permission(group, member, message_text)
    elif re.match(r"blacklist -add @[1-9][0-9]{4,14}", message_text):
        msg = await execute_blacklist_append(int(message_text[16:]), group,
                                             member)
    elif re.match(r"blacklist -add -all @[1-9][0-9]{4,14}", message_text):
        msg = await execute_blacklist_append(int(message_text[16:]), group,
                                             member)
    elif re.match(r"blacklist -remove @[1-9][0-9]{4,14}", message_text):
        msg = await execute_blacklist_remove(int(message_text[19:]), group,
                                             member)
    else:
        return None
    await app.sendGroupMessage(group, msg, quote=message.getFirst(Source))
Example #7
0
async def dice(app: Ariadne, message: MessageChain, group: Group):
    if not await group_setting.get_setting(group.id, Setting.dice):
        await app.sendGroupMessage(group,
                                   MessageChain("骰子功能尚未开启哟~"),
                                   quote=message.getFirst(Source))
        return
    times, max_point = message.asDisplay().strip().split('d')
    times, max_point = int(times), int(max_point)
    if times > 100:
        await app.sendGroupMessage(group,
                                   MessageChain("nmd,太多次了!"),
                                   quote=message.getFirst(Source))
    elif max_point > 1000:
        await app.sendGroupMessage(group,
                                   MessageChain("你滴太大,我忍不住!"),
                                   quote=message.getFirst(Source))
    else:
        await app.sendGroupMessage(
            group,
            MessageChain(
                f"{random.choice([num for num in range(1, max_point + 1)])}/{max_point} "
                for _ in range(times)),
            quote=message.getFirst(Source))
Example #8
0
    async def handle(
        app: Ariadne,
        message: MessageChain,
        group: Group,
        member: Member,
        cmd: RegexResult,
        at1: ElementResult,
        at2: ElementResult,
        qq1: RegexResult,
        qq2: RegexResult,
        img1: ElementResult,
        img2: ElementResult
    ):
        if not any([at1.matched, at2.matched, qq1.matched, qq2.matched, img1.matched, img2.matched]):
            return None
        await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
        message_text = message.asDisplay()
        if message_text.startswith("摸"):
            match_elements = AvatarFunPic.get_match_element(message)
            if len(match_elements) >= 1:
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                element = match_elements[0]
                return await AvatarFunPic.petpet(element.target if isinstance(element, At) else element.url)
            elif re.match(r"摸 [0-9]+", message_text):
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                return await AvatarFunPic.petpet(int(message_text[2:]))

        elif message_text.startswith("亲"):
            match_elements = AvatarFunPic.get_match_element(message)
            if len(match_elements) == 1:
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                element = match_elements[0]
                return await AvatarFunPic.kiss(
                    member.id, 
                    element.target if isinstance(element, At) else element.url
                )
            elif len(match_elements) > 1:
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                element1 = match_elements[0]
                element2 = match_elements[1]
                return await AvatarFunPic.kiss(
                    element1.target if isinstance(element1, At) else element1.url,
                    element2.target if isinstance(element2, At) else element2.url
                )
            elif re.match(r"亲 [0-9]+ [0-9]+", message_text):
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                operator, target = message_text[2:].split(" ")
                return await AvatarFunPic.kiss(int(operator), int(target))
            elif re.match(r"亲 [0-9]+", message_text):
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                return await AvatarFunPic.kiss(member.id, int(message_text[2:]))

        elif message_text.startswith("贴"):
            match_elements = AvatarFunPic.get_match_element(message)
            if len(match_elements) == 1:
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                element = match_elements[0]
                return await AvatarFunPic.rub(
                    member.id, 
                    element.target if isinstance(element, At) else element.url
                )
            elif len(match_elements) > 1:
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                element1 = match_elements[0]
                element2 = match_elements[1]
                return await AvatarFunPic.rub(
                    element1.target if isinstance(element1, At) else element1.url,
                    element2.target if isinstance(element2, At) else element2.url
                )
            elif re.match(r"贴 [0-9]+ [0-9]+", message_text):
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                operator, target = message_text[2:].split(" ")
                return await AvatarFunPic.rub(int(operator), int(target))
            elif re.match(r"贴 [0-9]+", message_text):
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                return await AvatarFunPic.rub(member.id, int(message_text[2:]))

        elif message_text.startswith("撕"):
            match_elements = AvatarFunPic.get_match_element(message)
            if len(match_elements) >= 1:
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                element = match_elements[0]
                return await AvatarFunPic.ripped(element.target if isinstance(element, At) else element.url)
            elif re.match(r"撕 [0-9]+", message_text):
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                return await AvatarFunPic.ripped(int(message_text[2:]))

        elif message_text.startswith("丢"):
            match_elements = AvatarFunPic.get_match_element(message)
            if len(match_elements) >= 1:
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                element = match_elements[0]
                return await AvatarFunPic.throw(element.target if isinstance(element, At) else element.url)
            elif re.match(r"丢 [0-9]+", message_text):
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                return await AvatarFunPic.throw(int(message_text[2:]))

        elif message_text.startswith("爬"):
            match_elements = AvatarFunPic.get_match_element(message)
            if len(match_elements) >= 1:
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                element = match_elements[0]
                return await AvatarFunPic.crawl(element.target if isinstance(element, At) else element.url)
            elif re.match(r"爬 [0-9]+", message_text):
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                return await AvatarFunPic.crawl(int(message_text[2:]))

        elif message_text.startswith("精神支柱"):
            match_elements = AvatarFunPic.get_match_element(message)
            if len(match_elements) >= 1:
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                element = match_elements[0]
                return await AvatarFunPic.support(element.target if isinstance(element, At) else element.url)
            elif re.match(r"精神支柱 [0-9]+", message_text):
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                return await AvatarFunPic.support(int(message_text[5:]))

        elif message_text.startswith("吞"):
            match_elements = AvatarFunPic.get_match_element(message)
            if len(match_elements) >= 1:
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                element = match_elements[0]
                return await AvatarFunPic.swallowed(element.target if isinstance(element, At) else element.url)
            elif re.match(r"吞 [0-9]+", message_text):
                await update_user_call_count_plus(group, member, UserCalledCount.functions, "functions")
                return await AvatarFunPic.swallowed(int(message_text[2:]))
        else:
            return None
Example #9
0
 async def real_handle(self,
                       app: Ariadne,
                       message: MessageChain,
                       group: Group = None,
                       member: Member = None,
                       friend: Friend = None) -> MessageItem:
     commands = {
         "enable": {
             "permission": [3, []],
             "permission_nl": "3 级权限",
             "manual": "/github-watch enable",
             "description": "启用 Github 订阅功能",
             "func": self.enable
         },
         "disable": {
             "permission": [3, []],
             "permission_nl": "3 级权限",
             "manual": "/github-watch disable",
             "description": "禁用 Github 订阅功能",
             "func": self.disable
         },
         "add": {
             "permission":
             [2, (MemberPerm.Administrator, MemberPerm.Owner)],
             "permission_nl": "2 级或群管理员及以上权限",
             "manual": "/github-watch add {repo} [repo]+",
             "description": "订阅仓库变动,可同时订阅多个仓库",
             "func": self.add
         },
         "remove": {
             "permission":
             [2, (MemberPerm.Administrator, MemberPerm.Owner)],
             "permission_nl": "2 级或群管理员及以上权限",
             "manual": "/github-watch remove {repo} [repo]+",
             "description": "取消订阅仓库变动,可同时取消订阅多个仓库",
             "func": self.remove
         },
         "check": {
             "permission": [
                 1,
                 (MemberPerm.Member, MemberPerm.Administrator,
                  MemberPerm.Owner)
             ],
             "permission_nl":
             "任何人",
             "manual":
             "/github-watch check",
             "description":
             "手动查看仓库订阅列表",
             "func":
             self.check
         },
         "cache": {
             "permission":
             [2, (MemberPerm.Administrator, MemberPerm.Owner)],
             "permission_nl": "2 级或群管理员及以上权限",
             "manual": "/github-watch cache {update/store}",
             "description": "更新/储存缓存",
             "func": self.cache
         }
     }
     if message.asDisplay().startswith("/github-watch"):
         if not self.initialize:
             self.update_cache()
             for repo in self.__cached.keys():
                 self.__cached[repo]['enabled'] = True
             self.store_cache()
             self.initialize = True
         args = message.asDisplay().split(" ", maxsplit=1)
         if len(args) == 1:
             msg = [Plain(text="缺少参数\n\n")]
             for func in commands.keys():
                 msg.append(
                     Plain(text=(
                         f"/github-watch {func}\n"
                         f"    描述:{commands[func]['description']}\n"
                         f"    用法:{commands[func]['manual']}\n"
                         f"    权限:{commands[func]['permission_nl']}\n")))
             return MessageItem(
                 await MessageChainUtils.messagechain_to_img(
                     MessageChain.create(msg)), QuoteSource())
         _, args = args
         name = args.split(" ", maxsplit=1)[0]
         arg = ''.join(args.split(" ", maxsplit=1)[1:])
         if name not in commands.keys():
             return MessageItem(
                 MessageChain.create([Plain(text=f"未知指令:{arg}")]),
                 QuoteSource())
         if member and group:
             permission = commands[name]['permission']
             if not await user_permission_require(group, member, permission[0]) \
                     and not (member.permission in permission[1]):
                 return MessageItem(
                     MessageChain.create([
                         Plain(
                             text=f"权限不足,你需要 {permission[0]} 级权限"
                             f"{('或来自 ' + str(permission[1][0]) + ' 的权限') if permission[1] else ''}"
                         )
                     ]), QuoteSource())
         arg = arg.strip()
         return MessageItem(
             await commands[name]['func'](app=app,
                                          group=group,
                                          friend=friend,
                                          arg=arg), QuoteSource())
Example #10
0
    async def handle(app: Ariadne, message: MessageChain, group: Group,
                     member: Member) -> MessageItem:
        # global saya_data
        if message.asDisplay().strip() == "已加载插件":
            loaded_channels = SayaManager.get_loaded_channels()
            keys = list(loaded_channels.keys())
            keys.sort()
            return MessageItem(
                await MessageChainUtils.messagechain_to_img(
                    MessageChain.create([Plain(text="目前加载插件:\n")] + [
                        Plain(
                            text=f"{i + 1}. {loaded_channels[keys[i]]._name}\n"
                        ) for i in range(len(keys))
                    ] + [Plain(text="发送 `插件详情 [编号|名称]` 可查看插件详情")])),
                QuoteSource())
        elif re.match(r"插件详情 .+", message.asDisplay()):
            target = message.asDisplay()[5:].strip()
            loaded_channels = SayaManager.get_loaded_channels()
            keys = list(loaded_channels.keys())
            if target.isdigit():
                keys.sort()
                if not 0 <= int(target) - 1 < len(keys):
                    return MessageItem(
                        MessageChain.create([Plain(text="错误的编号!请检查后再发送!")]),
                        QuoteSource())
                channel = loaded_channels[keys[int(target) - 1]]
                channel_path = keys[int(target) - 1]
            else:
                for lchannel in loaded_channels.keys():
                    if loaded_channels[lchannel]._name == target:
                        channel = loaded_channels[lchannel]
                        channel_path = lchannel
                        break
                else:
                    return MessageItem(
                        MessageChain.create([Plain(text="错误的名称!请检查后再发送!")]),
                        QuoteSource())
            return MessageItem(
                MessageChain.create([
                    Plain(text=f"插件名称:{channel._name}\n"),
                    Plain(text=f"插件作者:{'、'.join(channel._author)}\n"),
                    Plain(text=f"插件描述:{channel._description}\n"),
                    Plain(text=f"插件包名:{channel_path}")
                ]), QuoteSource())
        elif message.asDisplay() == "未加载插件":
            if not await user_permission_require(group, member, 3):
                return MessageItem(MessageChain.create([Plain(text="爬,权限不足")]),
                                   QuoteSource())
            unloaded_channels = SayaManager.get_unloaded_channels()
            unloaded_channels.sort()
            return MessageItem(
                MessageChain.create([Plain(text="目前未加载插件:\n")] + [
                    Plain(text=f"{i + 1}. {unloaded_channels[i]}\n")
                    for i in range(len(unloaded_channels))
                ] + [Plain(text="发送 `[加载|卸载|重载]插件 [编号|名称]` 可加载/卸载/重载插件\n")]),
                QuoteSource())
        elif re.match(r"加载插件 .+", message.asDisplay()):
            if not await user_permission_require(group, member, 3):
                return MessageItem(MessageChain.create([Plain(text="爬,权限不足")]),
                                   QuoteSource())
            target = message.asDisplay()[5:].strip()
            unloaded_channels = SayaManager.get_unloaded_channels()
            if target.isdigit():
                unloaded_channels.sort()
                if not 0 <= int(target) - 1 < len(unloaded_channels):
                    return MessageItem(
                        MessageChain.create([Plain(text="错误的编号!请检查后再发送!")]),
                        QuoteSource())
                channel = unloaded_channels[int(target) - 1]
            else:
                for ulchannel in unloaded_channels:
                    if ulchannel == target:
                        channel = ulchannel
                        break
                else:
                    return MessageItem(
                        MessageChain.create([Plain(text="错误的名称!请检查后再发送!")]),
                        QuoteSource())

            await app.sendMessage(
                group,
                MessageChain.create(
                    [Plain(text=f"你确定要加载插件 `{channel}` 吗?(是/否)")]))

            @Waiter.create_using_function([GroupMessage])
            def confirm_waiter(waiter_group: Group, waiter_member: Member,
                               waiter_message: MessageChain):
                if all([
                        waiter_group.id == group.id,
                        waiter_member.id == member.id
                ]):
                    if re.match(r"[是否]", waiter_message.asDisplay()):
                        return waiter_message.asDisplay()
                    else:
                        return ""

            result = await inc.wait(confirm_waiter)
            if not result:
                return MessageItem(
                    MessageChain.create([Plain(text="非预期回复,进程退出")]),
                    QuoteSource())
            elif result == "是":
                result = SayaManager.load_channel(channel)
                if result:
                    return MessageItem(
                        MessageChain.create(
                            [Plain(text=f"发生错误:{result[channel]}")]),
                        QuoteSource())
                else:
                    return MessageItem(
                        MessageChain.create([Plain(text="加载成功")]),
                        QuoteSource())
            else:
                return MessageItem(MessageChain.create([Plain(text="进程退出")]),
                                   QuoteSource())
        elif re.match(r"[卸重]载插件 .+", message.asDisplay()):
            if not await user_permission_require(group, member, 3):
                return MessageItem(MessageChain.create([Plain(text="爬,权限不足")]),
                                   QuoteSource())
            load_type = "reload" if message.asDisplay()[0] == "重" else "unload"
            target = message.asDisplay()[5:].strip()
            loaded_channels = SayaManager.get_loaded_channels()
            keys = list(loaded_channels.keys())
            keys.sort()
            if target.isdigit():
                if not 0 <= int(target) - 1 < len(keys):
                    return MessageItem(
                        MessageChain.create([Plain(text="错误的编号!请检查后再发送!")]),
                        QuoteSource())
                channel = loaded_channels[keys[int(target) - 1]]
                channel_path = keys[int(target) - 1]
            else:
                for lchannel in loaded_channels.keys():
                    if loaded_channels[lchannel]._name == target:
                        channel = loaded_channels[lchannel]
                        channel_path = lchannel
                        break
                else:
                    return MessageItem(
                        MessageChain.create([Plain(text="错误的名称!请检查后再发送!")]),
                        QuoteSource())

            await app.sendMessage(
                group,
                MessageChain.create([
                    Plain(
                        text=
                        f"你确定要{message.asDisplay()[0]}载插件 `{channel._name}` 吗?(是/否)"
                    )
                ]))

            @Waiter.create_using_function([GroupMessage])
            def confirm_waiter(waiter_group: Group, waiter_member: Member,
                               waiter_message: MessageChain):
                if all([
                        waiter_group.id == group.id,
                        waiter_member.id == member.id
                ]):
                    if re.match(r"[是否]", waiter_message.asDisplay()):
                        return waiter_message.asDisplay()
                    else:
                        return ""

            result = await inc.wait(confirm_waiter)
            if not result:
                return MessageItem(
                    MessageChain.create([Plain(text="非预期回复,进程退出")]),
                    QuoteSource())
            elif result == "是":
                result = SayaManager.unload_channel(
                    channel_path
                ) if load_type == "unload" else SayaManager.reload_channel(
                    channel_path)
                if result:
                    return MessageItem(
                        MessageChain.create(
                            [Plain(text=f"发生错误:{result[channel_path]}")]),
                        QuoteSource())
                else:
                    return MessageItem(
                        MessageChain.create(
                            [Plain(text=f"{message.asDisplay()[0]}载成功")]),
                        QuoteSource())
            else:
                return MessageItem(MessageChain.create([Plain(text="进程退出")]),
                                   QuoteSource())
        elif re.match(r"(打开|关闭)插件 .+", message.asDisplay()):
            if not await user_permission_require(group, member, 3):
                return MessageItem(MessageChain.create([Plain(text="爬,权限不足")]),
                                   QuoteSource())
            switch_type = "on" if message.asDisplay()[:2] == "打开" else "off"
            target = message.asDisplay()[5:].strip()
            loaded_channels = SayaManager.get_loaded_channels()
            keys = list(loaded_channels.keys())
            keys.sort()
            channel_path = ""
            if target.isdigit():
                if not 0 <= int(target) - 1 < len(keys):
                    return MessageItem(
                        MessageChain.create([Plain(text="错误的编号!请检查后再发送!")]),
                        QuoteSource())
                channel_path = keys[int(target) - 1]
            else:
                for lchannel in loaded_channels.keys():
                    if loaded_channels[lchannel]._name == target:
                        channel_path = lchannel
                        break
            saya_data.switch_on(
                channel_path,
                group) if switch_type == "on" else saya_data.switch_off(
                    channel_path, group)
            return MessageItem(
                MessageChain.create([
                    Plain(text=f"插件{channel_path}已{message.asDisplay()[:2]}!")
                ]), QuoteSource())
Example #11
0
 async def detected_event(self, app: Ariadne, group: Group, member: Member,
                          message: MessageChain):
     word = message.asDisplay().strip()
     message_source = message.getFirst(Source)
     if self.group == group.id and (self.member == member.id
                                    or not self.member):
         if message.asDisplay().strip() in ("/wordle -giveup",
                                            "/wordle -g"):
             dic = group_word_dic[group.id]
             word_data = word_list[dic][len(
                 self.wordle.word)][self.wordle.word]
             explain = '\n'.join(
                 [f"【{key}】:{word_data[key]}" for key in word_data])
             await app.sendGroupMessage(
                 group,
                 MessageChain([
                     Image(data_bytes=self.wordle.get_board_bytes()),
                     Plain("很遗憾,没有人猜出来呢"
                           f"单词:{self.wordle.word}\n{explain}")
                 ]),
                 quote=message_source)
             await self.member_list_mutex.acquire()
             for member in self.member_list:
                 await update_member_statistic(group, member,
                                               StatisticType.lose)
                 await update_member_statistic(group, member,
                                               StatisticType.game)
             self.member_list_mutex.release()
             await mutex.acquire()
             group_running[group.id] = False
             mutex.release()
             return True
         if message.asDisplay().strip() == "/wordle -hint":
             await update_member_statistic(group, member,
                                           StatisticType.hint)
             hint = self.wordle.get_hint()
             if not hint:
                 await app.sendGroupMessage(
                     group,
                     MessageChain("你还没有猜对过一个字母哦~再猜猜吧~"),
                     quote=message.getFirst(Source))
             else:
                 await app.sendGroupMessage(
                     group,
                     MessageChain(
                         [Image(data_bytes=self.wordle.draw_hint())]),
                     quote=message.getFirst(Source))
             return False
         if len(word) == self.wordle.length and word.encode(
                 'utf-8').isalpha():
             await self.member_list_mutex.acquire()
             self.member_list.add(member.id)
             self.member_list_mutex.release()
             await self.wordle.draw_mutex.acquire()
             print("required")
             result = self.wordle.guess(word)
             print(result)
             print("released")
             self.wordle.draw_mutex.release()
             if not result:
                 return True
             if result[0]:
                 await update_member_statistic(
                     group, member, StatisticType.correct
                     if result[1] else StatisticType.wrong)
                 await self.member_list_mutex.acquire()
                 for member in self.member_list:
                     await update_member_statistic(
                         group, member, StatisticType.win
                         if result[1] else StatisticType.lose)
                     await update_member_statistic(group, member,
                                                   StatisticType.game)
                 self.member_list_mutex.release()
                 dic = group_word_dic[group.id]
                 word_data = word_list[dic][len(
                     self.wordle.word)][self.wordle.word]
                 explain = '\n'.join(
                     [f"【{key}】:{word_data[key]}" for key in word_data])
                 await app.sendGroupMessage(
                     group,
                     MessageChain([
                         Image(data_bytes=self.wordle.get_board_bytes()),
                         Plain(
                             f"\n{'恭喜你猜出了单词!' if result[1] else '很遗憾,没有人猜出来呢'}\n"
                             f"【单词】:{self.wordle.word}\n{explain}")
                     ]),
                     quote=message_source)
                 await mutex.acquire()
                 group_running[group.id] = False
                 mutex.release()
                 return True
             elif not result[2]:
                 await app.sendGroupMessage(
                     group,
                     MessageChain(f"你确定 {word} 是一个合法的单词吗?"),
                     quote=message_source)
             elif result[3]:
                 await app.sendGroupMessage(group,
                                            MessageChain("你已经猜过这个单词了呢"),
                                            quote=message_source)
             else:
                 await update_member_statistic(group, member,
                                               StatisticType.wrong)
                 await app.sendGroupMessage(
                     group,
                     MessageChain(
                         [Image(data_bytes=self.wordle.get_board_bytes())]),
                     quote=message_source)
             return False
Example #12
0
async def pica_function(app: Ariadne, message: MessageChain, group: Group,
                        member: Member, operation: RegexResult,
                        message_type: ArgResult, forward_type: ArgResult,
                        rank_time: RegexResult, content: RegexResult):
    if not pica.init:
        await app.sendGroupMessage(group,
                                   MessageChain("pica实例初始化失败,请重启机器人或重载插件!"))
        return
    if any([
            operation.result.asDisplay() == "download"
            and not DAILY_DOWNLOAD_LIMITER.check(member.id),
            operation.result.asDisplay() == "search"
            and not DAILY_SEARCH_LIMITER.check(member.id),
            operation.result.asDisplay() == "random"
            and not DAILY_RANDOM_LIMITER.check(member.id),
            operation.result.asDisplay() == "rank"
            and not DAILY_RANK_LIMITER.check(member.id)
    ]):
        await app.sendGroupMessage(group,
                                   MessageChain(limit_text[str(
                                       operation.result.asDisplay())]),
                                   quote=message.getFirst(Source))
        return

    if operation.result.asDisplay() == "download":
        DAILY_DOWNLOAD_LIMITER.increase(member.id)
    elif operation.result.asDisplay() == "search":
        DAILY_SEARCH_LIMITER.increase(member.id)
    elif operation.result.asDisplay() == "random":
        DAILY_RANDOM_LIMITER.increase(member.id)
    elif operation.result.asDisplay() == "rank":
        DAILY_RANK_LIMITER.increase(member.id)

    if operation.result.asDisplay() == "init":
        if pica.init:
            await app.sendGroupMessage(group, MessageChain("pica已初始化"))
            return
        try:
            await pica.check()
            await app.sendGroupMessage(group, MessageChain("pica初始化成功"))
        except aiohttp.ClientConnectorError:
            await app.sendGroupMessage(group, MessageChain("pica初始化失败,请检查代理"))
        except KeyError:
            await app.sendGroupMessage(group,
                                       MessageChain("pica初始化失败,请检查账号密码是否配置正确"))

    elif operation.result.asDisplay(
    ) == "download" and forward_type.matched and content.matched:
        comic_id = content.result.asDisplay()
        await app.sendMessage(group, MessageChain(f"收到请求,正在下载{comic_id}..."))
        info = await pica.download_comic(comic_id, False)
        image_list = []
        for root, _, files in os.walk(info[0]):
            for file in files:
                if file[-4:] in (".jpg", ".png"):
                    image_list.append(os.path.join(root, file))
        node_count = 0
        time_count = 0
        time_base = datetime.now() - timedelta(seconds=len(image_list))
        forward_nodes = [
            ForwardNode(
                senderId=bot_qq,
                time=time_base + timedelta(seconds=time_count),
                senderName="纱雾酱",
                messageChain=MessageChain("IOS系统可能会乱序,请参照下方文件名和发送时间顺序自行排序!"))
        ]
        for path in image_list:
            node_count += 1
            time_count += 1
            forward_nodes.append(
                ForwardNode(
                    senderId=bot_qq,
                    time=time_base + timedelta(seconds=time_count),
                    senderName="纱雾酱",
                    messageChain=MessageChain([
                        Image(path=path),
                        Plain(
                            f"\n{path.replace(info[0], '')}\n{time_base + timedelta(seconds=time_count)}"
                        )
                    ])))
            if node_count == 20:
                await app.sendMessage(
                    group, MessageChain([Forward(nodeList=forward_nodes)]))
                forward_nodes = [
                    ForwardNode(senderId=bot_qq,
                                time=time_base + timedelta(seconds=time_count),
                                senderName="纱雾酱",
                                messageChain=MessageChain(
                                    "IOS系统可能会乱序,请参照下方文件名和发送时间顺序自行排序!"))
                ]
                node_count = 0
        await app.sendGroupMessage(
            group, MessageChain([Forward(nodeList=forward_nodes)]))

    elif operation.result.asDisplay(
    ) == "download" and message_type.matched and content.matched:
        comic_id = content.result.asDisplay()
        await app.sendMessage(group, MessageChain(f"收到请求,正在下载{comic_id}..."))
        info = await pica.download_comic(comic_id, False)
        image_list = []
        for root, _, files in os.walk(info[0]):
            for file in files:
                if not file[-3:] == "zip":
                    image_list.append(os.path.join(root, file))
        await app.sendGroupMessage(
            group, MessageChain([Image(path=path) for path in image_list]))

    elif operation.result.asDisplay() == "download" and content.matched:
        comic_id = message.asDisplay()[14:]
        await app.sendMessage(group, MessageChain(f"收到请求,正在下载{comic_id}..."))
        info = await pica.download_comic(comic_id)
        try:
            await app.uploadFile(data=info[1],
                                 method=UploadMethod.Group,
                                 target=group,
                                 name=f"{info[0].replace(' ', '')}.zip")
        except RemoteException:
            await app.uploadFile(data=info[1],
                                 method=UploadMethod.Group,
                                 target=group,
                                 name=f"pica_{comic_id}.zip")
        return None

    elif operation.result.asDisplay() in ("search", "random"):
        search = operation.result.asDisplay() == "search"
        keyword = content.result.asDisplay() if content.matched else ''
        if search and content.matched:
            await app.sendMessage(group,
                                  MessageChain(f"收到请求,正在搜索{keyword}..."))
        data = (await pica.search(keyword))[:10] \
            if search else (await pica.random())[:10]
        forward_nodes = []
        for comic in data:
            comic_info = await pica.comic_info(
                comic["id"]
            ) if operation.result.asDisplay() == "search" else comic
            try:
                forward_nodes.append(
                    ForwardNode(
                        senderId=bot_qq,
                        time=datetime.now(),
                        senderName="纱雾酱",
                        messageChain=MessageChain([
                            Image(data_bytes=TextEngine([
                                GraiaAdapter(
                                    MessageChain([
                                        await get_thumb(comic_info),
                                        Plain(
                                            text=f"\n名称:{comic_info['title']}\n"
                                        ),
                                        Plain(
                                            text=f"作者:{comic_info['author']}\n"
                                        ),
                                        Plain(
                                            text=
                                            f"描述:{comic_info['description']}\n"
                                        ) if search else Plain(text=''),
                                        Plain(
                                            text=
                                            f"分类:{'、'.join(comic_info['categories'])}\n"
                                        ),
                                        Plain(
                                            text=
                                            f"标签:{'、'.join(comic_info['tags'])}\n"
                                        ) if search else Plain(text=''),
                                        Plain(
                                            text=
                                            f"页数:{comic_info['pagesCount']}\n"
                                        ),
                                        Plain(
                                            text=
                                            f"章节数:{comic_info['epsCount']}\n"),
                                        Plain(
                                            text=
                                            f"完结状态:{'已完结' if comic_info['finished'] else '未完结'}\n"
                                        ),
                                        Plain(
                                            text=
                                            f"喜欢: {comic_info['totalLikes']}    "
                                        ),
                                        Plain(
                                            text=
                                            f"浏览次数: {comic_info['totalViews']}    "
                                        )
                                    ]))
                            ],
                                                        max_width=2160).draw())
                        ]).extend([
                            Plain(text="\n发送下列命令下载:\n"),
                            Plain(
                                text=
                                f"转发消息形式:pica download -forward {comic_info['_id']}\n"
                            ),
                            Plain(
                                text=
                                f"消息图片形式:pica download -message {comic_info['_id']}\n"
                            ),
                            Plain(
                                text=f"压缩包形式:pica download {comic_info['_id']}"
                            )
                        ])))
            except Exception as e:
                logger.error(e)
                continue
        await app.sendGroupMessage(
            group, MessageChain([Forward(nodeList=forward_nodes)]))

    elif operation.result.asDisplay() == "rank":
        rank_time = rank_time.result.asDisplay(
        ) if rank_time.matched else "-H24"
        if rank_time not in ("-H24", "-D7", "-D30"):
            await app.sendGroupMessage(
                group,
                MessageChain([
                    Plain(text="错误的时间!支持的选项:\n"),
                    Plain(text="H24:24小时排行榜\n"),
                    Plain(text="D7:一周排行榜\n"),
                    Plain(text="D30:一月排行榜\n"),
                    Plain(text="命令格式:pica random -{time}")
                ]))
            return
        data = (await pica.rank(rank_time[1:]))[:10]
        forward_nodes = []
        rank = 0
        for comic_info in data:
            rank += 1
            try:
                forward_nodes.append(
                    ForwardNode(
                        senderId=bot_qq,
                        time=datetime.now(),
                        senderName="纱雾酱",
                        messageChain=MessageChain([
                            Image(data_bytes=TextEngine([
                                GraiaAdapter(
                                    MessageChain([
                                        await get_thumb(comic_info),
                                        Plain(text=f"\n排名:{rank}\n"),
                                        Plain(
                                            text=f"名称:{comic_info['title']}\n"
                                        ),
                                        Plain(
                                            text=f"作者:{comic_info['author']}\n"
                                        ),
                                        Plain(
                                            text=
                                            f"分类:{'、'.join(comic_info['categories'])}\n"
                                        ),
                                        Plain(
                                            text=
                                            f"页数:{comic_info['pagesCount']}\n"
                                        ),
                                        Plain(
                                            text=
                                            f"章节数:{comic_info['epsCount']}\n"),
                                        Plain(
                                            text=
                                            f"完结状态:{'已完结' if comic_info['finished'] else '未完结'}\n"
                                        ),
                                        Plain(
                                            text=
                                            f"喜欢: {comic_info['totalLikes']}    "
                                        ),
                                        Plain(
                                            text=
                                            f"浏览次数: {comic_info['totalViews']}    "
                                        )
                                    ]))
                            ],
                                                        max_width=2160).draw())
                        ]).extend([
                            Plain(text="\n发送下列命令下载:\n"),
                            Plain(
                                text=
                                f"转发消息形式:pica download -forward {comic_info['_id']}\n"
                            ),
                            Plain(
                                text=
                                f"消息图片形式:pica download -message {comic_info['_id']}\n"
                            ),
                            Plain(
                                text=f"压缩包形式:pica download {comic_info['_id']}"
                            )
                        ])))
            except Exception as e:
                logger.error(e)
                continue
        await app.sendGroupMessage(
            group, MessageChain([Forward(nodeList=forward_nodes)]))
Example #13
0
async def wrong_usage_tips(app: Ariadne, group: Group, messagechain: MessageChain):
    msg_text = messagechain.asDisplay()
    if msg_text.startswith(('&mute ', '&unmute')) and msg_text.endswith(' '):
        await app.sendGroupMessage(group, MessageChain.create([Plain('请删除末尾空格后重试')]))