Пример #1
0
 async def handle(self, app: GraiaMiraiApplication, message: MessageChain,
                  group: Group, member: Member):
     message_serialization = message.asSerializationString().replace(
         "[mirai:source:" +
         re.findall(r'\[mirai:source:(.*?)]',
                    message.asSerializationString(), re.S)[0] + "]", "")
     if re.match(r"添加回复关键词#[\s\S]*#[\s\S]*", message_serialization):
         if await user_permission_require(group, member, 2):
             set_result(
                 message, await self.update_keyword(message,
                                                    message_serialization))
         else:
             return MessageItem(MessageChain.create([Plain(text="权限不足,爬")]),
                                QuoteSource(GroupStrategy()))
     elif re.match(r"删除回复关键词#[\s\S]*", message_serialization):
         if await user_permission_require(group, member, 2):
             set_result(
                 message, await
                 self.delete_keyword(app, message_serialization, group,
                                     member))
         else:
             set_result(
                 message,
                 MessageItem(MessageChain.create([Plain(text="权限不足,爬")]),
                             QuoteSource(GroupStrategy())))
     elif result := await self.keyword_detect(message_serialization):
         set_result(message, result)
Пример #2
0
    async def get_review(group: Group, member: Member, review_type: str,
                         target: str) -> MessageItem:
        group_id = group.id
        member_id = member.id
        time = datetime.now()
        time_right = time.strftime("%Y-%m-%d %H:%M:%S")
        if review_type == "year":
            timep = time - relativedelta(years=1)
            time_left = (time -
                         relativedelta(years=1)).strftime("%Y-%m-%d %H:%M:%S")
            tag = "年内"
        elif review_type == "month":
            timep = time - relativedelta(months=1)
            time_left = (time -
                         relativedelta(years=1)).strftime("%Y-%m-%d %H:%M:%S")
            tag = "月内"
        else:
            return MessageItem(
                MessageChain.create(
                    [Plain(text="Error: review_type invalid!")]),
                QuoteSource(GroupStrategy()))

        sql = select(ChatRecord).where(
            ChatRecord.group_id == group_id,
            ChatRecord.member_id == member_id if target == "member" else True,
            ChatRecord.time < time, ChatRecord.time > timep)

        if not (res := list(orm.fetchall(sql))):
            return MessageItem(MessageChain.create([Plain(text="没有你的发言记录呐~")]),
                               QuoteSource(GroupStrategy()))
 async def handle(self, app: GraiaMiraiApplication, message: MessageChain,
                  group: Group, member: Member):
     message_text = message.asDisplay()
     if re.match(r"super .*:[\n\r]+[\s\S]*", message_text):
         await update_user_call_count_plus1(group, member,
                                            UserCalledCount.functions,
                                            "functions")
         if not await get_setting(group.id, "compile"):
             return MessageItem(
                 MessageChain.create([Plain(text="网络编译器功能关闭了呐~去联系管理员开启吧~")
                                      ]), Normal(GroupStrategy()))
         language = re.findall(r"super (.*?):", message_text, re.S)[0]
         code = message_text[8 + len(language):]
         result = await self.network_compiler(group, member, language, code)
         if isinstance(result, str):
             return MessageItem(MessageChain.create([Plain(text=result)]),
                                QuoteSource(GroupStrategy()))
         else:
             return MessageItem(
                 MessageChain.create([
                     Plain(text=result["output"]
                           if result["output"] else result["errors"])
                 ]), QuoteSource(GroupStrategy()))
     else:
         return await super().handle(app, message, group, member)
Пример #4
0
 async def update_keyword(message_serialization: str) -> MessageItem:
     _, function, keyword = message_serialization.split("#")
     if re.match(r"\[mirai:image:{.*}\..*]", keyword):
         keyword = re.findall(r"\[mirai:image:{(.*?)}\..*]", keyword,
                              re.S)[0]
     if function not in ImageSenderHandler.functions:
         return MessageItem(MessageChain.create([Plain(text="非法方法名!")]),
                            QuoteSource(GroupStrategy()))
     try:
         await orm.insert_or_ignore(TriggerKeyword, [
             TriggerKeyword.keyword == keyword, TriggerKeyword.function
             == function
         ], {
             "keyword": keyword,
             "function": function
         })
         return MessageItem(
             MessageChain.create(
                 [Plain(text=f"关键词添加成功!\n{keyword} -> {function}")]),
             QuoteSource(GroupStrategy()))
     except Exception:
         logger.error(traceback.format_exc())
         return MessageItem(
             MessageChain.create([Plain(text="发生错误!请查看日志!")]),
             QuoteSource(GroupStrategy()))
