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()))
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)
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)
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()))
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()))
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
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
async def handle(app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member): legal_type = ("setu", "setu18", "real", "realHighq", "wallpaper", "sketch") if re.match( r"添加(setu|setu18|real|realHighq|wallpaper|sketch)图片(\[图片])+", message.asDisplay()): if not user_permission_require(group, member, 2): return MessageItem( MessageChain.create([Plain(text="你没有权限,爬!")]), Normal(GroupStrategy())) 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(GroupStrategy())) if path := get_config(f"{image_type}Path"): if os.path.exists(path): try: await ImageAdderHandler.add_image( path, message.get(Image)) except Exception as e: logger.error(traceback.format_exc()) return MessageItem( MessageChain.create( [Plain(text="出错了呐~请查看日志/控制台输出!")]), Normal(GroupStrategy())) return MessageItem( MessageChain.create([ Plain( text=f"保存成功!共保存了{len(message.get(Image))}张图片!") ]), Normal(GroupStrategy())) else: return MessageItem( MessageChain.create([ Image.fromLocalFile( f"{os.getcwd()}/statics/error/path_not_exists.png" ) ]), QuoteSource(GroupStrategy())) else: return MessageItem( MessageChain.create( [Plain(text=f"无{image_type}Path项!请检查配置!")]), QuoteSource(GroupStrategy()))
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)
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()))
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)
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()))
async def handle(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 None
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()))
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 handle(app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member): message_text = message.asDisplay() if message_text == "我的月内总结": await update_user_call_count_plus1(group, member, UserCalledCount.functions, "functions") return await GroupWordCloudGeneratorHandler.get_review(group, member, "month", "member") elif message_text == "我的年内总结": await update_user_call_count_plus1(group, member, UserCalledCount.functions, "functions") return await GroupWordCloudGeneratorHandler.get_review(group, member, "year", "member") elif message_text == "本群月内总结": if await user_permission_require(group, member, 2): await update_user_call_count_plus1(group, member, UserCalledCount.functions, "functions") return await GroupWordCloudGeneratorHandler.get_review(group, member, "month", "group") else: return MessageItem(MessageChain.create([Plain(text="权限不足呢~爪巴!")]), QuoteSource(GroupStrategy())) elif message_text == "本群年内总结": if await user_permission_require(group, member, 2): await update_user_call_count_plus1(group, member, UserCalledCount.functions, "functions") return await GroupWordCloudGeneratorHandler.get_review(group, member, "year", "group") else: return MessageItem(MessageChain.create([Plain(text="权限不足呢~爪巴!")]), QuoteSource(GroupStrategy())) else: return None
async def pornhub_style_image_generator(group: Group, member: Member, message: MessageChain) -> MessageItem: message_text = message.asDisplay() if '/' in message_text or '\\' in message_text: return MessageItem(MessageChain.create([Plain(text="不支持 '/' 与 '\\' !")]), QuoteSource(GroupStrategy())) try: _, left_text, right_text = message_text.split(" ") except ValueError: return MessageItem(MessageChain.create([Plain(text="格式错误!使用方法:ph left right!")]), QuoteSource(GroupStrategy())) try: return MessageItem(await PornhubStyleUtils.make_ph_style_logo(left_text, right_text), Normal(GroupStrategy())) except OSError as e: if "[Errno 22] Invalid argument:" in str(e): return MessageItem(MessageChain.create([Plain(text="非法字符!")]), QuoteSource(GroupStrategy()))
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 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()))
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: if asyncio.iscoroutinefunction(func): return await func(*args, **kwargs) return func(*args, **kwargs) frequency_limit_instance = GlobalFrequencyLimitDict() 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): frequency_limit_instance.blacklist_announced( group_id, member_id) return MessageItem( MessageChain.create( [Plain(text="检测到大量请求,警告一次,加入黑名单一小时!")]), QuoteSource(GroupStrategy())) else: return MessageItem(MessageChain.create([]), DoNoting(GroupStrategy())) if frequency_limit_instance.get(group_id) + weight >= 10: return MessageItem( MessageChain.create([ Plain( text="Frequency limit exceeded every 10 seconds!") ]), QuoteSource(GroupStrategy())) else: frequency_limit_instance.update(group_id, weight) if asyncio.iscoroutinefunction(func): return await func(*args, **kwargs) return func(*args, **kwargs)
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()))
async def handle(app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member): if message.asDisplay().startswith("/merge "): await update_user_call_count_plus1(group, member, UserCalledCount.functions, "functions") elements = [ element for element in message.__root__ if (isinstance(element, Image) or isinstance(element, Plain)) ] elements[0].text = elements[0].text[7:] return MessageItem( await MessageChainUtils.messagechain_to_img( MessageChain.create(elements)), QuoteSource(GroupStrategy())) else: return None
async def transform_abstract_message(content: str) -> MessageItem: result = "" length = len(content) index = 0 while index < length: if index < length - 1 and (get_pinyin(content[index]) + get_pinyin( content[index + 1])) in emoji: result += emoji[get_pinyin(content[index]) + get_pinyin(content[index + 1])] index += 1 elif get_pinyin(content[index]) in emoji: result += emoji[get_pinyin(content[index])] else: result += content[index] index += 1 return MessageItem(MessageChain.create([Plain(text=result)]), QuoteSource(GroupStrategy()))
async def handle(self, app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member): if re.match(r"qrcode .+", message.asDisplay()): await update_user_call_count_plus1(group, member, UserCalledCount.functions, "functions") content = message.asDisplay()[7:] qrcode_img = qrcode.make(content) bytes_io = BytesIO() qrcode_img.save(bytes_io) set_result( message, MessageItem( MessageChain.create( [Image.fromUnsafeBytes(bytes_io.getvalue())]), QuoteSource(GroupStrategy()))) else: return None
async def search_pdf(group: Group, member: Member, keyword: str) -> MessageItem: url = f"https://2lib.org/s/?q={keyword}" base_url = "https://2lib.org" async with aiohttp.ClientSession() as session: async with session.get(url=url) as resp: html = await resp.read() soup = BeautifulSoup(html, "html.parser") divs = soup.find("div", { "id": "searchResultBox" }).find_all("div", {"class": "resItemBox resItemBoxBooks exactMatch"}) count = 0 books = [] text = "搜索到以下结果:\n\n" for div in divs: count += 1 if count > 5: break name = div.find("h3").get_text().strip() href = div.find("h3").find("a", href=True)["href"] first_div = div.find("table").find("table").find("div") publisher = first_div.get_text().strip() if re.search( '.*?title="Publisher".*?', str(first_div)) else None authors = div.find("div", {"class": "authors"}).get_text().strip() text += f"{count}.\n" text += f"名字:{name}\n" text += f"作者:{authors}\n" if authors else "" text += f"出版社:{publisher}\n" if publisher else "" text += f"页面链接:{base_url + href}\n\n" books.append({ "name": name, "href": base_url + href, "publisher": publisher, "authors": authors }) if not books: text = "未搜索到结果呢 >A<\n要不要换个关键词试试呢~" return MessageItem(MessageChain.create([Plain(text=text)]), QuoteSource(GroupStrategy()))
async def formula2img(str_latex, img_size=(5, 3), font_size=20) -> MessageItem: fig = plt.figure(figsize=img_size) ax = fig.add_axes([0, 0, 1, 1]) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.set_xticks([]) ax.set_yticks([]) plt.text(0.5, 0.5, str_latex, fontsize=font_size, verticalalignment='center', horizontalalignment='center') bytes_io = BytesIO() plt.savefig(bytes_io) return MessageItem( MessageChain.create([Image.fromUnsafeBytes(bytes_io.getvalue())]), QuoteSource(GroupStrategy()))
async def get_result(group: Group, member: Member, keyword: str) -> MessageItem: url = "https://api.jikipedia.com/go/search_definitions" headers = {"Content-Type": "application/json;charset=UTF-8"} payload = {"phrase": keyword, "page": 1} async with aiohttp.ClientSession() as session: async with session.post(url=url, headers=headers, data=json.dumps(payload)) as resp: result = await resp.json() result = result["data"][0] return MessageItem( MessageChain.create([ Plain(text=f"{result['term']['title']}\n\n"), Plain( text= f"标签:{'、'.join(tag['name'] for tag in result['tags'])}\n\n" ), Plain(text=f"释义:{result['content']}") ]), QuoteSource(GroupStrategy()))
async def handle(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): return await ImageSenderHandler.update_keyword( 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): return await ImageSenderHandler.delete_keyword( app, group, member, message_serialization) else: return MessageItem(MessageChain.create([Plain(text="权限不足,爬")]), QuoteSource(GroupStrategy())) if re.match(r"\[mirai:image:{.*}\..*]", message_serialization): message_serialization = re.findall(r"\[mirai:image:{(.*?)}\..*]", message_serialization, re.S)[0] if resp_functions := list(await orm.fetchall( select(TriggerKeyword.function).where( TriggerKeyword.keyword == message_serialization))): resp_functions = resp_functions[0] tfunc = None for function in resp_functions: if function in ImageSenderHandler.functions: tfunc = function break if not tfunc: return None else: await update_user_call_count_plus1( group, member, user_called_column_index[tfunc], user_called_name_index[tfunc]) if tfunc == "setu": if await get_setting(group.id, Setting.setu): if await get_setting(group.id, Setting.r18): return await ImageSenderHandler.get_image_message( group, member, "setu18") else: return await ImageSenderHandler.get_image_message( group, member, tfunc) else: return MessageItem( MessageChain.create( [Plain(text="这是正规群哦~没有那种东西的呢!lsp爬!")]), Normal(GroupStrategy())) elif tfunc == "realHighq": if await get_setting( group.id, Setting.real) and await get_setting( group.id, Setting.real_high_quality): return await ImageSenderHandler.get_image_message( group, member, tfunc) else: return MessageItem( MessageChain.create( [Plain(text="这是正规群哦~没有那种东西的呢!lsp爬!")]), Normal(GroupStrategy())) else: if await get_setting(group.id, setting_column_index[tfunc]): return await ImageSenderHandler.get_image_message( group, member, tfunc) else: return MessageItem( MessageChain.create( [Plain(text="这是正规群哦~没有那种东西的呢!lsp爬!")]), Normal(GroupStrategy()))
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())) else: return MessageItem( MessageChain.create([Plain(text="未找到关键词数据!请检查输入!")]), QuoteSource(GroupStrategy()))