async def update_vtb_list(): vtb_list = load_vtb_list() urls = [ "https://api.vtbs.moe/v1/short", "https://api.tokyo.vtbs.moe/v1/short", "https://vtbs.musedash.moe/v1/short", ] for url in urls: try: async with get_running(Adapter).session.get(url, timeout=10) as resp: result = await resp.json() if not result: continue vtb_list += result uid_list = list(set((info["mid"] for info in vtb_list))) vtb_list = list( filter(lambda info: info["mid"] in uid_list, vtb_list)) break except asyncio.TimeoutError: logger.warning(f"Get {url} timeout") dump_vtb_list(vtb_list)
async def get_question_content(questionTitleSlug, language="Zh"): url = "https://leetcode-cn.com/graphql/" headers = { "accept": "*/*", "accept-encoding": "gzip, deflate, br", "accept-language": "zh-CN,zh;q=0.9", "content-type": "application/json", "origin": "https://leetcode-cn.com", "referer": "https://leetcode-cn.com/problems/%s/" % questionTitleSlug, "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/84.0.4147.135 Safari/537.36", "x-definition-name": "question", "x-operation-name": "questionData", "x-timezone": "Asia/Shanghai" } payload = { "operationName": "questionData", "variables": { "titleSlug": "%s" % questionTitleSlug }, "query": "query questionData($titleSlug: String!) {\n question(titleSlug: $titleSlug) {\n " "questionId\n questionFrontendId\n boundTopicId\n title\n titleSlug\n content\n " " translatedTitle\n translatedContent\n isPaidOnly\n difficulty\n likes\n " "dislikes\n isLiked\n similarQuestions\n contributors {\n username\n " "profileUrl\n avatarUrl\n __typename\n }\n langToValidPlayground\n topicTags " "{\n name\n slug\n translatedName\n __typename\n }\n companyTagStats\n " " codeSnippets {\n lang\n langSlug\n code\n __typename\n }\n stats\n " " hints\n solution {\n id\n canSeeDetail\n __typename\n }\n status\n " " sampleTestCase\n metaData\n judgerAvailable\n judgeType\n mysqlSchemas\n " "enableRunCode\n envInfo\n book {\n id\n bookName\n pressName\n " "source\n shortDescription\n fullDescription\n bookImgUrl\n pressImgUrl\n " " productUrl\n __typename\n }\n isSubscribed\n isDailyQuestion\n " "dailyRecordStatus\n editorType\n ugcQuestionId\n style\n __typename\n }\n}\n " } async with get_running(Adapter).session.post( url=url, headers=headers, data=json.dumps(payload)) as resp: result = await resp.json() if language == "En": return result["data"]["question"]["content"] elif language == "Zh": return result["data"]["question"]["translatedContent"] else: return None
async def get_leetcode_user_statics(account_name: str) -> MessageChain: url = "https://leetcode-cn.com/graphql/" headers = { "origin": "https://leetcode-cn.com", "referer": "https://leetcode-cn.com/u/%s/" % account_name, "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/80.0.3987.100 Safari/537.36", "x-definition-name": "userProfilePublicProfile", "x-operation-name": "userPublicProfile", "content-type": "application/json" } payload = { 'operationName': "userPublicProfile", "query": "query userPublicProfile($userSlug: String!) {\n userProfilePublicProfile(userSlug: $userSlug) {\n " " username,\n haveFollowed,\n siteRanking,\n profile {\n userSlug,\n realName," "\n aboutMe,\n userAvatar,\n location,\n gender,\n websites," "\n skillTags,\n contestCount,\n asciiCode,\n medals {\n name," "\n year,\n month,\n category,\n __typename,\n }\n ranking {\n " " rating,\n ranking,\n currentLocalRanking,\n currentGlobalRanking," "\n currentRating,\n ratingProgress,\n totalLocalUsers,\n " "totalGlobalUsers,\n __typename,\n }\n skillSet {\n langLevels {\n " "langName,\n langVerboseName,\n level,\n __typename,\n }\n " "topics {\n slug,\n name,\n translatedName,\n __typename," "\n }\n topicAreaScores {\n score,\n topicArea {\n name," "\n slug,\n __typename,\n }\n __typename,\n }\n " " __typename,\n }\n socialAccounts {\n provider,\n profileUrl," "\n __typename,\n }\n __typename,\n }\n educationRecordList {\n " "unverifiedOrganizationName,\n __typename,\n }\n occupationRecordList {\n " "unverifiedOrganizationName,\n jobTitle,\n __typename,\n }\n submissionProgress {\n " " totalSubmissions,\n waSubmissions,\n acSubmissions,\n reSubmissions," "\n otherSubmissions,\n acTotal,\n questionTotal,\n __typename\n }\n " "__typename\n }\n}", 'variables': '{"userSlug": "%s"}' % account_name } async with get_running(Adapter).session.post( url=url, headers=headers, data=json.dumps(payload)) as resp: data_json = await resp.json() if 'userProfilePublicProfile' in data_json["data"].keys() \ and data_json["data"]['userProfilePublicProfile'] is None: return MessageChain(f"未找到 userSlug: {account_name}!") data_json = data_json['data']['userProfilePublicProfile'] profile = data_json['profile'] user_slug = profile['userSlug'] user_name = profile['realName'] ranking = data_json['siteRanking'] if ranking == 100000: ranking = "%s+" % ranking websites_list = profile['websites'] websites = [] for i in websites_list: websites.append("\n %s" % i) skills_list = profile['skillTags'] skills = [] for i in skills_list: skills.append("\n %s" % i) architecture = profile['skillSet']['topicAreaScores'][0]['score'] data_structures = profile['skillSet']['topicAreaScores'][1]['score'] algorithms = profile['skillSet']['topicAreaScores'][2]['score'] design = profile['skillSet']['topicAreaScores'][3]['score'] solved_problems = data_json['submissionProgress']['acTotal'] ac_submissions = data_json['submissionProgress']['acSubmissions'] total_question = data_json['submissionProgress']['questionTotal'] total_submissions = data_json['submissionProgress']['totalSubmissions'] submission_pass_rate = float(100 * ac_submissions / total_submissions) return MessageChain([ f"userSlug: {user_slug}\n", f" userName: {user_name}\n", f" ranking: {ranking}\n", f" websites: {''.join(websites)}\n", f" skills: {''.join(skills)}\n", " score:\n", f" architecture: {architecture}%\n", f" data-structures: {data_structures}%\n", f" algorithms: {algorithms}%\n", f" design: {design}%\n", f" solvedProblems: {solved_problems}/{total_question}\n", f" acSubmissions: {ac_submissions}\n", f" submissionPassRate: {submission_pass_rate}%", ])
async def get_thumb(url: str, proxy: str) -> bytes: async with get_running(Adapter).session.get(url, proxy=proxy) as resp: return await resp.read()
sql = ( select([func.count()]) .select_from(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(await orm.fetchone(sql))): return MessageChain("没有你的发言记录呐~") times = res[0] if mask: async with get_running(Adapter).session.get(url=mask.url) as resp: mask = IMG.open(BytesIO(await resp.read())) return MessageChain( [ Plain(text="记录时间:\n"), Plain(text=f"{time_left}"), Plain(text="\n---------至---------\n"), Plain(text=f"{time_right}"), Plain( text="\n自有记录以来," f"{'你' if target == 'member' else '本群'}" f"一共发了{times}条消息\n下面是" f"{'你的' if target == 'member' else '本群的'}" f"{review_type}词云:\n" ), Image(
async def color_card( app: Ariadne, group: Group, member: Member, message: MessageChain, help: RegexResult, size: RegexResult, mode: RegexResult, text: RegexResult, image: ElementResult, at: ElementResult, qq: RegexResult ): source = message.getFirst(Source) if help.matched: await app.sendGroupMessage( group, MessageChain( "ColorCard色卡插件\n" "在群中发送 `/色卡 {图片/@成员/qq号/回复有图片的消息}` 即可\n" "可选参数:\n" " -s/-size:色卡颜色个数,在群中发送 `/色卡 -s={size} {图片/@成员/qq号/回复有图片的消息}` 即可,默认值为5\n" " -m/-mode:色卡形式,在群中发送 `/色卡 -s={size} {图片/@成员/qq号/回复有图片的消息}` 即可,默认值为center,可选值及说明如下:\n" " pure:纯颜色\n" " below:在下方添加方形色块\n" " center:在图片中央添加圆形色块(自适应,若图片长>宽则为center_horizon,反之则为center_vertical)\n" " center_horizon:在图片中央水平添加圆形色块\n" " center_vertical:在图片中央垂直添加圆形色块\n" " -t/-text:是否在下方附加色块RGB即十六进制值文本,在群中发送 `/色卡 -t {图片/@成员/qq号/回复有图片的消息}` 即可\n" "上述参数可同步使用,并按照 -s、-m、-t的顺序添加,如 `/色卡 -s=10 -m=pure -t {图片/@成员/qq号/回复有图片的消息}`" ), quote=source ) return size = int(size.result.asDisplay().split('=')[1].strip()) if size.matched else 5 if size <= 0: await app.sendGroupMessage(group, MessageChain(f"蛤?size为{size}我还给你什么色卡阿,爪巴巴!"), quote=source) return elif size > 30: await app.sendGroupMessage(group, MessageChain(f"太多了啦,要溢出了!"), quote=source) return if mode.matched: mode = mode.result.asDisplay().split('=')[1].strip().lower() if mode == "center_vertical": mode = CardType.CENTER_VERTICAL elif mode == "center_horizon": mode = CardType.CENTER_HORIZON elif mode == "center": mode = CardType.CENTER elif mode == "pure": mode = CardType.PURE elif mode == "below": mode = CardType.BELOW_BLOCK else: await app.sendGroupMessage( group, MessageChain("mode参数错误!合法的参数如下:center_vertical、center_horizon、center、pure、below"), quote=source ) return else: mode = CardType.CENTER @Waiter.create_using_function(listening_events=[GroupMessage]) async def image_waiter( waiter_group: Group, waiter_member: Member, waiter_message: MessageChain ): if waiter_group.id == group.id and waiter_member.id == member.id: if waiter_message.has(Image): return await waiter_message.getFirst(Image).get_bytes() else: return False if image.matched: image_bytes = await image.result.get_bytes() elif at.matched or qq.matched: url = f'http://q1.qlogo.cn/g?b=qq&nk={at.result.target if at.matched else qq.result.asDisplay().strip()}&s=640' async with get_running(Adapter).session.get(url=url) as resp: image_bytes = await resp.read() else: try: if message.getFirst(Quote) and (await app.getMessageFromId(message.getFirst(Quote).id)).messageChain.get(Image): image_bytes = await (await app.getMessageFromId(message.getFirst(Quote).id)).messageChain.getFirst(Image).get_bytes() else: raise AttributeError() except (IndexError, AttributeError): try: await app.sendMessage(group, MessageChain("请在30s内发送要处理的图片"), quote=source) image_bytes = await asyncio.wait_for(inc.wait(image_waiter), 30) if not image_bytes: await app.sendGroupMessage(group, MessageChain("未检测到图片,请重新发送,进程退出"), quote=source) return except asyncio.TimeoutError: await app.sendGroupMessage(group, MessageChain("图片等待超时,进程退出"), quote=source) return result = await loop.run_in_executor(None, draw, image_bytes, mode, size) bytes_io = BytesIO() result[0].save(bytes_io, "PNG") if text.matched: await app.sendGroupMessage( group, MessageChain([ Image(data_bytes=bytes_io.getvalue()), Plain("\n"), Plain("\n".join([f"rgb{str(i).ljust(15, ' ')} #{''.join(hex(i[j]).upper()[2:] for j in range(3))}" for i in result[1]])) ]), quote=source ) else: await app.sendGroupMessage(group, MessageChain([Image(data_bytes=bytes_io.getvalue())]), quote=source)
async def aminer(app: Ariadne, group: Group, message: MessageChain, person: ArgResult, article: ArgResult, patent: ArgResult, keyword: RegexResult): if person.matched: router = "person" elif article.matched: router = "publication" elif patent.matched: router = "patent" else: router = "person" url = f"https://searchtest.aminer.cn/aminer-search/search/{router}" headers = {"Content-Type": "application/json"} data = { "query": keyword.result.asDisplay().strip(), "needDetails": True, "page": 0, "size": 5, "filters": [] } print(data) async with get_running(Adapter).session.post( url=url, headers=headers, data=json.dumps(data)) as resp: res = await resp.json() print(res) forward_nodes = [] if router == "person": persons = res["data"]["hitList"] time_count = -len(persons) for person in persons: institution = person["contact"]["affiliationZh"] if person[ "contact"].get("affiliationZh") else person['contact'].get( 'affiliation', '无数据') bio = person['contact']['bioZh'].replace( '<br>', '\n') if person["contact"].get( "bioZh") else person['contact'].get('bio', '无数据') edu = person['contact']['eduZh'].replace( '<br>', '\n') if person["contact"].get( "eduZh") else person['contact'].get('edu', '无数据') work = person['contact']['workZh'].replace( '<br>', '\n') if person["contact"].get( "workZh") else person['contact'].get('work', '无数据') forward_nodes.append( ForwardNode( senderId=config.bot_qq, time=datetime.now() + timedelta(seconds=time_count), senderName="纱雾酱", messageChain=MessageChain([ Image(data_bytes=TextEngine([ GraiaAdapter( MessageChain([ Image(url=person.get("avatar")) if person. get("avatar") else Plain(""), Plain("\n") if person.get("avatar" ) else Plain(""), Plain( f"英文名:{person.get('name', '无数据')}\n"), Plain( f"中文名:{person.get('nameZh', '无数据')}\n" ), Plain(f"所属机构:{institution}\n"), Plain( f"g-index:{person.get('gindex', '无数据')}\n" ), Plain( f"h-index:{person.get('hindex', '无数据')}\n" ), Plain( f"论文总数:{person.get('npubs', '无数据')}\n" ), Plain( f"被引用数:{person.get('ncitation', '无数据')}\n" ), Plain(bio), Plain(f"\n教育经历:\n{edu}"), Plain(f"\n工作(经历/职位):\n"), Plain(work), Plain("\n邮箱:\n"), Plain(person['contact'].get( 'email', '无数据').replace(';', '\n')) ])) ], min_width=1080).draw()) ]))) time_count += 1 elif router == "publication": pubs = res["data"]["hitList"] time_count = -len(pubs) for pub in pubs: title = pub['titleZh'] if pub.get("titleZh") else pub.get( "title", "无数据") authors = ", ".join([ i["nameZh"] if i.get("nameZh") else i.get("name", "无数据") for i in pub.get("authors", []) ]) create_data = pub.get("createDate", "无数据") keywords = ", ".join(pub["keywordsZh"] if pub.get("keywordsZh") else pub.get("keywords", [])) abstract = pub['pubAbstractZh'] if pub.get( "pubAbstractZh") else pub.get("pubAbstract", "无数据") forward_nodes.append( ForwardNode( senderId=config.bot_qq, time=datetime.now() + timedelta(seconds=time_count), senderName="纱雾酱", messageChain=MessageChain([ Image(data_bytes=TextEngine([ GraiaAdapter( MessageChain([ Plain(f"标题:{title[0]}\n"), Plain(f"作者:{authors}\n"), Plain(f"创建时间:{create_data}\n"), Plain( f"关键词:{keywords if keyword else '无数据'}\n" ), Plain(f"论文摘要:\n{abstract}") ])) ], min_width=1080).draw()) ]))) time_count += 1 elif router == "patent": patents = res["data"]["hitList"] time_count = -len(patents) for patent in patents: title = patent["title"].get("zh", patent["title"].get("en", "无数据")) inventors = ", ".join( [i.get("name", "无数据") for i in patent.get("inventor", [])]) assignees = ", ".join( [i.get("name", "无数据") for i in patent.get("assignees", [])]) abstract = patent.get("abstract", {}) abstract = abstract.get("zh", abstract.get("en", "无数据")) country = patent.get("country") pub_num = patent.get("pub_num") pub_kind = patent.get("pub_kind") pub_auth = country + pub_num + pub_kind if all( [country, pub_num, pub_kind]) else "无数据" forward_nodes.append( ForwardNode( senderId=config.bot_qq, time=datetime.now() + timedelta(seconds=time_count), senderName="纱雾酱", messageChain=MessageChain([ Image(data_bytes=TextEngine([ GraiaAdapter( MessageChain([ Plain(f"标题:{title}\n"), Plain(f"专利号:{pub_auth}\n"), Plain(f"发明人:{inventors}\n"), Plain(f"专利受让人:{assignees}\n"), Plain(f"专利摘要:\n{abstract}") ])) ], min_width=1080).draw()) ]))) time_count += 1 await app.sendGroupMessage(group, MessageChain([Forward(nodeList=forward_nodes)]), quote=message.getFirst(Source))
async def poisonous_chicken_soup(app: Ariadne, group: Group): url = f"https://api.shadiao.app/du" async with get_running(Adapter).session.get(url=url) as resp: text = (await resp.json())["data"].get("text", "未找到数据") await app.sendGroupMessage(group, MessageChain(text))