Пример #5
0
async def grant_permission_process(group_id: int, member_id: int,
                                   new_level: int) -> MessageItem:
    if await grant_permission(group_id, member_id, new_level):
        return MessageItem(
            MessageChain.create([
                Plain(text=f"修改成功!\n{member_id} permission level: {new_level}")
            ]), Normal(GroupStrategy()))
    else:
        return MessageItem(MessageChain.create([Plain(text="出现错误,请查看日志!")]),
                           QuoteSource(GroupStrategy()))
    async def get_steam_game_search(group: Group, member: Member,
                                    keyword: str) -> MessageItem:
        url = "https://steamstats.cn/api/steam/search?q=%s&page=1&format=json&lang=zh-hans" % keyword
        headers = {
            "accept":
            "application/json, text/plain, */*",
            "accept-encoding":
            "gzip, deflate, br",
            "accept-language":
            "zh-CN,zh;q=0.9,zh-TW;q=0.8,en-US;q=0.7,en;q=0.6",
            "pragma":
            "no-cache",
            "referer":
            "https://steamstats.cn/",
            "sec-fetch-dest":
            "empty",
            "sec-fetch-mode":
            "cors",
            "sec-fetch-site":
            "same-origin",
            "user-agent":
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36"
        }

        async with aiohttp.ClientSession() as session:
            async with session.get(url=url, headers=headers) as resp:
                result = await resp.json()

        if len(result["data"]["results"]) == 0:
            return MessageItem(
                MessageChain.create([
                    Plain(text=f"搜索不到{keyword}呢~检查下有没有吧~偷偷告诉你,搜英文名的效果可能会更好哟~")
                ]), QuoteSource(GroupStrategy()))
        else:
            result = result["data"]["results"][0]
            async with aiohttp.ClientSession() as session:
                async with session.get(url=result["avatar"]) as resp:
                    img_content = await resp.read()
            description = await SteamGameInfoSearchHandler.get_steam_game_description(
                result["app_id"])
            return MessageItem(
                MessageChain.create([
                    Plain(text="\n搜索到以下信息:\n"),
                    Plain(text="游戏:%s (%s)\n" %
                          (result["name"], result["name_cn"])),
                    Plain(text="游戏id:%s\n" % result["app_id"]),
                    Image.fromUnsafeBytes(img_content),
                    Plain(text="游戏描述:%s\n" % description),
                    Plain(
                        text="\nSteamUrl:https://store.steampowered.com/app/%s/"
                        % result["app_id"])
                ]), QuoteSource(GroupStrategy()))
