async def main(kwargs: dict): command = re.sub('^user ', '', kwargs['trigger_msg']) commandsplit = command.split(' ') mode = None metaurl = None username = None if Group in kwargs: id = kwargs[Group].id if Friend in kwargs: id = kwargs[Friend].id if '-r' in commandsplit: mode = '-r' commandsplit.remove('-r') command = ' '.join(commandsplit) if '-p' in commandsplit: mode = '-p' commandsplit.remove('-p') command = ' '.join(commandsplit) match_gpsite = re.match(r'~(.*?) (.*)', command) if match_gpsite: metaurl = f'https://{match_gpsite.group(1)}.gamepedia.com/api.php' username = match_gpsite.group(2) else: match_interwiki = re.match(r'(.*?):(.*)', command) if match_interwiki: if Group in kwargs: table = 'custom_interwiki_group' if Friend in kwargs: table = 'custon_interwiki_self' get_iw = get_custom_interwiki(table, id, match_interwiki.group(1)) if get_iw: metaurl = get_iw username = match_interwiki.group(2) else: if Group in kwargs: table = 'start_wiki_link_group' if Friend in kwargs: table = 'start_wiki_link_self' get_url = get_start_wiki(table, id) if get_url: metaurl = get_url username = command else: await sendMessage(kwargs, '未设置起始Interwiki。') result = await GetUser(metaurl, username, mode) if result: matchimg = re.match('.*\[\[uimgc:(.*)]]', result) if matchimg: if Group in kwargs: mth = UploadMethods.Group if Friend in kwargs: mth = UploadMethods.Friend imgchain = MessageChain.create([Image.fromLocalFile(matchimg.group(1), method=mth)]) result = re.sub('\[\[uimgc:.*]]', '', result) msgchain = MessageChain.create([Plain(result)]) msgchain = msgchain.plusWith(imgchain) else: msgchain = MessageChain.create([Plain(result)]) await sendMessage(kwargs, msgchain)
async def main(kwargs: dict): message = kwargs['trigger_msg'] message = message.split(' ') assets = os.path.abspath('assets/arcaea') if len(message) > 1: if message[1] == 'initialize': if database.check_superuser(kwargs): await arcb30init(kwargs) else: await sendMessage(kwargs, '权限不足') return else: if not os.path.exists(assets): msg = { 'text': '未找到资源文件!请放置一枚arcaea的apk到机器人的assets目录并重命名为arc.apk后,使用~b30 initialize初始化资源。' } else: msg = await getb30(message[1]) else: msg = {'text': '请输入好友码!~b30 <friendcode>'} if 'file' in msg: imgchain = MessageChain.create([Image.fromLocalFile(msg['file'])]) else: imgchain = False msgchain = MessageChain.create([Plain(msg['text'])]) if imgchain: msgchain = msgchain.plusWith(imgchain) await sendMessage(kwargs, msgchain)
async def set_start_wiki(kwargs: dict): if Group in kwargs: if check_permission(kwargs): command = kwargs['trigger_msg'] command = re.sub(r'^wiki_start_site ', '', command) check = await check_wiki_available(command) if check: result = database.add_start_wiki('start_wiki_link_group', kwargs[Group].id, check[0]) await sendMessage( kwargs, MessageChain.create([Plain(result + check[1])])) else: result = '错误:此Wiki不是一个有效的MediaWiki/尝试建立连接超时。' await sendMessage(kwargs, MessageChain.create([Plain(result)])) else: result = '你没有使用该命令的权限。' await sendMessage(kwargs, MessageChain.create([Plain(result)])) if Friend in kwargs: command = kwargs['trigger_msg'] command = re.sub(r'^wiki_start_site ', '', command) check = await check_wiki_available(command) if check: result = database.add_start_wiki('start_wiki_link_self', kwargs[Friend].id, check[0]) await sendMessage(kwargs, MessageChain.create([Plain(result + check[1])])) else: result = '错误:此Wiki不是一个有效的MediaWiki/尝试建立连接超时。' await sendMessage(kwargs, MessageChain.create([Plain(result)]))
async def reFriend(app: GraiaMiraiApplication, sender: Friend, message: MessageChain): text = message.asDisplay().strip().replace('\r\n', '\n').replace('\r', '\n') keywords = ['个人课表', '个人课程表', 'selfcourse', 'owncourse', 'self course', 'own course', 'privatecourse'] if any([text.lower().startswith(opt) for opt in ('.owncourse', '。owncourse', '.groupcourse', '。groupcourse')]): msg = await Command.parseCommand(text, qq=sender.id) if not msg: msg = '命令执行失败,请检查格式' await app.sendFriendMessage(sender, MessageChain.create([Plain(msg)])) elif (text.lower() in keywords) or at_me(app, message) and any(keyword in text.lower() for keyword in keywords): await app.sendFriendMessage(sender, MessageChain.create([await getCourseTable(f'qq{sender.id}')]))
async def interwiki(kwargs: dict): command = kwargs['trigger_msg'] command = re.sub(r'^interwiki ', '', command) command = command.split(' ') print(command) if Group in kwargs: check = check_permission(kwargs) if not check: result = '你没有使用该命令的权限,请联系管理员进行操作。' await sendMessage(kwargs, MessageChain.create([Plain(result)])) return table = 'custom_interwiki_' + kwargs[Target].target_from htable = 'request_headers_' + kwargs[Target].target_from target = kwargs[Target].id if command[0] in ['add', 'set']: command = ' '.join(command[1:]) command = re.sub(' ', '>', command) iw = command.split('>') if len(iw) == 1 or len(iw) > 2: await sendMessage(kwargs, '错误:命令不合法:~wiki iw add <interwiki> <url>') return check = await wikilib.wikilib().check_wiki_available( iw[1], headers=WikiDB.config_headers('get', htable, target)) if check[0]: result = WikiDB.config_custom_interwiki('add', table, target, iw[0], check[0]) await sendMessage( kwargs, MessageChain.create([Plain(result + f'{iw[0]} > {check[1]}')])) else: if check[1] == 'Timeout': result = '错误:尝试建立连接超时。' else: result = '错误:此站点也许不是一个有效的Mediawiki:' + check[1] link = re.match(r'^(https?://).*', iw[1]) if not link: result = '错误:所给的链接没有指明协议头(链接应以http://或https://开头)。' await sendMessage(kwargs, MessageChain.create([Plain(result)])) elif command[0] == 'del': result = WikiDB.config_custom_interwiki('del', table, target, command[1]) await sendMessage(kwargs, MessageChain.create([Plain(result)])) elif command[0] == 'list': query_database = WikiDB.get_custom_interwiki_list(table, target) if query_database: result = '当前设置了以下Interwiki:\n' + query_database await sendMessage(kwargs, result) else: await sendMessage( kwargs, '当前没有设置任何Interwiki,使用~wiki iw add <interwiki> <api_endpoint_link>添加一个。' ) else: await sendMessage(kwargs, '命令不合法,参数应为add/del/list。')
async def sendMsg(app: GraiaMiraiApplication, msg: MESSAGE_T, qq: int = None, group: int = None): if isinstance(msg, str): msg = MessageChain.create([Plain(msg)]) if isinstance(msg, ExternalElement): msg = MessageChain.create([msg]) msg = msg.asSendable() if qq: asyncio.create_task(app.sendFriendMessage(qq, msg)) if group: asyncio.create_task(app.sendGroupMessage(group, msg))
async def sendMessage(kwargs: dict, msgchain, Quote=True): """ 用于发送一条消息,兼容Group和Friend消息。 :param kwargs: 函数传入的dict :param msgchain: 消息链,若传入str则自动创建一条带有Plain元素的消息链 :param Quote: 是否引用传入dict中的消息(仅对Group消息有效) :return: 被发送的消息链 """ if isinstance(msgchain, str): if msgchain == '': msgchain = '发生错误:机器人尝试发送空文本消息,请联系机器人开发者解决问题。' msgchain = MessageChain.create([Plain(msgchain)]) QuoteTarget = None if 'TEST' not in kwargs: if Quote: QuoteTarget = kwargs[MessageChain][Source][0].id if Group in kwargs: send = await app.sendGroupMessage(kwargs[Group], msgchain, quote=QuoteTarget) return send if Friend in kwargs: send = await app.sendFriendMessage(kwargs[Friend], msgchain) return send if 'From' in kwargs: if kwargs['From'] == 'Group': send = await app.sendGroupMessage(kwargs['ID'], msgchain) return send if kwargs['From'] == 'Friend': send = await app.sendFriendMessage(kwargs['ID'], msgchain) return send if 'TEST' in kwargs: print(msgchain.asDisplay())
async def search(kwargs: dict, cmd: list): try: obj = cmd[1] result = await query( 'https://api.github.com/search/repositories?q=' + obj, 'json') items = result['items'] item_count_expected = int( result['total_count']) if result['total_count'] < 5 else 5 items_out = [] for item in items: try: items_out.append( str(item['full_name'] + ': ' + item['html_url'])) except TypeError: continue footnotes = f"另有 {result['total_count'] - 5} 个结果未显示。" if item_count_expected == 5 else '' msg = f"搜索成功:共 {result['total_count']} 个结果。\n" + '\n'.join( items_out[0:item_count_expected]) + f'\n{footnotes}' is_dirty = await dirty_check(msg) or await darkCheck(msg) if is_dirty: msg = 'https://wdf.ink/6OUp' await sendMessage(kwargs, MessageChain.create([Plain(msg)])) except Exception as error: await sendMessage(kwargs, '发生错误:' + str(error)) traceback.print_exc()
async def bedrock_dungeons(): url = 'https://bugs.mojang.com/rest/api/2/project/11901/versions' try: version_file = os.path.abspath( './assets/mcversion_jira-dungeons.txt') logger_info('Checking Jira mcv-bedrock...') verlist = getfileversions(version_file) file = await get_data(url, 'json') release = [] for v in file: if not v['archived']: release.append(v['name']) for x in release: if x not in verlist: logger_info(f'huh, we find {x}.') for qqgroup in check_enable_modules_all( 'group_permission', 'mcv_jira_rss'): try: await app.sendGroupMessage( int(qqgroup), MessageChain.create([ Plain( f'Jira已更新Dungeons {x}。\n(Jira上的信息仅作版本号预览用,不代表商店已更新此版本)' ) ])) await asyncio.sleep(0.5) except Exception: traceback.print_exc() for qqfriend in check_enable_modules_all( 'friend_permission', 'mcv_jira_rss'): try: await app.sendFriendMessage( int(qqfriend), MessageChain.create([ Plain( f'Jira已更新Dungeons {x}。\n(Jira上的信息仅作版本号预览用,不代表启动器已更新此版本)' ) ])) await asyncio.sleep(0.5) except Exception: traceback.print_exc() addversion = open(version_file, 'a') addversion.write('\n' + x) addversion.close() logger_info('jira mcv-dungeons checked.') except Exception: traceback.print_exc()
async def bugtracker(kwargs: dict): msg = kwargs['trigger_msg'] msg = re.sub('bug ', '', msg) q = re.match(r'(.*)-(.*)', msg) if q: result = await bugtracker_get(q.group(1) + '-' + q.group(2)) msgchain = MessageChain.create([Plain(result)]) await sendMessage(kwargs, msgchain)
async def newbie(app): logger_info('Subbot newbie launched') url = 'https://minecraft-zh.gamepedia.com/api.php?action=query&list=logevents&letype=newusers&format=json' while True: try: file = await get_data(url, 'json') qq = [] for x in file['query']['logevents'][:]: qq.append(x['title']) while True: c = 'f' try: qqqq = await get_data(url, 'json') for xz in qqqq['query']['logevents'][:]: if xz['title'] in qq: pass else: s = await check([ UTC8(xz['timestamp'], 'onlytime') + '新增新人:' + xz['title'] ]) if s.find("<吃掉了>") != -1 or s.find( "<全部吃掉了>") != -1: await app.sendGroupMessage( 731397727, MessageChain.create([ Plain( s + '\n检测到外来信息介入,请前往日志查看所有消息。Special:日志?type=newusers' ) ]).asSendable()) else: await app.sendGroupMessage( 731397727, MessageChain.create([Plain(s) ]).asSendable()) c = 't' except Exception: pass if c == 't': break else: await asyncio.sleep(10) await asyncio.sleep(5) except Exception: traceback.print_exc()
async def main(kwargs: dict): command = re.sub('^user ', '', kwargs['trigger_msg']) commandsplit = command.split(' ') mode = None metaurl = None username = None id = kwargs[Target].id if '-r' in commandsplit: mode = '-r' commandsplit.remove('-r') command = ' '.join(commandsplit) if '-p' in commandsplit: mode = '-p' commandsplit.remove('-p') command = ' '.join(commandsplit) table = 'start_wiki_link_' + kwargs[Target].target_from get_url = WikiDB.get_start_wiki(table, id) if get_url: metaurl = get_url username = command else: await sendMessage(kwargs, '未设置起始wiki。') match_interwiki = re.match(r'(.*?):(.*)', command) if match_interwiki: table = 'custom_interwiki_' + kwargs[Target].target_from get_iw = WikiDB.get_custom_interwiki(table, id, match_interwiki.group(1)) if get_iw: metaurl = get_iw username = match_interwiki.group(2) result = await GetUser(metaurl, username, mode) if result: matchimg = re.match('.*\[\[uimgc:(.*)]]', result) if matchimg: imgchain = MessageChain.create( [Image.fromLocalFile(matchimg.group(1))]) result = re.sub('\[\[uimgc:.*]]', '', result) msgchain = MessageChain.create([Plain(result)]) msgchain = msgchain.plusWith(imgchain) else: msgchain = MessageChain.create([Plain(result)]) await sendMessage(kwargs, msgchain)
async def wrapper(message: MESSAGE_T, *, at_sender: bool = False): if isinstance(message, ExternalElement): message = MessageChain.create([message]) if isinstance(message, str): message = MessageChain.create([Plain(message)]) if at_sender: if isinstance(message, MessageChain): message = MessageChain.join( MessageChain.create([At(Sender.id)]), message) else: raise TypeError( f"not supported type for reply: {message.__class__.__name__}" ) message = message.asSendable() if event_type == "GroupMessage": await app.sendGroupMessage(sender.group, message) elif event_type == "FriendMessage": await app.sendFriendMessage(sender, message) else: raise ValueError("Not supported event type")
async def make_illust_message(illust: dict) -> MessageChain: """ 将给定illust按照模板转换为message :param illust: 给定illust :return: 转换后的message """ msg = Template(reply_pattern).render( title=Plain(illust["title"]), author=Plain(illust["user"]["name"]), author_id=Plain(illust["user"]["id"]), caption=Plain(illust["caption"]), tags=Plain(" ".join(map(lambda x: x["name"], illust["tags"]))), id=Plain(str(illust["id"])) ) illegal_tags = [] for tag in block_tags: if has_tag(illust, tag): illegal_tags.append(tag) if len(illegal_tags) > 0: block_msg = Template(block_message).render( tag=Plain(' '.join(illegal_tags)) ) if block_mode == "escape_img": return msg.plusWith(block_msg) elif block_mode == "fully_block": return block_msg else: raise ValueError("illegal block_mode value: " + block_mode) try: b = await cache_illust(illust) img_msg = MessageChain.create([Image.fromUnsafeBytes(b)]) except asyncio.TimeoutError: img_msg = MessageChain.create([Plain(download_timeout_message)]) except Exception as e: img_msg = MessageChain.create([Plain(f"{type(e)} {str(e)}")]) msg.plus(img_msg) return msg
async def set_start_wiki(kwargs: dict): command = kwargs['trigger_msg'] command = re.sub(r'^wiki_start_site ', '', command) if Group in kwargs: if not check_permission(kwargs): result = '你没有在群内使用该命令的权限,请联系管理员进行操作。' await sendMessage(kwargs, MessageChain.create([Plain(result)])) return check = await wikilib.wikilib().check_wiki_available(command) if check[0]: result = WikiDB.add_start_wiki('start_wiki_link_' + kwargs[Target].target_from, kwargs[Target].id, check[0]) await sendMessage(kwargs, MessageChain.create([Plain(result + check[1])])) else: if check[1] == 'Timeout': result = '错误:尝试建立连接超时。' else: result = '错误:此站点也许不是一个有效的Mediawiki:' + check[1] link = re.match(r'^(https?://).*', command) if not link: result = '错误:所给的链接没有指明协议头(链接应以http://或https://开头)。' await sendMessage(kwargs, MessageChain.create([Plain(result)]))
async def GroupMessageHandler(group: Group, member: Member, msgchain: MessageChain): Record.addMessage(ChatRecord(messagechain=msgchain, group=group, member=member)) if msgchain.has(Plain): text = msgchain.get(Plain)[0].text if text == '#词云生成': await app.sendGroupMessage(group, MessageChain.create( [At(member.id), Plain('生成中...')] )) await app.sendGroupMessage(group, MessageChain.create( [At(member.id), Image.fromLocalFile(wordCloudGenerator(Record.getAGroupMessageList(group.id)))] )) elif text == '#今日消息图表': await app.sendGroupMessage(group, MessageChain.create( [At(member.id), Plain('生成中...')] )) await app.sendGroupMessage(group, MessageChain.create( [At(member.id), Image.fromLocalFile(summaryGraphGenerator("today", Record.getAGroupMessageList(group.id)))] )) elif text == '#总消息图表': await app.sendGroupMessage(group, MessageChain.create( [At(member.id), Plain('生成中...')] )) await app.sendGroupMessage(group, MessageChain.create( [At(member.id), Image.fromLocalFile(summaryGraphGenerator("total", Record.getAGroupMessageList(group.id)))] ))
async def generate_reply( self, app: GraiaMiraiApplication, subject: T.Union[Group, Friend], message: MessageChain ) -> T.AsyncGenerator[T.Union[str, MessageChain], None]: mode = self.__find_ranking_mode(message) if mode is None: return begin, end = self.__find_ranges(message) logger.info(f"{self.tag}: [{mode}] [{begin}-{end}]") illusts = await get_illusts(search_func=papi.illust_ranking, mode=mode, search_item_limit=end) if isinstance(subject, Group): item_per_msg = self.item_per_group_message elif isinstance(subject, Friend): item_per_msg = self.item_per_friend_message else: raise TypeError( f"type(subject) expect Group or Friend, got {type(subject)}.") msg = MessageChain.create([]) item_cur_msg = 0 rank = begin for illust in illusts[begin - 1:]: msg.plus(self.__make_msg(rank, illust)) item_cur_msg = item_cur_msg + 1 if item_cur_msg == item_per_msg: yield msg msg = MessageChain.create([]) item_cur_msg = 0 rank = rank + 1 if item_cur_msg > 0: yield msg logger.info(f"{self.tag}: [{mode}] [{begin}-{end}] ok")
async def handle(self, app: GraiaMiraiApplication, subject: T.Union[Group, Friend], message: MessageChain, channel: asyncio.Queue) -> bool: mode = self.__find_ranking_mode(message) if mode is None: return False begin, end = self.__find_ranges(message) logger.info(f"{self.tag}: [{mode}] [{begin}-{end}]") illusts = await get_illusts(search_func=papi.illust_ranking, mode=mode, search_item_limit=end) if isinstance(subject, Group): item_per_msg = self.item_per_group_message elif isinstance(subject, Friend): item_per_msg = self.item_per_friend_message else: raise TypeError(f"type(subject) expect Group or Friend, got {type(subject)}.") msg = MessageChain.create([]) item_cur_msg = 0 rank = begin for illust in illusts[begin - 1:]: msg.plus(self.__make_msg(rank, illust)) item_cur_msg = item_cur_msg + 1 if item_cur_msg == item_per_msg: await channel.put(msg) msg = MessageChain.create([]) item_cur_msg = 0 rank = rank + 1 if item_cur_msg > 0: await channel.put(msg) logger.info(f"{self.tag}: [{mode}] [{begin}-{end}] ok") return True
async def regex_bugtracker(kwargs: dict): msg = kwargs[MessageChain].asDisplay() if msg.find('[Webhook]') != -1: return if msg[0] == '!': msg = re.sub('!', '', msg) msg = re.sub('bug ', '', msg) q = re.match(r'(.*)\-(.*)', msg) if q: result = await bugtracker_get(q.group(1) + '-' + q.group(2)) msgchain = MessageChain.create([Plain(result)]) await sendMessage(kwargs, msgchain) findlink = re.findall(r'(https://bugs.mojang.com/browse/.*?-\d*)', msg) for link in findlink: print(link) matchbug = re.match(r'https://bugs.mojang.com/browse/(.*?-\d*)', link) if matchbug: await sendMessage(kwargs, await bugtracker_get(matchbug.group(1)))
async def set_headers(kwargs: dict): command = kwargs['trigger_msg'] command = command.split(' ') if Group in kwargs: check = check_permission(kwargs) if not check: result = '你没有使用该命令的权限,请联系管理员进行操作。' await sendMessage(kwargs, MessageChain.create([Plain(result)])) return table = 'request_headers_' + kwargs[Target].target_from id = kwargs[Target].id do = command[0] if do == 'show': headers = WikiDB.config_headers(do, table, id) msg = f'当前设置了以下标头:\n{headers}\n如需自定义,请使用~wiki headers <set> <headers>,不同标头之间使用换行隔开。' else: msg = WikiDB.config_headers(do, table, id, ' '.join(command[1:])) await sendMessage(kwargs, msg)
async def check_news(): logger_info('Checking Minecraft news...') baseurl = 'https://www.minecraft.net' url = 'https://www.minecraft.net/content/minecraft-net/_jcr_content.articles.grid?tileselection=auto&tagsPath=minecraft:article/news,minecraft:article/insider,minecraft:article/culture,minecraft:article/merch,minecraft:stockholm/news,minecraft:stockholm/guides,minecraft:stockholm/deep-dives,minecraft:stockholm/merch,minecraft:stockholm/events,minecraft:stockholm/minecraft-builds,minecraft:stockholm/marketplace&offset=0&count=500&pageSize=10' async with aiohttp.ClientSession() as session: async with session.get(url) as resp: status = resp.status if status == 200: nws = json.loads(await resp.read())['article_grid'] for article in nws: default_tile = article['default_tile'] title = default_tile['title'] image = baseurl + default_tile['image']['imageURL'] desc = default_tile['sub_header'] link = baseurl + article['article_url'] date = article['publish_date'] q = database.check_exist(title) if not q: database.add_news(title, link, desc, image, date) articletext = f'Minecraft官网发布了新的文章:\n{title}\n{link}\n{desc}\n' msgchain = MessageChain.create([ Plain(articletext), Image.fromNetworkAddress(image) ]) for qqgroup in check_enable_modules_all( 'group_permission', 'minecraft_news'): try: await app.sendGroupMessage( int(qqgroup), msgchain) await asyncio.sleep(0.5) except Exception: traceback.print_exc() for qqfriend in check_enable_modules_all( 'friend_permission', 'minecraft_news'): try: await app.sendFriendMessage( int(qqfriend), msgchain) await asyncio.sleep(0.5) except Exception: traceback.print_exc() logger_info(articletext) logger_info('Minecraft news checked.') else: logger_info('Check minecraft news failed:' + status)
async def check_weekly(): logger_info('Checking MCWZH weekly...') result = json.loads(await get_url( 'https://minecraft.fandom.com/zh/api.php?action=parse&page=Minecraft_Wiki/weekly&prop=text|revid&format=json' )) html = result['parse']['text']['*'] text = re.sub(r'<p>', '\n', html) # 分段 text = re.sub(r'<(.*?)>', '', text, flags=re.DOTALL) # 移除所有 HTML 标签 text = re.sub(r'\n\n\n', '\n\n', text) # 移除不必要的空行 text = re.sub(r'\n*$', '', text) img = re.findall( r'(?<=src=")(.*?)(?=/revision/latest/scale-to-(width|height)-down/\d{3}\?cb=\d{14}?")', html) page = re.findall(r'(?<=<b><a href=").*?(?=")', html) sended_img = Image.fromNetworkAddress( img[0][0]) if img else Plain('\n(发生错误:图片获取失败)') msg = '发生错误:本周页面已过期,请联系中文 Minecraft Wiki 更新。' if page[0] == '/zh/wiki/%E7%8E%BB%E7%92%83' else '本周的每周页面:\n\n' + text + '\n图片:' + \ img[0][ 0] + '?format=original\n\n页面链接:https://minecraft.fandom.com' + \ page[ 0] + '\n每周页面:https://minecraft.fandom.com/zh/wiki/?oldid=' + str( result['parse']['revid']) chain = MessageChain.create([Plain(msg), sended_img]) for qqgroup in check_enable_modules_all('group_permission', 'weekly_rss'): try: await app.sendGroupMessage(int(qqgroup), chain) await asyncio.sleep(0.5) except Exception: traceback.print_exc() for qqfriend in check_enable_modules_all('friend_permission', 'weekly_rss'): try: await app.sendFriendMessage(int(qqfriend), chain) await asyncio.sleep(0.5) except Exception: traceback.print_exc() logger_info(msg) logger_info('Weekly checked.')
async def cytoid(kwargs: dict): command = kwargs['trigger_msg'] command = re.sub('cytoid ', '', command) command_split = command.split(' ') if command_split[0] == 'profile': kwargs['trigger_msg'] = re.sub(r'^profile ', '', command) await cytoid_profile(kwargs) if command_split[0] in ['b30', 'r30']: c = database.check_time(kwargs, 'cytoidrank', 300) if not c: database.write_time(kwargs, 'cytoidrank') uid = re.sub(r'^.*?30 ', '', command) img = await get_rating(uid, command_split[0]) if 'path' in img: await sendMessage( kwargs, MessageChain.create([Image.fromLocalFile(img['path'])])) if 'text' in img: await sendMessage(kwargs, img['text']) else: await sendMessage(kwargs, f'距离上次执行已过去{int(-c)}秒,本命令的冷却时间为300秒。')
async def reply(app: GraiaMiraiApplication, subject: T.Union[Group, Friend], message: T.Union[MessageChain, str], quote: T.Optional[T.Union[Source, int]]) -> T.NoReturn: """ 回复消息。 :param app: GraiaMiraiApplication实例 :param subject: 回复的对象 :param message: 回复的消息 :param quote: 引用回复的消息源 """ if isinstance(message, str): message = MessageChain.create([Plain(message)]) # 因为mirai-api-http的问题,不能并发传图不然容易车祸 if isinstance(subject, Group): await __reply_queue.do(partial(app.sendGroupMessage, group=subject, message=message, quote=quote)) elif isinstance(subject, Friend): await __reply_queue.do(partial(app.sendFriendMessage, target=subject, message=message, quote=quote)) else: raise TypeError(f"type(subject) expect Group or Friend, got {type(subject)}.")
async def cytoid_profile(kwargs: dict): if Group in kwargs: mth = UploadMethods.Group if Friend in kwargs: mth = UploadMethods.Friend name = kwargs['trigger_msg'] profile_url = 'http://services.cytoid.io/profile/' + name profile = json.loads(await get_url(profile_url)) if 'statusCode' in profile: if profile['statusCode'] == 404: await sendMessage(kwargs, '发生错误:此用户不存在。') return uid = profile['user']['uid'] nick = profile['user']['name'] if nick is None: nick = False avatar = profile['user']['avatar']['large'] basicExp = profile['exp']['basicExp'] levelExp = profile['exp']['levelExp'] totalExp = profile['exp']['totalExp'] currentLevel = profile['exp']['currentLevel'] nextLevelExp = profile['exp']['nextLevelExp'] rating = profile['rating'] grade = profile['grade'] grade = f'A: {grade["A"]}, B: {grade["B"]}, C: {grade["C"]}, D: {grade["D"]}, F: {grade["F"]}, S: {grade["S"]}, SS: {grade["SS"]}' text = f'UID: {uid}\n' + \ (f'Nickname: {nick}\n' if nick else '') + \ f'BasicExp: {basicExp}\n' + \ f'LevelExp: {levelExp}\n' + \ f'TotalExp: {totalExp}\n' + \ f'CurrentLevel: {currentLevel}\n' + \ f'NextLevelExp: {nextLevelExp}\n' + \ f'Rating: {rating}\n' + \ f'Grade: {grade}' msg = MessageChain.create( [Image.fromNetworkAddress(avatar, method=mth), Plain(text)]) await sendMessage(kwargs, msg)
async def weekly(kwargs: dict): try: result = json.loads(await get_url( 'https://minecraft.fandom.com/zh/api.php?action=parse&page=Minecraft_Wiki/weekly&prop=text|revid&format=json')) html = result['parse']['text']['*'] text = re.sub(r'<p>', '\n', html) # 分段 text = re.sub(r'<(.*?)>', '', text, flags=re.DOTALL) # 移除所有 HTML 标签 text = re.sub(r'\n\n\n', '\n\n', text) # 移除不必要的空行 text = re.sub(r'\n*$', '', text) img = re.findall(r'(?<=src=")(.*?)(?=/revision/latest/scale-to-(width|height)-down/\d{3}\?cb=\d{14}?")', html) page = re.findall(r'(?<=<b><a href=").*?(?=")', html) sended_img = Image.fromNetworkAddress(img[0][0]) if img else Plain('\n(发生错误:图片获取失败)') msg = '发生错误:本周页面已过期,请联系中文 Minecraft Wiki 更新。' if page[ 0] == '/zh/wiki/%E7%8E%BB%E7%92%83' else '本周的每周页面:\n\n' + text + '\n图片:' + \ img[0][ 0] + '?format=original\n\n页面链接:https://minecraft.fandom.com' + \ page[ 0] + '\n每周页面:https://minecraft.fandom.com/zh/wiki/?oldid=' + str( result['parse']['revid']) await sendMessage(kwargs, MessageChain.create([Plain(msg), sended_img])) except Exception as e: await sendMessage(kwargs, '发生错误:' + str(e))
async def process(messagePlain: str, group, member): """ 处理游戏进度 :param messagePlain :param group :param member """ global a, q if messagePlain == "exit": akinatorGame.hold = False akinatorGame.end = False if akinatorGame.end: # 评价结果 if messagePlain.lower() == "yes" or messagePlain.lower() == "y": await atri.app.sendGroupMessage(group, MessageChain.create( [ Plain("Yay") ] )) else: await atri.app.sendGroupMessage(group, MessageChain.create( [ Plain("Oof") ] )) akinatorGame.end = False if akinatorGame.hold and messagePlain in [ 'yes', 'y', '0', 'no', 'n', '1', 'i', 'idk', 'i dont know', "i don't know", '2', 'probably', 'p', '3', 'probably not', 'pn', '4' ]: # 分支过程中 a = messagePlain if a == "b": try: q = akinatorGame.aki.back() await atri.app.sendGroupMessage(group, MessageChain.create( [ Plain(q) ] )) except akinator.CantGoBackAnyFurther: pass else: q = akinatorGame.aki.answer(a) await atri.app.sendGroupMessage(group, MessageChain.create( [ Plain(q + "\n\t"), Plain(f"{akinatorGame.aki.progression}%") ] )) if akinatorGame.aki.progression > 99: # 给出结果 akinatorGame.hold = False akinatorGame.aki.win() await atri.app.sendGroupMessage(group, MessageChain.create( [ Plain( f"It's {akinatorGame.aki.first_guess['name']} ({akinatorGame.aki.first_guess['description']})! Was I correct?\n"), Image.fromNetworkAddress(akinatorGame.aki.first_guess['absolute_picture_path']) ] )) akinatorGame.end = True if messagePlain in akinatorGame.AkinatorCmd and not akinatorGame.hold: # start akinatorGame.end = False akinatorGame.hold = True await atri.app.sendGroupMessage(group, MessageChain.create( [ Plain("Please wait...\n" '''yes or y or 0 for YES no or n or 1 for NO i or idk or i dont know or i don't know or 2 for I DON’T KNOW probably or p or 3 for PROBABLY probably not or pn or 4 for PROBABLY NOT''' ), ] )) q = akinatorGame.aki.start_game("cn") await atri.app.sendGroupMessage(group, MessageChain.create( [ Plain(q + "\n\t"), Plain(f"{akinatorGame.aki.progression}%") ] ))
async def repo(kwargs: dict, cmd: list): try: try: obj = cmd[1].replace('@', '') except IndexError: obj = cmd[0].replace('@', '') result = await query('https://api.github.com/repos/' + obj, 'json') if 'message' in result and result['message'] == 'Not Found': raise RuntimeError('此仓库不存在。') elif 'message' in result and result['message']: raise RuntimeError(result['message']) name = result['full_name'] url = result['html_url'] rid = result['id'] lang = result['language'] fork = result['forks_count'] star = result['stargazers_count'] watch = result['watchers_count'] mirror = result['mirror_url'] rlicense = 'Unknown' if 'license' in result and result['license'] is not None: if 'spdx_id' in result['license']: rlicense = result['license']['spdx_id'] is_fork = result['fork'] created = result['created_at'] updated = result['updated_at'] parent = False website = result['homepage'] if website is not None: website = 'Website: ' + website + '\n' else: website = '' if mirror is not None: mirror = f' (This is a mirror of {mirror} )' else: mirror = False if is_fork: parent_name = result['parent']['name'] parent = f' (This is a fork of {parent_name} )' desc = result['description'] if desc is None: desc = '' else: desc = '\n' + result['description'] msg = f'''{name} ({rid}){desc} Language · {lang} | Fork · {fork} | Star · {star} | Watch · {watch} License: {rlicense} Created {time_diff(created)} ago | Updated {time_diff(updated)} ago {website}{url} ''' if mirror: msg += '\n' + mirror if parent: msg += '\n' + parent is_dirty = await dirty_check( msg, result['owner']['login']) or darkCheck(msg) if is_dirty: msg = 'https://wdf.ink/6OUp' await sendMessage(kwargs, MessageChain.create([Plain(msg)])) else: await sendMessage( kwargs, MessageChain.create([ Plain(msg), Image.fromNetworkAddress( 'https://opengraph.githubassets.com/c9f4179f4d560950b2355c82aa2b7750bffd945744f9b8ea3f93cc24779745a0/' + name) ])) except Exception as e: await sendMessage(kwargs, '发生错误:' + str(e)) traceback.print_exc()
async def user(kwargs: dict, cmd: list): try: obj = cmd[1] result = await query('https://api.github.com/users/' + obj, 'json') login = result['login'] name = result['name'] uid = result['id'] url = result['html_url'] utype = result['type'] if 'company' in result: company = result['company'] else: company = False following = result['following'] follower = result['followers'] repo = result['public_repos'] gist = result['public_gists'] is_staff = False if 'license' in result: if 'spdx_id' in result['license']: is_staff = result['license']['spdx_id'] if 'twitter_username' in result: twitter = result['twitter_username'] else: twitter = False created = result['created_at'] updated = result['updated_at'] if 'blog' in result: website = result['blog'] else: website = False if 'location' in result: location = result['location'] else: location = False hireable = False if 'hireable' in result: hireable = result['hireable'] optional = [] if hireable: optional.append('Hireable') if is_staff: optional.append('GitHub Staff') if company: optional.append('Work · ' + company) if twitter: optional.append('Twitter · ' + twitter) if website: optional.append('Site · ' + website) if location: optional.append('Location · ' + location) bio = result['bio'] if bio is None: bio = '' else: bio = '\n' + result['bio'] optional_text = '\n' + ' | '.join(optional) msg = f'''{login} aka {name} ({uid}){bio} Type · {utype} | Follower · {follower} | Following · {following} | Repo · {repo} | Gist · {gist}{optional_text} Account Created {time_diff(created)} ago | Latest activity {time_diff(updated)} ago {url} ''' is_dirty = await dirty_check(msg, login) or darkCheck(msg) if is_dirty: msg = 'https://wdf.ink/6OUp' await sendMessage(kwargs, MessageChain.create([Plain(msg)])) except Exception as error: await sendMessage(kwargs, '发生错误:' + str(error)) traceback.print_exc()
async def replyGroup(app: GraiaMiraiApplication, sender: Member, message: MessageChain): keywords = ['课程表', '.course', 'course'] text = message.asDisplay().strip().lower().replace('\r', '\n') if (text in keywords) or (at_me(app, message) and any([keyword in text for keyword in keywords])): msg = MessageChain.create([courseTable, Plain(timeTable)]) await app.sendGroupMessage(sender.group, msg)