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 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) ]))
def write_define(self, message: MessageChain): msg = message.asDisplay().split(' ', 3) if len(msg) == 2: Msg = '? 定义啥你倒是说啊' elif len(msg) == 3: try: del self.define_data[msg[2]] Msg = '定义清除成功' except KeyError: Msg = '没有这个定义啊喂' elif len(msg) == 4: if message.has(Image): image = Image() image.url = message.get(Image)[0].url data = [image.url] else: data = msg[3] if msg[2] in self.define_data: Msg = '定义覆盖成功' else: Msg = '定义成功' self.define_data[msg[2]] = data self.db.write_define_to_file(self.define_data) return Msg
async def live_handler(*args, bot: Bot, subject: Union[Member, Friend]): '''B站直播间开播订阅 用法: /live 房间号''' if len(args) == 0: msg = [] monitor_dict = readJSON(BILI_LIVE_JSON_PATH) if not isinstance(monitor_dict, dict): raise TypeError("Expected dict but found:", monitor_dict) for room_id, target in monitor_dict.items(): if room_id == "time": continue if (isinstance(subject, Member) and groupToStr(subject.group) in target) \ or (isinstance(subject, Friend) and subject.id in target): res = getLiveInfo(room_id) if isinstance(res, str): continue if res['isLive'] == 0: msg.append(Plain(res['name'] + " 未在直播.\n")) else: msg.append( Plain(res['name'] + " 正在直播 " + "[{}]{}\n{}".format( res["area_name"], res["title"], res["url"]))) msg.append(Image.fromNetworkAddress(res["keyframe"])) return MessageChain.create(msg) room_id = args[0] res = getLiveInfo(room_id) if isinstance(res, str): msg = [Plain("未找到该直播!")] logger.info("[LIVE]未找到该直播") else: monitor_dict = readJSON(BILI_LIVE_JSON_PATH) if not isinstance(monitor_dict, dict): raise TypeError("Expected dict but found:", monitor_dict) if room_id in monitor_dict.keys(): if isinstance(subject, Member) and groupToStr( subject.group) not in monitor_dict[room_id]: monitor_dict[room_id].append(groupToStr(subject.group)) elif isinstance(subject, Friend) and subject.id not in monitor_dict[room_id]: monitor_dict[room_id].append(subject.id) else: if isinstance(subject, Member): monitor_dict[room_id] = [groupToStr(subject.group)] elif isinstance(subject, Friend): monitor_dict[room_id] = [subject.id] updateJSON(BILI_LIVE_JSON_PATH, monitor_dict) if res['isLive'] == 0: msg = [Plain("已加入监视列表\n" + res['name'] + " 未在直播.")] else: msg = [ Plain("已加入监视列表\n" + res['name'] + " 正在直播 " + "[{}]{}\n{}".format( res["area_name"], res["title"], res["url"])), Image.fromNetworkAddress(res["keyframe"]) ] logger.info("[LIVE]返回成功") return MessageChain.create(msg)
async def save_img(image: Image) -> str: path = "./statics/temp/tempSavedImage.jpg" async with aiohttp.ClientSession() as session: async with session.get(url=image.url) as resp: img_content = await resp.read() image = IMG.open(BytesIO(img_content)) image.save(path) return path
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 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 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 xiaolaodi(app: GraiaMiraiApplication, group: Group, message: MessageChain, member: Member): if '小老弟' in message.asDisplay() and message.has(At): xiaolaodi = IMG.open(Path(__file__).parent/'小老弟.png') if (at_u := message.get(At)[0].target) == app.connect_info.account: text = '我哪里像小老弟了,小老弟' to = member.id user = at_u else: text = '' to = at_u user = member.id user_pic = f'http://q1.qlogo.cn/g?b=qq&nk={user}&s=640' to_pic = f'http://q1.qlogo.cn/g?b=qq&nk={to}&s=640' async with aiohttp.request("GET",user_pic) as r: user_pic = await r.read() user_pic = IMG.open(BytesIO(user_pic)) async with aiohttp.request("GET",to_pic) as r: to_pic = await r.read() to_pic = IMG.open(BytesIO(to_pic)) user_box = (18,9,87,78) to_box = (173,23,232,82) user_pic = user_pic.resize((user_box[2] - user_box[0], user_box[3] - user_box[1])) to_pic = to_pic.resize((to_box[2] - to_box[0], to_box[3] - to_box[1])) xiaolaodi.paste(user_pic,user_box) xiaolaodi.paste(to_pic,to_box) out = BytesIO() xiaolaodi.save(out, format='PNG') await app.sendGroupMessage(group, MessageChain.create([ Plain(text = text), Image.fromUnsafeBytes(out.getvalue())]))
async def Monitor(nickname: str, app: GraiaMiraiApplication, QQ_id: int, Group_id: int, blog_id_set: Set) -> List: ''' 每隔一段时间监控一次, 如有新微博,发送给指定群组, 并@指定人 ''' try: tempList = await raw_monitor(nickname, blog_id_set) except: tempList = [False, []] if tempList[0] is True: new_blog_list = tempList[1] msg_to_send = MessageChain.create([At(QQ_id)]) msg_st = "\n" msg_st += f"您关注的[ {nickname} ]有新动态哦, 请注意查收~~\n" msg_to_send.plus(MessageChain.create([Plain(msg_st)])) for blog in new_blog_list: try: msg_end = "" msg_end += "[Content] : \n{}\n".format(blog["blog_text"]) msg_end += "[Time] : {}\n".format(blog["blog_time"]) msg_end += "[Source] : {}\n".format(blog["source"]) msg_end += "[Likes] : {}\n".format(blog["attitudes_count"]) msg_end += "[Comments] : {}\n".format(blog["comments_count"]) msg_end += "[Reposts] : {}\n".format(blog["reposts_count"]) if blog["blog_imgs"].__len__() > 0: msg_to_send.plus( MessageChain.create([ Image.fromNetworkAddress(img) for img in blog["blog_imgs"] ])) msg_to_send.plus(MessageChain.create([Plain(msg_end)])) except: print("[发送错误, pos = 1]") await app.sendGroupMessage(Group_id, msg_to_send)
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 subscriptionCheckTask(self, app: Slave): while True: new_videos: list = await self.ripper.checkSubscriptionsUpdate() if new_videos: q2v = vrConfig.getConfig(self.ripper.ripper).get('quote2video') for video in new_videos: user_id = video[0] video_link = video[1] video_info = await self.ripper.getVideo(video_link) author = Plain(video_info['author'] + '\n') time = Plain(video_info['time']) public = '' if video_info['public'] else '隐藏' ty = Plain('提交' + public + ('视频' if video_info['video'] else '图片') + '\n') title = Plain(video_info['title'] + '\n') connector = await IwaraRipper.getConnector() img_byte = await request(url=video_info['thumbnail'], connector=connector) thumbnail = Image.fromUnsafeBytes(img_byte) info = Plain(f"\n{video_info['info']}\n" if video_info['info'] else '') link = Plain(self.ripper.host + video_info['url']) youtube = Plain('\nyoutube' if video_info['youtube'] else '') msg = [author, time, ty, title, thumbnail, info, link, youtube] qq = vrConfig.getConfig(self.ripper.ripper).get('qq') bot_msg = await app.sendFriendMessage(qq, MeCh.create(msg)) q2v[bot_msg.messageId] = [user_id, video_link] await vrConfig.save(self.ripper.ripper) else: logger.debug('nothing was post') await asyncio.sleep(30 * 60)
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 keyword_reply( app: GraiaMiraiApplication, message: MessageChain, group: Group ): message_serialization = message.asSerializationString() message_serialization = message_serialization.replace( "[mirai:source:" + re.findall(r'\[mirai:source:(.*?)]', message_serialization, re.S)[0] + "]", "" ) if re.match(r"\[mirai:image:{.*}\..*]", message_serialization): message_serialization = re.findall(r"\[mirai:image:{(.*?)}\..*]", message_serialization, re.S)[0] sql = f"SELECT * FROM keywordReply WHERE keyword='{message_serialization}'" if result := await execute_sql(sql): replies = [] for i in range(len(result)): content_type = result[i][1] content = result[i][2] replies.append([content_type, content]) # print(replies) final_reply = random.choice(replies) content_type = final_reply[0] content = final_reply[1] try: if content_type == "img": await app.sendGroupMessage(group, MessageChain.create([Image.fromUnsafeBytes(base64.b64decode(content))])) elif content_type == "text": await app.sendGroupMessage(group, MessageChain.create([Plain(text=content)])) else: await app.sendGroupMessage(group, MessageChain.create([Plain(text=f"unknown content_type:{content_type}")])) except AccountMuted: pass
async def rub(operator_image: Union[int, str], target_image: Union[int, str]) -> MessageItem: user_locs = [(39, 91, 75, 75, 0), (49, 101, 75, 75, 0), (67, 98, 75, 75, 0), (55, 86, 75, 75, 0), (61, 109, 75, 75, 0), (65, 101, 75, 75, 0)] self_locs = [(102, 95, 70, 80, 0), (108, 60, 50, 100, 0), (97, 18, 65, 95, 0), (65, 5, 75, 75, -20), (95, 57, 100, 55, -70), (109, 107, 65, 75, 0)] frames = [] self_img = await AvatarFunPicHandler.get_pil_avatar(operator_image) user_img = await AvatarFunPicHandler.get_pil_avatar(target_image) for i in range(6): frame = IMG.open(f'{os.getcwd()}/statics/RubFrames/frame{i}.png' ).convert('RGBA') x, y, w, h, angle = user_locs[i] user_img_new = (await AvatarFunPicHandler.resize_img( user_img, w, h, angle)).convert("RGBA") frame.paste(user_img_new, (x, y), mask=user_img_new) x, y, w, h, angle = self_locs[i] self_img_new = (await AvatarFunPicHandler.resize_img( self_img, w, h, angle)).convert("RGBA") frame.paste(self_img_new, (x, y), mask=self_img_new) frames.append(frame) output = BytesIO() imageio.mimsave(output, frames, format='gif', duration=0.05) return MessageItem( MessageChain.create([Image.fromUnsafeBytes(output.getvalue())]), Normal(GroupStrategy()))
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 video_info(app: GraiaMiraiApplication, group: Group, message: MessageChain, member: Member): msg_str = message.asDisplay().strip() if msg_str.startswith(('av', 'AV', 'Av')): try: id_type = 'aid' num = int(re.sub('av', '', msg_str, flags=re.I)) except ValueError: return elif msg_str.startswith('BV') and len(msg_str) == 12: id_type = 'bvid' num = msg_str else: return url = f'https://api.bilibili.com/x/web-interface/view?{id_type}={num}' async with aiohttp.request("GET", url) as r: get = await r.json() data = get['data'] during = '{}分{}秒'.format(data['duration'] // 60, data['duration'] % 60) await app.sendGroupMessage( group, MessageChain.create([ Image.fromNetworkAddress(get['data']['pic']), Plain(f"\n标题:{data['title']}"), Plain(f"\nUp主:{data['owner']['name']}"), Plain(f"\n视频时长:{during}"), Plain(f"\nav号:{data['aid']}"), Plain(f"\nbv号:{data['bvid']}"), Plain(f"\n链接:https://bilibili.com/video/{data['bvid']}") ]))
async def generate_messagechain(info: dict) -> MessageChain: data = info["data"] chain_list = [] chain_list.append(Plain(text=f"【标题】{data['title']}\n")) img_url = data['pic'] async with aiohttp.ClientSession() as session: async with session.get(url=img_url) as resp: img_content = await resp.read() chain_list.append(Image.fromUnsafeBytes(img_content)) chain_list.append(Plain(text=f"\n【分区】{bilibili_partition_dict[str(data['tid'])]['name']}->{data['tname']}\n")) chain_list.append(Plain(text=f"【视频类型】{'原创' if data['copyright'] == 1 else '转载'}\n")) chain_list.append(Plain(text=f"【投稿时间】{time.strftime('%Y-%m-%d', time.localtime(int(data['pubdate'])))}\n")) chain_list.append(Plain(text=f"【视频长度】{sec_format(data['duration'])}\n")) chain_list.append(Plain(text=f"【UP主】\n 【名字】{data['owner']['name']}\n 【UID】:{data['owner']['mid']}\n")) if "staff" in data: char = "\n" chain_list.append(Plain(text=f"""【合作成员】\n{char.join([f"【{staff['title']}】{staff['name']}" for staff in data['staff']])}\n""")) chain_list.append(Plain(text="【视频数据】\n")) chain_list.append(Plain(text=f" 【播放量】{data['stat']['view']}\n")) chain_list.append(Plain(text=f" 【弹幕量】{data['stat']['danmaku']}\n")) chain_list.append(Plain(text=f" 【评论量】{data['stat']['reply']}\n")) chain_list.append(Plain(text=f" 【点赞量】{data['stat']['like']}\n")) chain_list.append(Plain(text=f" 【投币量】{data['stat']['coin']}\n")) chain_list.append(Plain(text=f" 【收藏量】{data['stat']['favorite']}\n")) chain_list.append(Plain(text=f" 【转发量】{data['stat']['share']}\n")) chara, charb = "\\n", "\n" chain_list.append(Plain(text=f"【简介】{data['desc'].replace(chara, charb)}\n")) chain_list.append(Plain(text=f"【AV】av{data['aid']}\n")) chain_list.append(Plain(text=f"【BV】{data['bvid']}\n")) chain_list.append(Plain(text=f"【链接】https://www.bilibili.com/video/av{data['aid']}")) return MessageChain.create(chain_list)
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 send(self, app: Slave, yummy: [], group: Group, prefix: str): try: yande: PictureRipperListener.dataClass = yummy[0] img_byte: bytes = await yande.get() msg = [Image.fromUnsafeBytes(img_byte)] if self.ym == "ehentai" and hasattr(yande, 'gid'): msg.append(Plain(f'{yande.gid}/{yande.token}')) with enter_message_send_context(UploadMethods.Group): msg_chain = await MeCh.create(msg).build() image: Image = msg_chain.__root__[0] bot_message = await app.sendGroupMessage( group, msg_chain) # At(sender.id), Plain(prefix_ + data_.purl), if len(self.GCache) >= 150: self.GCache.pop(list(self.GCache.keys())[0]) logger.info('Cache is full,pop first one') ext = yande.url.split('.')[-1] self.GCache[(group.id << 32) + bot_message.messageId] = [ image, ext, yande.id, yande.__class__.__name__ ] logger.info(f"{prefix}sent,tags:{yande.tags}") await self.reCallYms(app, bot_message.messageId, 60) except asyncio.TimeoutError as e: logger.exception("[YummyPictures]: " + 'Timeout' + str(e)) raise e except ValueError as e: logger.exception("[YummyPictures]: " + 'Size check failed' + str(e)) raise e
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 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): 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 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 COVID(app: GraiaMiraiApplication, group: Group): back = await get_COVID_19() await app.sendGroupMessage( group, MessageChain.create([ Plain("新型冠状病毒前10:\n" + "\n".join(back[0])), Image.fromUnsafeBytes(back[1]) ]))
async def sendURaNai(force=False): files = os.listdir(self.PATH_URN + pack) random.seed(seed) randint = random.randint(1, len(files)) if pack == 'princess/': bio = io.BytesIO() self.drawing_pic(randint, pack).save(bio, format='JPEG') img: Image = Image.fromUnsafeBytes(bio.getvalue()) else: img: Image = Image.fromLocalFile(self.PATH_URN + pack + f'URaNai{randint}.jpg') msg = [At(message.sender.id), img] if force: msg.append(Plain(f'已花费5只{self.Economy.unit}')) await app.sendGroupMessage(message.sender.group.id, MeCh.create(msg)) random.seed(None)
async def ghost_tank(app: GraiaMiraiApplication, group: Group, member: Member, para: MessageChain): if len(p := messages.get(Image)) == 2: pics = asyncio.gather(*[i.http_to_bytes() for i in p]) b = bytesIO() gray_car(*pics).save(b, format='PNG') await app.sendGroupMessage( group, MessageChain.create([Image.fromUnsafeBytes(b.getvalue())]))
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_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_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