Пример #7
0
    async def delete_keyword(app: GraiaMiraiApplication, group: Group,
                             member: Member,
                             message_serialization: str) -> MessageItem:
        _, keyword = message_serialization.split("#")
        if re.match(r"\[mirai:image:{.*}\..*]", keyword):
            keyword = re.findall(r"\[mirai:image:{(.*?)}\..*]", keyword,
                                 re.S)[0]
        if record := await orm.fetchone(
                select(TriggerKeyword.function).where(
                    TriggerKeyword.keyword == keyword)):
            await app.sendGroupMessage(
                group,
                MessageChain.create([
                    Plain(
                        text=f"查找到以下信息:\n{keyword} -> {record[0]}\n是否删除?(是/否)")
                ]))
            inc = InterruptControl(AppCore.get_core_instance().get_bcc())

            @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="非预期回复,进程退出")]),
                    Normal(GroupStrategy()))
            elif result == "是":
                try:
                    await orm.delete(TriggerKeyword,
                                     [TriggerKeyword.keyword == keyword])
                except:
                    logger.error(traceback.format_exc())
                    return MessageItem(
                        MessageChain.create([Plain(text="发生错误!请查看日志!")]),
                        QuoteSource(GroupStrategy()))
                return MessageItem(
                    MessageChain.create([Plain(text=f"关键词 {keyword} 删除成功")]),
                    Normal(GroupStrategy()))
            else:
                return MessageItem(MessageChain.create([Plain(text="进程退出")]),
                                   Normal(GroupStrategy()))
    async def get_bangumi_info(group: Group, member: Member,
                               keyword: str) -> MessageItem:
        headers = {
            "user-agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36"
        }
        url = "https://api.bgm.tv/search/subject/%s?type=2&responseGroup=Large&max_results=1" % parse.quote(
            keyword)
        async with aiohttp.ClientSession() as session:
            async with session.post(url=url, headers=headers) as resp:
                data = await resp.json()

        if "code" in data.keys() and data["code"] == 404 or not data["list"]:
            return MessageItem(
                MessageChain.create([Plain(text=f"番剧 {keyword} 未搜索到结果!")]),
                QuoteSource(GroupStrategy()))

        bangumi_id = data["list"][0]["id"]
        url = "https://api.bgm.tv/subject/%s?responseGroup=medium" % bangumi_id

        async with aiohttp.ClientSession() as session:
            async with session.post(url=url, headers=headers) as resp:
                data = await resp.json()

        name = data["name"]
        cn_name = data["name_cn"]
        summary = data["summary"]
        img_url = data["images"]["large"]
        score = data["rating"]["score"]
        rank = data["rank"] if "rank" in data.keys() else None
        rating_total = data["rating"]["total"]

        async with aiohttp.ClientSession() as session:
            async with session.get(url=img_url) as resp:
                img_content = await resp.read()

        message = MessageChain.create([
            Plain(text="查询到以下信息:\n"),
            Image.fromUnsafeBytes(img_content),
            Plain(text=f"名字:{name}\n\n中文名字:{cn_name}\n\n"),
            Plain(text=f"简介:{summary}\n\n"),
            Plain(text=f"bangumi评分:{score}(参与评分{rating_total}人)"),
            Plain(text=f"\n\nbangumi排名:{rank}" if rank else "")
        ])
        # print(message)
        return MessageItem(
            await MessageChainUtils.messagechain_to_img(message=message,
                                                        max_width=1080,
                                                        img_fixed=True),
            QuoteSource(GroupStrategy()))
Пример #9
0
 async def handle(app: GraiaMiraiApplication, message: MessageChain,
                  group: Group, member: Member):
     if message.asDisplay().startswith("说 "):
         text = ''.join([plain.text for plain in message.get(Plain)
                         ])[2:].replace(" ", ',')
         voice = await SpeakHandler.get_voice(text)
         if isinstance(voice, str):
             return MessageItem(MessageChain.create([Plain(text=voice)]),
                                QuoteSource(GroupStrategy()))
         elif isinstance(voice, bytes):
             voice_element = await app.uploadVoice(await
                                                   silkcoder.encode(voice))
             return MessageItem(MessageChain.create([voice_element]),
                                Normal(GroupStrategy()))
Пример #10
0
 async def handle(self, app: GraiaMiraiApplication, message: MessageChain,
                  group: Group, member: Member) -> bool:
     tasks = [
         func(app, message, group, member) for func in self.__other_handlers
     ]
     # for handler in self.__chain:
     #     if isinstance(handler, ChatRecordHandler):
     #         self.__chat_record_handler = handler
     #     if isinstance(handler, RepeaterHandler):
     #         repeat_handler = handler
     #     else:
     #         tasks.append(handler.handle(app, message, group, member))
     if self.__chat_record_handler:
         await self.__chat_record_handler.handle(app, message, group,
                                                 member)
     print(1)
     g = asyncio.gather(*tasks)
     try:
         await g
     except AsyncioTasksGetResult:
         g.cancel()
         return True
     except FrequencyLimitExceededDoNothing:
         g.cancel()
         return False
     except FrequencyLimitExceeded:
         g.cancel()
         set_result_without_raise(
             message,
             MessageItem(
                 MessageChain.create([
                     Plain(
                         text="Frequency limit exceeded every 10 seconds!")
                 ]), QuoteSource(GroupStrategy())))
         return True
     except FrequencyLimitExceededAddBlackList:
         g.cancel()
         set_result_without_raise(
             message,
             MessageItem(
                 MessageChain.create([Plain(text="检测到大量请求,警告一次,加入黑名单一小时!")
                                      ]), QuoteSource(GroupStrategy())))
         return True
     if self.__repeat_handler:
         try:
             await self.__repeat_handler.handle(app, message, group, member)
         except AsyncioTasksGetResult:
             return True
     return False
