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 group_message_handler( message: MessageChain, app: GraiaMiraiApplication, group: Group, member: Member, ): msgText = message.asDisplay() if msgText.startswith('/云图'): cloud = qunCloud(group.id) if msgText == '/云图': data = cloud.selectLastTime(dayCnt=0, timeType=2) cloud.solve(data) await app.sendGroupMessage( group, MessageChain.create( [At(member.id), Image.fromLocalFile('./res/1.png')])) elif msgText.split()[1] != '屏蔽词': data = cloud.getData(msgText) cloud.solve(data) await app.sendGroupMessage( group, MessageChain.create( [At(member.id), Image.fromLocalFile('./res/1.png')])) else: print(1) words = msgText.split()[2:] if msgText.split()[1] == '屏蔽词': if member.id == adminId: if words[0] == '全局': cloud.addGlobalStopWords(words[1:]) await app.sendGroupMessage( group, MessageChain.create([ At(member.id), Plain('\n全局屏蔽词添加成功\n' + str(words[1:])) ])) else: cloud.addQunStopWords(words) await app.sendGroupMessage( group, MessageChain.create([ At(member.id), Plain('\n屏蔽词添加成功\n' + str(words)) ])) else: await app.sendGroupMessage( group, MessageChain.create([At(member.id), Plain('\n权限不足\n')])) else: qqid = member.id qunid = group.id sendtime = int(time.time()) wordDB().insertvalue(msgText, qqid, qunid, sendtime)
async def AutoReply_Group_listener(message: MessageChain, app: GraiaMiraiApplication, group: Group, member: Member): if SearchSetting(group.id)["function"]["AutoReply"]: if member.id not in BlackId: MessageGet = AutoReply(message.asDisplay()) if MessageGet.startswith("./Menhera/"): await app.sendGroupMessage( group, MessageChain.create([Image.fromLocalFile(MessageGet)])) elif MessageGet == "": pass else: await app.sendGroupMessage( group, MessageChain.create([Plain(MessageGet)])) MessageGet = AutoVoice(message.asDisplay()) if MessageGet.startswith("./voice/"): await app.sendGroupMessage( group, MessageChain.create([Voice().fromLocalFile(MessageGet)])) elif MessageGet == "": pass slogan = re.findall('(.*)\n(.*).jpg', message.asDisplay()) # 在线P图 if slogan: upper = slogan[0][0] lower = slogan[0][1] await app.sendGroupMessage( group, MessageChain.create([ Image.fromNetworkAddress( "https://api.dihe.moe/5000choyen?upper=" + upper + "&lower=" + lower) ]))
async def pornhub_style_logo_generator(app: GraiaMiraiApplication, message: MessageChain, group: Group): try: _, left_text, right_text = message.asDisplay().split(" ") try: try: genImage(word_a=left_text, word_b=right_text).save("./modules/5000zhao/test.png") except TypeError: await app.sendGroupMessage( group, MessageChain.create([Plain(text="不支持的内容!不要给我一些稀奇古怪的东西!")])) return None await app.sendGroupMessage( group, MessageChain.create( [Image.fromLocalFile("./modules/5000zhao/test.png")])) except AccountMuted: pass except ValueError: try: await app.sendGroupMessage( group, MessageChain.create( [Plain(text="参数非法!使用格式:5000兆 text1 text2")])) except AccountMuted: pass
async def get_weibo_hot(group_id: int) -> list: weibo_hot_url = "http://api.weibo.cn/2/guest/search/hot/word" async with aiohttp.ClientSession() as session: async with session.get(url=weibo_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("\n%d.%s" % (index, i["word"])) text = "".join(text_list).replace("#", "") long_text_setting = await get_setting(group_id, "longTextType") if long_text_setting == "img": img = text2piiic(string=text, poster="", length=max(len(x) for x in text.split("\n"))) img.save("./statics/temp/tempWeibo.png") return [ "None", MessageChain.create( [Image.fromLocalFile("./statics/temp/tempWeibo.png")]) ] elif long_text_setting == "text": return ["None", MessageChain.create([Plain(text=text)])] else: return [ "None", MessageChain.create([Plain(text="数据库 longTextType 项出错!请检查!")]) ]
async def make_ph_style_logo(left_text: str, right_text: str) -> MessageChain: img_name = f'ph_{left_text}_{right_text}.png' out_put_path = f"./modules/PornhubStyleLogoGenerator/temp/{img_name}" if not os.path.exists("./modules/PornhubStyleLogoGenerator/temp"): os.mkdir("./modules/PornhubStyleLogoGenerator/temp") await combine_img(left_text, right_text, FONT_SIZE, out_put_path) return MessageChain.create([Image.fromLocalFile(out_put_path)])
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)
def setu(group,id): print('开始请求色图') id = str(id) gr = str(group) hsolv = id_data[id] outmsg = [(Plain("你没有剩余色图或其他错误"))] if group in cfg['sg'] or fr_data[id] >= 1: x = randint(0,setulen) filepach = str(filepachs[x]) filename = filepach.replace(setu_ + '/','') print("选中色图" + filepach) hsolvmax = cfg['hsolvmax'] if group in cfg['sg'] and hsolv <= hsolvmax: lstgr_data[id] = filename id_data[id] = id_data[id] + 1 stlist_data[id] = stlist_data[id] + 1 outmsg = [Image.fromLocalFile(filepach)] elif fr_data[id] >= 1: df = 'https://pixiv.lxns.org/i/' + filename for i in folders: df = df.replace('/' + str(i),'') df = df[:-7] if group == 0: lstfr_data[id] = filename else: lstgr_data[gr] = filename print(lstgr_data[gr]) fr_data[id] = fr_data[id] - 1 stlist_data[id] = stlist_data[id] + 1 savecfg() outmsg = [(Plain(df + "剩余色图:" + str(fr_data[id])))] return outmsg
async def get_clock_wallpaper_preview_list() -> list: """ Return clock wallpaper list Args: None Examples: clock_list = await get_clock_wallpaper_preview_list() Return: [ Plain, Image ] """ clock_wallpaper_preview_path = await get_config("clockWallpaperPreviewPath" ) msg_list = list() wallpaper_list = os.listdir(clock_wallpaper_preview_path) wallpaper_list.sort(key=lambda x: int(x[:-4])) index = 1 for i in wallpaper_list: msg_list.append(Plain(text="\n%s." % index)) msg_list.append(Image.fromLocalFile(clock_wallpaper_preview_path + i)) index += 1 return msg_list
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 portune(app, group: int, member: int, var, model=''): ''' uid = ev.user_id if not lmt.check(uid): await bot.finish(ev, f'你今天已经抽过签了,欢迎明天再来~', at_sender=True) lmt.increase(uid) model = 'DEFAULT' pic = drawing_pic(model) await bot.send(ev, pic, at_sender=True) ''' t = datetime.datetime.now() - datetime.timedelta(hours=4) if var[0].date() != t.date(): var = [t, '', {}] p = Plain('') if var[1] and var[2]: p = Plain('\n你今天已经抽过签了,这是你今天抽到的签,欢迎明天再来~\n') img = drawing_pic(var, model) img.save("./source/bak1.png") m = MessageChain.create( [At(member), p, Img.fromLocalFile("./source/bak1.png")]) m.__root__[0].display = '' await app.sendGroupMessage(group, m)
async def make_qrcode(content: str) -> list: img = qrcode.make(content) img.save("./statics/temp/tempQrcodeMaked.jpg") return [ "quoteSource", MessageChain.create( [Image.fromLocalFile("./statics/temp/tempQrcodeMaked.jpg")]) ]
async def get_personal_review(group_id: int, member_id: int, review_type: str) -> list: mask_path = f"./statics/wordCloud/PersonalCustomizationMask/{group_id}_{member_id}.jpg" time = datetime.datetime.now() year, month, day, hour, minute, second = time.strftime( "%Y %m %d %H %M %S").split(" ") if review_type == "year": yearp, monthp, dayp, hourp, minutep, secondp = ( time - relativedelta(years=1)).strftime("%Y %m %d %H %M %S").split(" ") tag = "年内" elif review_type == "month": yearp, monthp, dayp, hourp, minutep, secondp = ( time - relativedelta(months=1)).strftime("%Y %m %d %H %M %S").split(" ") tag = "月内" else: return [ "None", MessageChain.create([Plain(text="Error: review_type invalid!")]) ] sql = f"""SELECT * FROM chatRecord WHERE groupId={group_id} AND memberId={member_id} AND time<'{year}-{month}-{day} {hour}:{minute}:{second}' AND time>'{yearp}-{monthp}-{dayp} {hourp}:{minutep}:{secondp}'""" # print(sql) res = await execute_sql(sql) texts = [] for i in res: if i[4]: texts += i[4].split(",") else: texts.append(i[3]) print(texts) top_n = await count_words(texts, 20000) if os.path.exists(mask_path): await draw_word_cloud(top_n, mask_path) else: await draw_word_cloud(top_n) sql = f"""SELECT count(*) FROM chatRecord WHERE groupId={group_id} AND memberId={member_id} AND time<'{year}-{month}-{day} {hour}:{minute}:{second}' AND time>'{yearp}-{monthp}-{dayp} {hourp}:{minutep}:{secondp}'""" res = await execute_sql(sql) times = res[0][0] return [ "quoteSource", MessageChain.create([ Plain(text="记录时间:\n"), Plain(text=f"{yearp}-{monthp}-{dayp} {hourp}:{minutep}:{secondp}"), Plain(text="\n---------至---------\n"), Plain(text=f"{year}-{month}-{day} {hour}:{minute}:{second}"), Plain(text=f"\n自有记录以来,你一共发了{times}条消息\n下面是你的{tag}个人词云:\n"), Image.fromLocalFile("./statics/temp/tempWordCloud.png") ]) ]
async def get_steam_game_search(keyword: str, msg_type: str = "text") -> MessageChain: """ Return search result Args: keyword: Keyword to search(game name) msg_type: Type of MessageChain Examples: await get_steam_game_search("Monster Hunter") Return: MessageChain """ base_path = "./modules/SteamGameSearcher/game_cover_cache/" if not os.path.exists(base_path): os.mkdir(base_path) url = "https://steamstats.cn/api/steam/search?q=%s&page=1&format=json&lang=zh-hans" % keyword headers = { "referer": "https://steamstats.cn/", "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 MessageChain.create( [Plain(text=f"搜索不到{keyword}呢~检查下有没有吧~偷偷告诉你,搜英文名的效果可能会更好哟~")]) else: result = result["data"]["results"][0] path = f"{base_path}{result['app_id']}.png" print(f"cache: {os.path.exists(path)}") if not os.path.exists(path): async with aiohttp.ClientSession() as session: async with session.get(url=result["avatar"]) as resp: img_content = await resp.read() image = IMG.open(BytesIO(img_content)) image.save(path) description = await get_steam_game_description(result["app_id"]) msg = 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.fromLocalFile(path), Plain(text="游戏描述:%s\n" % description), Plain(text="\nsteamUrl:https://store.steampowered.com/app/%s/" % result["app_id"]) ]) return await messagechain_to_img(msg) if msg_type == "img" else msg
async def get_bangumi_info(sender: int, keyword: str) -> list: 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) print(url) 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: return [ "None", MessageChain.create([ At(target=sender), Plain(text="番剧 %s 未搜索到结果!" % keyword) ]) ] print(data) bangumi_id = data["list"][0]["id"] url = "https://api.bgm.tv/subject/%s?responseGroup=medium" % bangumi_id print(url) 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"] rating_total = data["rating"]["total"] save_base_path = await get_config("imgSavePath") path = save_base_path + "%s.jpg" % name if not os.path.exists(path): async with aiohttp.ClientSession() as session: async with session.get(url=img_url) as resp: img_content = await resp.read() image = IMG.open(BytesIO(img_content)) image.save(path) return [ "None", MessageChain.create([ At(target=sender), Plain(text="查询到以下信息:\n"), Image.fromLocalFile(path), Plain(text="名字:%s\n\n中文名字:%s\n\n" % (name, cn_name)), Plain(text="简介:%s\n\n" % summary), Plain(text="bangumi评分:%s(参与评分%s人)\n\n" % (score, rating_total)), Plain(text="bangumi排名:%s" % rank) ]) ]
async def get_jlu_csw_notice(group_id: int) -> list: """ Get JLU CSW notice Args: group_id: Group id Examples: msg = await get_jlu_csw_notice() Return: [ str: Auxiliary treatment to be done(Such as add statement), MessageChain: Message to be send(MessageChain) ] """ url = "https://api.sagiri-web.com/JLUCSWNotice/" async with aiohttp.ClientSession() as session: async with session.get(url=url) as resp: res = await resp.json() data = res["data"] 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" long_text_setting = await get_setting(group_id, "longTextType") if long_text_setting == "img": img = text2piiic(string=content, poster="", length=max(len(x) for x in content.split("\n"))) img.save("./statics/temp/tempJLUCSWNotice.png") return [ "None", MessageChain.create([ Image.fromLocalFile("./statics/temp/tempJLUCSWNotice.png") ]) ] elif long_text_setting == "text": return [ "None", MessageChain.create([ Plain(text=content) ]) ] else: return [ "None", MessageChain.create([ Plain(text="数据库 longTextType 项出错!请检查!") ]) ]
async def group_message_listener(app: GraiaMiraiApplication, group: Group, message: MessageChain, member: Member): if message.asDisplay() == "单抽": times = user.get_times(member.id) rarity, char = await gacha(times=times) await user.change(member.id, member.name, rarity, char) await app.sendGroupMessage( group, MessageChain.create([ Image.fromLocalFile("chars/{}/{}".format(rarity, char)), Plain( text="{}: {}".format(rarity_text_dict[rarity], char[:-4])) ])) elif message.asDisplay() == "十连": rarity_list, char_list = [], [] for i in range(10): times = user.get_times(member.id) rarity, char = await gacha(times=times) await user.change(member.id, member.name, rarity, char) rarity_list.append(rarity) char_list.append(char) result_file, result_str = await ten_img_make(rarity_list, char_list) await app.sendGroupMessage( group, MessageChain.create( [Image.fromUnsafeBytes(result_file), Plain(text=result_str)])) if "浊心斯卡蒂.png" in char_list: await app.sendGroupMessage( group, MessageChain.create( [Voice_LocalFile(filepath="浊心斯卡蒂_干员报到.amr")])) await app.sendGroupMessage( group, MessageChain.create([ Plain( text= "我在等你,博士。我等你太久,太久了,我甚至已经忘了为什么要在这里等你......不过这些都不重要了。不再那么重要了。" ) ])) elif message.asDisplay().startswith("查询"): await app.sendGroupMessage( group, MessageChain.create( [Plain(text=user.query(member.id, member.name))])) elif message.asDisplay() == "清除": user.delete(member.id) await app.sendGroupMessage( group, MessageChain.create([ Plain( text="号码: {}\n昵称: {}\n清除完成".format(member.id, member.name)) ]))
async def Schedule_Task(): UseTime = time.strftime('%H:%M', time.localtime(time.time())) if UseTime == "08:00": for i in range(len(ScheduleGroup)): await app.sendGroupMessage( ScheduleGroup[i], MessageChain.create([ Image.fromLocalFile("./Menhera/121.png"), Plain("早早早(*´▽`)ノノ") ])) elif UseTime == "12:00": for i in range(len(ScheduleGroup)): await app.sendGroupMessage( ScheduleGroup[i], MessageChain.create([ Image.fromLocalFile("./Menhera/44.jpg"), Plain("干饭时间到,开始干饭啦ヾ(^▽^*)))~") ])) elif UseTime == "23:00": for i in range(len(ScheduleGroup)): await app.sendGroupMessage( ScheduleGroup[i], MessageChain.create([ Image.fromLocalFile("./Menhera/122.png"), Plain("米娜桑,晚安( ̄o ̄) . z Z") ])) VideoDetail = None if VideoDetail is not None: VideoMessage = "你关注的UP主:" + VideoDetail[2] + "发布了新的视频:\n" + VideoDetail[ 0] + "\n视频链接:https://www.bilibili.com/video/" + VideoDetail[ 1] + "\n快去给他一个三连吧o(*////▽////*)q" for i in range(len(ScheduleGroup)): await app.sendGroupMessage( ScheduleGroup[i], MessageChain.create([ Image.fromNetworkAddress("http://" + VideoDetail[3]), Plain(VideoMessage) ])) global PerNumMessages PerNumMessages = 0 pass
def handle_type(result: dict) -> List: if result['type'] == 'text': return [Plain(result['return'])] elif result['type'] == 'image': return [ Image.fromLocalFile(result['return'], method=UploadMethods.Temp) ] elif result['type'] == 'error': return [Face(faceId=168), Plain(result['return'])] else: return []
def papi(url): headers = {} text = requests.get(url, headers=headers) data = json.loads(text.text) data = data['illusts'] outmsg = '' n = 0 msglist = [] for i in data: if n <= 6: r18 = 0 surl = i['image_urls']['medium'] tags = i['tags'] pid = i['id'] title = i['title'] print(type(title),title,':',tags) for i in tags: if i['name'].find('18') >=1: r18 = 1 if r18 == 0: srcfile= './' + str(pid) + "_p0_master1200.jpg" dstfile='./chace/s/' + str(pid) + "_p0_master1200.jpg" my_file = Path(dstfile) print(n,pid,'下载中') try: if my_file.is_file() == False: print(1) api.download(surl) print('下载完成') shutil.move(srcfile,dstfile) else: print('略过') except Exception: print('none') pass outmsg ='\n-' + str(n) + ':' + title msglist.append(Plain(outmsg)) msglist.append(Image.fromLocalFile(dstfile)) print('appdone') else: print(n,pid,'r18被屏蔽') outmsg ='\n-' + str(n) + ':' + title + '-r18图不显示预览' msglist.append(Plain(outmsg)) n = n + 1 else: break msglist.append(Plain('\n通过tp[id]来查看详细信息')) cfg['slist'] = data if cfg['slist'] == []: msglist = [(Plain('没有搜索结果'))] return msglist
async def get_setu_keyword(keyword: str) -> list: """ Search image by keyword Args: keyword: Keyword to search Examples: msg = await get_setu_keyword(keyword) Return: [ str: Auxiliary treatment to be done(Such as add statement), MessageChain: Message to be send(MessageChain) ] """ url = f"http://api.sagiri-web.com/setu/?keyword={keyword}" # print(url) async with aiohttp.ClientSession() as session: async with session.get(url=url) as resp: res = await resp.json() print(res) count = res["result count"] if count == 0: return [ "quoteSource", MessageChain.create([Plain(text="没有找到呢~可能还没有收录呢~也可能是你的XP系统太怪了叭(")]) ] data = res["data"][0] img_url = data["url"] # print(img_url) save_base_path = await get_config("setuPath") path = save_base_path + f"{data['pid']}_p{data['p']}.png" if not os.path.exists(path): async with aiohttp.ClientSession() as session: async with session.get(url=img_url) as resp: img_content = await resp.read() image = IMG.open(BytesIO(img_content)) image.save(path) return [ "quoteSource", MessageChain.create([ Plain(text=f"你要的{keyword}涩图来辣!\n"), Image.fromLocalFile(path), Plain(text=f"title:{data['title']}"), Plain(text=f"\nurl:{data['url']}\n") ]) ]
async def get_book_recommand_by_tag(tag: str) -> list: path = await getImagePath(tag) if path: return [ "quoteSource", MessageChain.create([Image.fromLocalFile(path)]) ] else: return [ "quoteSource", MessageChain.create([Plain(text=f"没有找到有关{tag}的图书呐~换个标签吧~")]) ]
async def AutoReply_Friend_listener(message: MessageChain, app: GraiaMiraiApplication, friend: Friend): MessageGet = AutoReply(message.asDisplay()) if MessageGet.startswith("./Menhera/"): await app.sendFriendMessage( friend, MessageChain.create([Image.fromLocalFile(MessageGet)])) elif MessageGet == "": pass else: await app.sendFriendMessage(friend, MessageChain.create([Plain(MessageGet)]))
async def get_review(group_id: int, member_id: int, review_type: str, target: str) -> MessageChain: time = datetime.datetime.now() year, month, day, hour, minute, second = time.strftime( "%Y %m %d %H %M %S").split(" ") if review_type == "year": yearp, monthp, dayp, hourp, minutep, secondp = ( time - relativedelta(years=1)).strftime("%Y %m %d %H %M %S").split(" ") tag = "年内" elif review_type == "month": yearp, monthp, dayp, hourp, minutep, secondp = ( time - relativedelta(months=1)).strftime("%Y %m %d %H %M %S").split(" ") tag = "月内" else: return MessageChain.create([Plain(text="Error: review_type invalid!")]) sql = f"""SELECT * FROM chatRecord WHERE groupId={group_id} {f'AND memberId={member_id}' if target == 'member' else ''} AND time<'{year}-{month}-{day} {hour}:{minute}:{second}' AND time>'{yearp}-{monthp}-{dayp} {hourp}:{minutep}:{secondp}'""" # print(sql) res = await execute_sql(sql) texts = [] for i in res: if i[4]: texts += i[4].split(",") else: texts.append(i[3]) print(texts) top_n = await count_words(texts, 20000) await draw_word_cloud(top_n) sql = f"""SELECT count(*) FROM chatRecord WHERE groupId={group_id} {f'AND memberId={member_id}' if target == 'member' else ''} AND time<'{year}-{month}-{day} {hour}:{minute}:{second}' AND time>'{yearp}-{monthp}-{dayp} {hourp}:{minutep}:{secondp}'""" res = await execute_sql(sql) times = res[0][0] return MessageChain.create([ Plain(text="记录时间:\n"), Plain(text=f"{yearp}-{monthp}-{dayp} {hourp}:{minutep}:{secondp}"), Plain(text="\n---------至---------\n"), Plain(text=f"{year}-{month}-{day} {hour}:{minute}:{second}"), Plain( text= f"\n自有记录以来,{'你' if target == 'member' else '本群'}一共发了{times}条消息\n下面是{'你的' if target == 'member' else '本群的'}{tag}词云:\n" ), Image.fromLocalFile(f"{BASE_PATH}tempWordCloud.png") ])
async def get_bangumi_info(keyword: str, sender: int) -> MessageChain: 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) # print(url) 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 MessageChain.create( [At(target=sender), Plain(text=f"番剧 {keyword} 未搜索到结果!")]) bangumi_id = data["list"][0]["id"] url = "https://api.bgm.tv/subject/%s?responseGroup=medium" % bangumi_id # print(url) async with aiohttp.ClientSession() as session: async with session.post(url=url, headers=headers) as resp: data = await resp.json() # print(data) 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"] path = f"./modules/BangumiInfoSearcher/bangumi_cover_cache/{name}.jpg" if not os.path.exists("./modules/BangumiInfoSearcher/bangumi_cover_cache"): os.mkdir("./modules/BangumiInfoSearcher/bangumi_cover_cache") if not os.path.exists(path): async with aiohttp.ClientSession() as session: async with session.get(url=img_url) as resp: img_content = await resp.read() image = IMG.open(BytesIO(img_content)) image.save(path) message = MessageChain.create([ Plain(text="查询到以下信息:\n"), Image.fromLocalFile(path), 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 "") ]) return await messagechain_to_img(message=message, max_width=1080, img_fixed=True)
async def search_pdf(keyword: str) -> MessageChain: url = f"https://zh.1lib.us/s/?q={keyword}" base_url = "https://zh.1lib.us" 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, # "download_href": base_url + download_href }) print(name, href, publisher, authors, sep="\n", end="\n\n") if not books: text = "未搜索到结果呢 >A<\n要不要换个关键词试试呢~" return MessageChain.create([Plain(text=text)]) text = text.replace("搜索到以下结果:\n\n", "") pics_path = await text2piiic_with_link(text=text) msg = [Plain(text="搜索到以下结果:\n\n")] for path in pics_path: msg.append(Image.fromLocalFile(path)) return MessageChain.create(msg)
async def formatted_output_bangumi(days: int, group_id: int) -> list: """ Formatted output json data Args: days: The number of days to output(1-7) group_id: Group id Examples: data_str = formatted_output_bangumi(7) Return: str: formatted """ formatted_bangumi_data = await 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("url:%s\n" % (data["url"])) temp_output_substring.append("\n\n----------------\n\n") now += datetime.timedelta(days=1) long_text_setting = await get_setting(group_id, "longTextType") content = "".join(temp_output_substring) if long_text_setting == "img": img = text2piiic( string=content, poster="", length=int( max(count_len(line) for line in content.split("\n")) / 2)) img.save("./statics/temp/tempBungumiTimeTable.png") return [ "None", MessageChain.create([ Image.fromLocalFile("./statics/temp/tempBungumiTimeTable.png") ]) ] elif long_text_setting == "text": return ["None", MessageChain.create([Plain(text=content)])] else: return [ "None", MessageChain.create([Plain(text="数据库 longTextType 项出错!请检查!")]) ]
async def keyword_reply(message_text: str): with open('./json/reply_keywords.json', 'r', encoding='utf-8') as f: # 从json读配置 keywords_dict = json.loads(f.read()) if message_text in keywords_dict.keys(): return [ "None", MessageChain.create([Plain(text=keywords_dict[message_text][1])]) ] if keywords_dict[message_text][0] == "text" else [ "None", MessageChain.create( [Image.fromLocalFile(keywords_dict[message_text][1])]) ] 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 petpet_generator(app: GraiaMiraiApplication, message: MessageChain, member: Member, group: Group): message_text = message.asDisplay() if message.has(At) and message_text.startswith( "摸") or message_text.startswith("摸 "): await petpet(message.get(At)[0].target) try: await app.sendGroupMessage( group, MessageChain.create([ Image.fromLocalFile( f"./plugins/PetPet/tempPetPet-{message.get(At)[0].target}.gif" ) ])) except AccountMuted: pass