Пример #11
0
 async def handle(app: GraiaMiraiApplication, message: MessageChain,
                  group: Group, member: Member):
     if re.match(r"来点.+笑话", message.asDisplay()):
         keyword = message.asDisplay()[2:-2]
         if keyword in joke_non_replace.keys():
             return MessageItem(
                 MessageChain.create([
                     Plain(text=random.choice(joke_non_replace[keyword]))
                 ]), Normal(GroupStrategy()))
         else:
             return MessageItem(
                 MessageChain.create([
                     Plain(text=random.choice(jokes).replace(
                         "%name%", keyword))
                 ]), QuoteSource(GroupStrategy()))
Пример #12
0
 async def handle(app: GraiaMiraiApplication, message: MessageChain,
                  group: Group, member: Member):
     message_text = message.asDisplay()
     if message_text == "/chains":
         app_core = AppCore.get_core_instance()
         return MessageItem(
             MessageChain.create([
                 Plain(text="目前链序:\n    " + "\n    ".join([
                     handler.__name__
                     for handler in app_core.get_group_chain()
                 ]))
             ]), Normal(GroupStrategy()))
     elif message_text == "/help":
         return MessageItem(
             MessageChain.create([
                 Plain(
                     text=
                     "SAGIRI-BOT文档地址:http://doc.sagiri-web.com/web/#/51?page_id=284"
                 )
             ]), QuoteSource(GroupStrategy()))
     elif message_text == "!help":
         app_core = AppCore.get_core_instance()
         content = "目前已加载Handler:\n"
         index = 0
         for handler in app_core.get_group_chains():
             index = index + 1
             content += f"{index}. {handler.__name__}\n"
         content += "请回复 /help 序号来查看Handler描述"
         return MessageItem(MessageChain.create([Plain(text=content)]),
                            QuoteSource(GroupStrategy()))
     elif re.match(r"!help [0-9]+", message_text):
         chains = AppCore.get_core_instance().get_group_chains()
         length = len(chains)
         index = int(message_text[6:])
         if index > length:
             return MessageItem(
                 MessageChain.create([Plain(text="非法编号!请检查发送的信息!")]),
                 QuoteSource(GroupStrategy()))
         else:
             content = "Handler详情:\n"
             handler = chains[index - 1]
             content += f"名称:{handler.__name__}\n"
             content += f"描述:{handler.__description__}\n"
             content += f"使用方法:{handler.__usage__}"
             return MessageItem(MessageChain.create([Plain(text=content)]),
                                QuoteSource(GroupStrategy()))
     else:
         return None
Пример #13
0
    async def handle(self, app: GraiaMiraiApplication, message: MessageChain,
                     group: Group, member: Member):
        message_text = "".join([plain.text
                                for plain in message.get(Plain)]).strip()
        if message_text == "幻影" or message_text == "彩色幻影":
            await update_user_call_count_plus1(group, member,
                                               UserCalledCount.functions,
                                               "functions")
            if len(message.get(Image)) != 2:
                return MessageItem(
                    MessageChain.create(
                        [Plain(text="非预期图片数!请按照 `显示图 隐藏图` 顺序发送,一共两张图片")]),
                    QuoteSource(GroupStrategy()))
            else:
                display_img = message[Image][0]
                async with aiohttp.ClientSession() as session:
                    async with session.get(url=display_img.url) as resp:
                        display_img = IMG.open(BytesIO(await resp.read()))

                hide_img = message[Image][1]
                async with aiohttp.ClientSession() as session:
                    async with session.get(url=hide_img.url) as resp:
                        hide_img = IMG.open(BytesIO(await resp.read()))

                return await self.get_message(group, member, display_img,
                                              hide_img)
        else:
            return await super().handle(app, message, group, member)
Пример #14
0
 async def rub(operator_image: Union[int, str],
               target_image: Union[int, str]) -> MessageItem:
     user_locs = [(39, 91, 75, 75, 0), (49, 101, 75, 75, 0),
                  (67, 98, 75, 75, 0), (55, 86, 75, 75, 0),
                  (61, 109, 75, 75, 0), (65, 101, 75, 75, 0)]
     self_locs = [(102, 95, 70, 80, 0), (108, 60, 50, 100, 0),
                  (97, 18, 65, 95, 0), (65, 5, 75, 75, -20),
                  (95, 57, 100, 55, -70), (109, 107, 65, 75, 0)]
     frames = []
     self_img = await AvatarFunPicHandler.get_pil_avatar(operator_image)
     user_img = await AvatarFunPicHandler.get_pil_avatar(target_image)
     for i in range(6):
         frame = IMG.open(f'{os.getcwd()}/statics/RubFrames/frame{i}.png'
                          ).convert('RGBA')
         x, y, w, h, angle = user_locs[i]
         user_img_new = (await AvatarFunPicHandler.resize_img(
             user_img, w, h, angle)).convert("RGBA")
         frame.paste(user_img_new, (x, y), mask=user_img_new)
         x, y, w, h, angle = self_locs[i]
         self_img_new = (await AvatarFunPicHandler.resize_img(
             self_img, w, h, angle)).convert("RGBA")
         frame.paste(self_img_new, (x, y), mask=self_img_new)
         frames.append(frame)
     output = BytesIO()
     imageio.mimsave(output, frames, format='gif', duration=0.05)
     return MessageItem(
         MessageChain.create([Image.fromUnsafeBytes(output.getvalue())]),
         Normal(GroupStrategy()))
Пример #15
0
    async def handle(app: GraiaMiraiApplication, message: MessageChain,
                     group: Group, member: Member):
        if message.asDisplay() == "搜番":
            await update_user_call_count_plus1(group, member,
                                               UserCalledCount.search,
                                               "search")
            if not await get_setting(group.id, Setting.bangumi_search):
                return MessageItem(
                    MessageChain.create([Plain(text="搜番功能未开启呐~请联系管理员哦~")]),
                    Normal(GroupStrategy()))
            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

            bcc = AppCore.get_core_instance().get_bcc()
            inc = InterruptControl(bcc)
            start_time = time.time()
            await inc.wait(waiter)
            if image_get:
                logger.success("收到用户图片,启动搜索进程!")
                try:
                    await app.sendGroupMessage(
                        group,
                        await BangumiSearchHandler.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
Пример #16
0
 async def wrapper(*args, **kwargs):
     member_id = -1
     group_id = -1
     for i in args:
         if isinstance(i, Member):
             member_id = i.id
         if isinstance(i, Group):
             group_id = i.id
     if member_id == -1 or group_id == -1 or not await get_setting(group_id, Setting.frequency_limit):
         if asyncio.iscoroutinefunction(func):
             return await func(*args, **kwargs)
         return func(*args, **kwargs)
     frequency_limit_instance = GlobalFrequencyLimitDict()
     await frequency_limit_instance.add_record(group_id, member_id, weight)
     if frequency_limit_instance.blacklist_judge(group_id, member_id):
         if not frequency_limit_instance.announce_judge(group_id, member_id):
             await frequency_limit_instance.blacklist_announced(group_id, member_id)
             return MessageItem(MessageChain.create([Plain(text="检测到大量请求,加入黑名单一小时!")]), QuoteSource(GroupStrategy()))
         else:
             return MessageItem(MessageChain.create([Plain("")]), DoNoting(GroupStrategy()))
     if frequency_limit_instance.get(group_id, member_id, func.__name__) + weight >= 10:
         return MessageItem(MessageChain.create([Plain(text="超过频率调用限制!")]), QuoteSource(GroupStrategy()))
     else:
         await frequency_limit_instance.update(group_id, weight)
         if asyncio.iscoroutinefunction(func):
             return await func(*args, **kwargs)
         return func(*args, **kwargs)
Пример #17
0
    async def get_abbreviation_explain(group: Group, member: Member,
                                       abbreviation: str) -> MessageItem:
        url = "https://lab.magiconch.com/api/nbnhhsh/guess"
        headers = {"referer": "https://lab.magiconch.com/nbnhhsh/"}
        data = {"text": abbreviation}

        async with aiohttp.ClientSession() as session:
            async with session.post(url=url, headers=headers,
                                    data=data) as resp:
                res = await resp.json()

        result = "可能的结果:\n\n"
        has_result = False
        for i in res:
            if "trans" in i:
                if i["trans"]:
                    has_result = True
                    result += f"{i['name']} => {','.join(i['trans'])}\n\n"
                else:
                    result += f"{i['name']} => 没找到结果!\n\n"
            else:
                if i["inputting"]:
                    has_result = True
                    result += f"{i['name']} => {','.join(i['inputting'])}\n\n"
                else:
                    result += f"{i['name']} => 没找到结果!\n\n"

        return MessageItem(
            MessageChain.create(
                [Plain(text=result if has_result else "没有找到结果哦~")]),
            QuoteSource(GroupStrategy()))
Пример #18
0
    async def get_github_trending(group: Group, member: Member) -> MessageItem:
        url = "https://github.com/trending"
        headers = {
            "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"
        }
        async with aiohttp.ClientSession() as session:
            async with session.get(url=url, headers=headers) as resp:
                html = await resp.read()
        soup = BeautifulSoup(html, "html.parser")
        articles = soup.find_all("article", {"class": "Box-row"})

        text_list = [f"随机数:{random.randint(0, 10000)}", "\ngithub实时热榜:\n"]
        index = 0
        for i in articles:
            try:
                index += 1
                title = i.find('h1').get_text().replace('\n', '').replace(
                    ' ', '').replace('\\', ' \\ ')
                text_list.append(f"\n{index}. {title}\n")
                text_list.append(f"\n    {i.find('p').get_text().strip()}\n")
            except Exception:
                pass

        text = "".join(text_list).replace("#", "")
        return MessageItem(MessageChain.create([Plain(text=text)]),
                           Normal(GroupStrategy()))
Пример #19
0
    async def handle(self, app: GraiaMiraiApplication, message: MessageChain,
                     group: Group, member: Member):
        if apps := message.get(App):
            app_json = json.loads(apps[0].content)
            if app_json[
                    "prompt"] == "[QQ小程序]哔哩哔哩" or "meta" in app_json and "detail_1" in app_json[
                        "meta"] and app_json["meta"]["detail_1"][
                            "title"] == "哔哩哔哩":
                short_url = app_json["meta"]["detail_1"]["qqdocurl"]

                async with aiohttp.ClientSession() as session:
                    async with session.get(url=short_url,
                                           allow_redirects=False) as resp:
                        result = (await resp.read()).decode("utf-8")
                bv_url = result.split("\"")[1].split("?")[0].split(
                    "/")[-1].strip()
                print(bv_url)

                bilibili_video_api_url = f"http://api.bilibili.com/x/web-interface/view?aid={self.bv_to_av(bv_url)}"

                async with aiohttp.ClientSession() as session:
                    async with session.get(url=bilibili_video_api_url) as resp:
                        result = (await resp.read()).decode('utf-8')
                result = json.loads(result)
                return MessageItem(await self.generate_messagechain(result),
                                   Normal(GroupStrategy()))

            else:
                return await super().handle(app, message, group, member)
Пример #20
0
 async def get_message(group: Group, member: Member, display_img: IMG,
                       hide_img: IMG):
     return MessageItem(
         MessageChain.create([
             Image.fromUnsafeBytes(await PhantomTankHandler.make_tank(
                 display_img, hide_img))
         ]), QuoteSource(GroupStrategy()))
Пример #21
0
    async def get_reply(member_id: int, group_id: int, content: str):
        if mode_now := list(orm.fetchone(select(Setting.speak_mode).where(Setting.group_id == group_id))):
            mode_now = mode_now[0][0]
            if mode_now == "normal":
                return None
            elif mode_now == "zuanLow":
                url = f"https://nmsl.shadiao.app/api.php?level=min&from={get_config('shadiaoAppName')}"
                async with aiohttp.ClientSession() as session:
                    async with session.get(url=url) as resp:
                        text = await resp.text()
            elif mode_now == "zuanHigh":
                url = f"https://nmsl.shadiao.app/api.php?from={get_config('shadiaoAppName')}"
                async with aiohttp.ClientSession() as session:
                    async with session.get(url=url) as resp:
                        text = await resp.text()
            elif mode_now == "rainbow":
                url = f"https://chp.shadiao.app/api.php?from={get_config('shadiaoAppName')}"
                async with aiohttp.ClientSession() as session:
                    async with session.get(url=url) as resp:
                        text = await resp.text()

            elif mode_now == "chat":
                text = await ChatReplyHandler.get_chat_reply(group_id, member_id, content)
            else:
                raise Exception(f"数据库群 <{group_id}> speak_mode项非法!目前值:{mode_now}")
            return MessageItem(MessageChain.create([Plain(text=text)]), AtSender(GroupStrategy()))
    async def formatted_output_bangumi(group: Group, member: Member,
                                       days: int) -> MessageItem:
        """
        Formatted output json data

        Args:
            days: The number of days to output(1-7)

        Examples:
            data_str = formatted_output_bangumi(7)

        Return:
            MessageChain
        """
        formatted_bangumi_data = await BiliBiliBangumiScheduleHandler.get_formatted_new_bangumi_json(
        )
        temp_output_substring = ["------BANGUMI------\n\n"]
        now = datetime.datetime.now()
        for index in range(days):
            temp_output_substring.append(now.strftime("%m-%d"))
            temp_output_substring.append("即将播出:")
            for data in formatted_bangumi_data[index]:
                temp_output_substring.append(
                    "\n%s %s %s\n" %
                    (data["pub_time"], data["title"], data["pub_index"]))
            temp_output_substring.append("\n\n----------------\n\n")
            now += datetime.timedelta(days=1)

        content = "".join(temp_output_substring)
        return MessageItem(
            await MessageChainUtils.messagechain_to_img(
                MessageChain.create([Plain(text=content)])),
            Normal(GroupStrategy()))
Пример #23
0
    async def handle(self, app: GraiaMiraiApplication, message: MessageChain,
                     group: Group, member: Member):
        group_id = group.id
        message_serialization = message.asSerializationString()
        message_serialization = message_serialization.replace(
            "[mirai:source:" + re.findall(r'\[mirai:source:(.*?)]',
                                          message_serialization, re.S)[0] +
            "]", "")
        if group_id in self.__group_repeat.keys():
            self.__group_repeat[group.id]["lastMsg"] = self.__group_repeat[
                group.id]["thisMsg"]
            self.__group_repeat[group.id]["thisMsg"] = message_serialization
            if self.__group_repeat[group.id]["lastMsg"] != self.__group_repeat[
                    group.id]["thisMsg"]:
                self.__group_repeat[group.id]["stopMsg"] = ""
            else:
                if self.__group_repeat[group.id][
                        "thisMsg"] != self.__group_repeat[group.id]["stopMsg"]:
                    self.__group_repeat[group.id][
                        "stopMsg"] = self.__group_repeat[group.id]["thisMsg"]
                    return MessageItem(message.asSendable(),
                                       Normal(GroupStrategy()))
        else:
            self.__group_repeat[group_id] = {
                "lastMsg": "",
                "thisMsg": message_serialization,
                "stopMsg": ""
            }

        return await super().handle(app, message, group, member)
Пример #24
0
 async def get_image_message(group: Group, member: Member,
                             func: str) -> MessageItem:
     if func == "setu18":
         r18_process = await get_setting(group.id, Setting.r18_process)
         if r18_process == "revoke":
             return MessageItem(
                 MessageChain.create(
                     [await ImageSenderHandler.get_pic(func)]),
                 Revoke(GroupStrategy()))
         elif r18_process == "flashImage":
             return MessageItem(
                 MessageChain.create([
                     (await ImageSenderHandler.get_pic(func)).asFlash()
                 ]), Normal(GroupStrategy()))
     return MessageItem(
         MessageChain.create([await ImageSenderHandler.get_pic(func)]),
         Normal(GroupStrategy()))
Пример #25
0
async def execute_setting_update(group: Group, member: Member,
                                 command: str) -> MessageItem:
    """
        setting -set setu=True real=True
        多命令执行
    """
    commands = command[13:].split(" ")
    error_commands = []
    success_commands = []
    for command in commands:
        try:
            command = command.strip()  # .replace("-", "")
            if not command:
                continue
            func, value = command.split("=")
            func = camel_to_underscore(func)
            value = (True if value == "True" else False) if value in [
                "True", "False"
            ] else value
            if func in command_index.keys():
                if command_index[func].is_valid(value):
                    """ update """
                    if await user_permission_require(
                            group, member, command_index[func].level):
                        try:
                            await orm.insert_or_update(
                                Setting, [Setting.group_id == group.id],
                                {func: value})
                            success_commands.append(f"{func} -> {value}")
                        except Exception as e:
                            error_commands.append((command, str(e)))
                            logger.error(traceback.format_exc())
                    else:
                        error_commands.append(
                            (command,
                             f"权限不足,要求权限等级{command_index[func].level}"))
                else:
                    error_commands.append((
                        f"{func} -> {value}",
                        f"期望值:{','.join([str(valid_value) for valid_value in command_index[func].valid_values])}"
                    ))
            else:
                error_commands.append((command, "未找到此命令"))
        except ValueError:
            error_commands.append((command, "格式非法!应为 func=value"))
    response_text = f"共解析{len(commands)}条命令,\n其中{len(success_commands)}条执行成功,{len(error_commands)}条失败"
    if success_commands:
        response_text += "\n\n成功命令:"
        for i in success_commands:
            response_text += f"\n{i}"
    if error_commands:
        response_text += "\n\n失败命令:"
        for i in error_commands:
            response_text += f"\n{i[0]} | {i[1]}"
    return MessageItem(MessageChain.create([Plain(text=response_text)]),
                       Normal(GroupStrategy()))
 async def get_result(group: Group, member: Member,
                      question: str) -> MessageItem:
     api_key = get_config("wolframAlphaKey")
     if api_key == "wolframAlphaKey":
         return MessageItem(
             MessageChain.create([Plain(text="尚未配置wolframAlphaKey!")]),
             QuoteSource(GroupStrategy()))
     url = f"https://api.wolframalpha.com/v1/simple?i={question.replace('+', '%2B')}&appid={api_key}"
     async with aiohttp.ClientSession() as session:
         async with session.get(url=url) as resp:
             if resp.status == 200:
                 res = await resp.read()
                 return MessageItem(
                     MessageChain.create([Image.fromUnsafeBytes(res)]),
                     QuoteSource(GroupStrategy()))
             else:
                 return MessageItem(
                     MessageChain.create([Plain(text=await resp.text())]),
                     QuoteSource(GroupStrategy()))
Пример #27
0
 async def format_output_notices(top: int = 10) -> MessageItem:
     data = await JLUCSWNoticeHandler.get_jlu_csw_notice(top)
     content = "----------------------------------\n"
     for i in range(10):
         content += f"{data[i]['title']}\n"
         content += f"{data[i]['href']}\n"
         content += f"                                        {data[i]['time'].replace('-', '.')}\n"
         content += "----------------------------------\n"
     return MessageItem(MessageChain.create([Plain(text=content)]),
                        Normal(GroupStrategy()))
Пример #28
0
 async def handle(self, app: GraiaMiraiApplication, message: MessageChain,
                  group: Group, member: Member):
     if message.asDisplay() == "舔":
         set_result(
             message,
             MessageItem(
                 MessageChain.create([
                     Plain(text=random.choice(pero_dog_contents).replace(
                         '*', ''))
                 ]), Normal(GroupStrategy())))
     else:
         return None
 async def handle(self, app: GraiaMiraiApplication, message: MessageChain,
                  group: Group, member: Member):
     if re.match("营销号#.*#.*#.*", message.asDisplay()):
         await update_user_call_count_plus1(group, member,
                                            UserCalledCount.functions,
                                            "functions")
         _, somebody, something, other_word = message.asDisplay().split("#")
         content = f"""{somebody}{something}是怎么回事呢?{somebody}相信大家都很熟悉,但是{somebody}{something}是怎么回事呢,下面就让小编带大家一起了解下吧。\n{somebody}{something},其实就是{somebody}{other_word},大家可能会很惊讶{somebody}怎么会{something}呢?但事实就是这样,小编也感到非常惊讶。\n这就是关于{somebody}{something}的事情了,大家有什么想法呢,欢迎在评论区告诉小编一起讨论哦!"""
         return MessageItem(MessageChain.create([Plain(text=content)]),
                            QuoteSource(GroupStrategy()))
     else:
         return await super().handle(app, message, group, member)
Пример #30
0
 async def get_zhihu_trending(group: Group, member: Member) -> MessageItem:
     zhihu_hot_url = "https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total?limit=50&desktop=true"
     async with aiohttp.ClientSession() as session:
         async with session.get(url=zhihu_hot_url) as resp:
             data = await resp.json()
     data = data["data"]
     text_list = [f"随机数:{random.randint(0, 10000)}", "\n知乎实时热榜:"]
     index = 0
     for i in data:
         index += 1
         text_list.append(f"\n{index}. {i['target']['title'].strip()}")
     text = "".join(text_list).replace("#", "")
     return MessageItem(MessageChain.create([Plain(text=text)]), Normal(GroupStrategy()))