async def handle(app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member): message_text = "".join([plain.text for plain in message.get(Plain)]).strip() if message_text == "幻影" or message_text == "彩色幻影": await update_user_call_count_plus1(group, member, UserCalledCount.functions, "functions") if len(message.get(Image)) != 2: return MessageItem( MessageChain.create( [Plain(text="非预期图片数!请按照 `显示图 隐藏图` 顺序发送,一共两张图片")]), QuoteSource(GroupStrategy())) else: display_img = message[Image][0] async with aiohttp.ClientSession() as session: async with session.get(url=display_img.url) as resp: display_img = IMG.open(BytesIO(await resp.read())) hide_img = message[Image][1] async with aiohttp.ClientSession() as session: async with session.get(url=hide_img.url) as resp: hide_img = IMG.open(BytesIO(await resp.read())) return await PhantomTankHandler.get_phantom_message( group, member, display_img, hide_img ) if message_text == "幻影" else await PhantomTankHandler.get_colorful_phantom_message( group, member, display_img, hide_img) else: return None
async def handle(self, app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member): group_id = group.id message_serialization = message.asSerializationString() message_serialization = message_serialization.replace( "[mirai:source:" + re.findall(r'\[mirai:source:(.*?)]', message_serialization, re.S)[0] + "]", "") if group_id in self.__group_repeat.keys(): self.__group_repeat[group.id]["lastMsg"] = self.__group_repeat[ group.id]["thisMsg"] self.__group_repeat[group.id]["thisMsg"] = message_serialization if self.__group_repeat[group.id]["lastMsg"] != self.__group_repeat[ group.id]["thisMsg"]: self.__group_repeat[group.id]["stopMsg"] = "" else: if self.__group_repeat[group.id][ "thisMsg"] != self.__group_repeat[group.id]["stopMsg"]: self.__group_repeat[group.id][ "stopMsg"] = self.__group_repeat[group.id]["thisMsg"] return MessageItem(message.asSendable(), Normal(GroupStrategy())) else: self.__group_repeat[group_id] = { "lastMsg": "", "thisMsg": message_serialization, "stopMsg": "" } return await super().handle(app, message, group, member)
async def rmup_handler(*args, bot: Bot, subject: Union[Member, Friend]): '''取消订阅UP主投稿 用法: /rmup UP主uid''' if len(args) != 1: return MessageChain.create([Plain("缺少参数或参数过多")]) up_id = args[0] res = getCards(up_id) if res == "error": msg = [Plain("未找到该UP主!")] logger.info("[RMUP]未找到该UP主") else: up_dict = readJSON(BILI_UP_JSON_PATH) if not isinstance(up_dict, dict): raise TypeError("Expected dict but found:", up_dict) if up_id in up_dict.keys(): if isinstance(subject, Member): up_dict[up_id].remove(groupToStr(subject.group)) elif isinstance(subject, Friend): up_dict[up_id].remove(subject.id) if len(up_dict[up_id]) == 0: del up_dict[up_id] updateJSON(BILI_UP_JSON_PATH, up_dict) msg = [Plain("已将 {} 移出监视列表\n".format(getNameByUid(up_id)))] logger.info("[RMUP]返回成功") return MessageChain.create(msg)
async def rmlive_handler(*args, bot: Bot, subject: Union[Member, Friend]): '''取消订阅直播间 用法: /rmlive 房间号''' if len(args) != 1: return MessageChain.create([Plain("缺少参数或参数过多")]) room_id = args[0] res = getLiveInfo(room_id) if isinstance(res, str): msg = [Plain("未找到该直播!")] logger.info("[RMLIVE]未找到该直播") 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): monitor_dict[room_id].remove(groupToStr(subject.group)) elif isinstance(subject, Friend): monitor_dict[room_id].remove(subject.id) if len(monitor_dict[room_id]) == 0: del monitor_dict[room_id] updateJSON(BILI_LIVE_JSON_PATH, monitor_dict) msg = [Plain("已将 {} 移出监视列表\n".format(res['name']))] logger.info("[RMLIVE]返回成功") return MessageChain.create(msg)
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 atOrQuoteHandler(self, app, message: GroupMessage): logger.debug('TalkToMe at handler act') cmd: str = message.messageChain.asDisplay().split(' ')[0] if cmd == '骂他': if self.Economy: if not await self.Economy.Economy.pay( message.sender.id, self.Economy.capitalist, 500): info: dict = await self.Economy.Economy.money( message.sender.id) plain: Plain = Plain( f"你的{self.Economy.unit}不足,你还剩{info['balance']}只{self.Economy.unit},单价500只{self.Economy.unit}" ) await app.sendGroupMessage(message.sender.group, MeCh.create([plain])) return else: if message.sender.permission == MemberPerm.Member: await app.sendGroupMessage(message.sender.group, MeCh.create([Plain('你骂你爹呢')])) return if ats := message.messageChain.get(At): for a in range(0, random.randint(2, 10)): msg = ats.copy() love = await requestText(self.nm_api) msg.append(Plain(love[0])) await app.sendGroupMessage(message.sender.group, MeCh.create(msg)) await asyncio.sleep(2) msg.clear()
async def hero_handler(*args, bot: Bot, subject: Union[Member, Friend]): '''展示玩家英雄平均数据 用法: /hero (id) 英雄名''' if len(args) != 2: return MessageChain.create( [Plain(f"缺少参数或参数过多:{args},用法: /hero (id) 英雄名")]) query_id = args[0] if isinstance(subject, Member): dota_id = bot.db.get(subject.group, "dota_id").get(query_id) else: dota_id = bot.db.get(subject, "dota_id").get(query_id) if not dota_id: logger.info(f"[HERO]未添加该用户{query_id}") return MessageChain.create([Plain(f"未添加该用户{query_id}!")]) else: query_id = dota_id res = getDotaHero(query_id, args[1]) if isinstance(res, tuple): res = res[1] logger.info("[HERO]返回成功") elif res == 0: res = f"参数有误:{args[1]}" logger.info(f"[HERO]参数有误:{args[1]}") else: logger.info("[HERO]返回成功") return MessageChain.create([Plain(res)])
async def stat_handler(*args, bot: Bot, subject: Union[Member, Friend]): '''展示最近指定场数(默认20场)游戏平均数据 用法: /stat (id) (num)''' if len(args) < 1 or len(args) > 2: return MessageChain.create( [Plain(f"缺少参数或参数过多:{args},用法: /stat (id) (num)")]) query_id, *num = args if isinstance(subject, Member): dota_id = bot.db.get(subject.group, "dota_id").get(query_id) else: dota_id = bot.db.get(subject, "dota_id").get(query_id) if not dota_id: logger.info(f"[STAT]未添加该用户{query_id}") return MessageChain.create([Plain(f"未添加该用户{query_id}!")]) else: if num and type(num[0]) == type(query_id) and query_id == num[0]: num = [20] query_id = dota_id args = 20 if len(num) == 1: try: args = int(num[0]) if args > 50 or args <= 0: args = 20 except ValueError: args = 20 res = getStat(query_id, args) logger.info("[STAT]返回成功") return MessageChain.create([Plain(res)])
async def handle(self, app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member): message_text = message.asDisplay() if re.match(r"super .*:[\n\r]+[\s\S]*", message_text): await update_user_call_count_plus1(group, member, UserCalledCount.functions, "functions") if not await get_setting(group.id, "compile"): return MessageItem( MessageChain.create([Plain(text="网络编译器功能关闭了呐~去联系管理员开启吧~") ]), Normal(GroupStrategy())) language = re.findall(r"super (.*?):", message_text, re.S)[0] code = message_text[8 + len(language):] result = await self.network_compiler(group, member, language, code) if isinstance(result, str): return MessageItem(MessageChain.create([Plain(text=result)]), QuoteSource(GroupStrategy())) else: return MessageItem( MessageChain.create([ Plain(text=result["output"] if result["output"] else result["errors"]) ]), QuoteSource(GroupStrategy())) else: return await super().handle(app, message, group, member)
async def handle(app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member): if message.asDisplay() == "搜番": await update_user_call_count_plus1(group, member, UserCalledCount.search, "search") if not await get_setting(group.id, Setting.bangumi_search): return MessageItem( MessageChain.create([Plain(text="搜番功能未开启呐~请联系管理员哦~")]), Normal(GroupStrategy())) try: await app.sendGroupMessage( group, MessageChain.create( [At(member.id), Plain("请在30秒内发送要搜索的图片呐~")])) except AccountMuted: logger.error(f"Bot 在群 <{group.name}> 被禁言,无法发送!") return None image_get = None message_received = None @Waiter.create_using_function([GroupMessage]) def waiter(event: GroupMessage, waiter_group: Group, waiter_member: Member, waiter_message: MessageChain): nonlocal image_get nonlocal message_received if time.time() - start_time < 30: if all([ waiter_group.id == group.id, waiter_member.id == member.id, len(waiter_message[Image]) == len( waiter_message.__root__) - 1 ]): image_get = True message_received = waiter_message return event else: logger.warning("等待用户超时!BangumiSearchHandler进程推出!") return event bcc = AppCore.get_core_instance().get_bcc() inc = InterruptControl(bcc) start_time = time.time() await inc.wait(waiter) if image_get: logger.success("收到用户图片,启动搜索进程!") try: await app.sendGroupMessage( group, await BangumiSearchHandler.search_bangumi( message_received[Image][0]), quote=message_received[Source][0]) except AccountMuted: logger.error(f"Bot 在群 <{group.name}> 被禁言,无法发送!") pass return None else: return None
async def register(group_id: int, member_id: int) -> list: now = datetime.datetime.now() today_date = now.strftime("%Y-%m-%d") today = datetime.datetime.strptime(today_date, "%Y-%m-%d") print(today) sql = f"SELECT `date` FROM registerRecord WHERE groupId={group_id} AND memberId={member_id} AND `date`>='{today}'" res = await execute_sql(sql) print(res) if len(res) != 0: return [ "None", MessageChain.create( [At(target=member_id), Plain(text="你今天已经签过到了呢~请不要重复签到哦~")]) ] else: sql = f"SELECT count(*) FROM registerRecord WHERE groupId={group_id} AND `date`>='{today}'" res = await execute_sql(sql) rank = res[0][0] + 1 sql = f"INSERT IGNORE INTO registerRecord (groupId,memberId,`date`) VALUES ({group_id},{member_id},'{now}')" await execute_sql(sql) return [ "quoteSource", MessageChain.create([Plain(text=f"签到成功!你是本群今日第{rank}个签到的哦~")]) ]
def NetEaseMusic(app: GraiaMiraiApplication, group: Group, member: Member, message: MessageChain): msg_argv = message.asDisplay().split(" ", 1) SearchResult = requests.get( "https://musicapi.leanapp.cn/search?" + urllib.parse.urlencode({"keywords": msg_argv[1]}), timeout=3).json()['result']['songs'][0] SongId = SearchResult['id'] SongName = SearchResult['name'] ArtistName = '/'.join([x['name'] for x in SearchResult['artists']]) CoverPic = requests.get("https://musicapi.leanapp.cn/song/detail?ids=" + str(SongId), timeout=3).json()['songs'][0]['al']['picUrl'] MusicUrl = "https://music.163.com/song/media/outer/url?id=" + str( SongId) + ".mp3" WebUrl = "https://music.163.com/#/song?id=" + str(SongId) finalXML = '''<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><msg serviceID="2" templateID="1" action="web" brief="[分享] {SongName}" sourceMsgId="0" url="{WebUrl}" flag="0" adverSign="0" multiMsgFlag="0"><item layout="2"><audio cover="{CoverPic}" src="{MusicUrl}" /><title>{SongName}</title><summary>{ArtistName}</summary></item><source name="网易云音乐" icon="https://s1.music.126.net/style/favicon.ico?v20180823" url="{WebUrl}" action="app" a_actionData="com.tencent.qqmusic" i_actionData="tencent1101079856://" appid="1101079856" /></msg>'''.format( SongName=SongName, WebUrl=WebUrl, CoverPic=CoverPic, MusicUrl=MusicUrl, ArtistName=ArtistName) # return app.sendGroupMessage( # group.id, # MessageChain.create( # [ # Plain(MusicUrl), # Plain(SongName), # Plain(str(SongId)) # ] # ) return app.sendGroupMessage( group.id, MessageChain.create([Plain(""), Xml(xml=finalXML)]))
def quoteFilter(self, message: MessageChain): if not message.has(Quote): raise ExecutionStop() if plains := message.get(Plain): if all(text.__dict__['text'].strip() not in self.QUOTE_COMMANDS for text in plains): raise ExecutionStop()
async def handle(self, app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member): message_serialization = message.asSerializationString().replace( "[mirai:source:" + re.findall(r'\[mirai:source:(.*?)]', message.asSerializationString(), re.S)[0] + "]", "") if re.match(r"添加回复关键词#[\s\S]*#[\s\S]*", message_serialization): if await user_permission_require(group, member, 2): set_result( message, await self.update_keyword(message, message_serialization)) else: return MessageItem(MessageChain.create([Plain(text="权限不足,爬")]), QuoteSource(GroupStrategy())) elif re.match(r"删除回复关键词#[\s\S]*", message_serialization): if await user_permission_require(group, member, 2): set_result( message, await self.delete_keyword(app, message_serialization, group, member)) else: set_result( message, MessageItem(MessageChain.create([Plain(text="权限不足,爬")]), QuoteSource(GroupStrategy()))) elif result := await self.keyword_detect(message_serialization): set_result(message, result)
async def get_review(group: Group, member: Member, review_type: str, target: str) -> MessageItem: group_id = group.id member_id = member.id time = datetime.now() time_right = time.strftime("%Y-%m-%d %H:%M:%S") if review_type == "year": timep = time - relativedelta(years=1) time_left = (time - relativedelta(years=1)).strftime("%Y-%m-%d %H:%M:%S") tag = "年内" elif review_type == "month": timep = time - relativedelta(months=1) time_left = (time - relativedelta(years=1)).strftime("%Y-%m-%d %H:%M:%S") tag = "月内" else: return MessageItem( MessageChain.create( [Plain(text="Error: review_type invalid!")]), QuoteSource(GroupStrategy())) sql = select(ChatRecord).where( ChatRecord.group_id == group_id, ChatRecord.member_id == member_id if target == "member" else True, ChatRecord.time < time, ChatRecord.time > timep) if not (res := list(orm.fetchall(sql))): return MessageItem(MessageChain.create([Plain(text="没有你的发言记录呐~")]), QuoteSource(GroupStrategy()))
async def waiter(event: GroupMessage, waiter_group: Group, waiter_member: Member, waiter_message: MessageChain): if waiter_group.id == group.id and waiter_member.id == member.id: if is_int(waiter_message.asDisplay()): id = int(waiter_message.asDisplay()) - 1 if id >= len(lit) or id < 0: await app.sendGroupMessage(group, MessageChain.create([Plain('查询被取消了切噜噜——')])) return event text = lit[id].split(', ') if len(text) == 2: text.append('') if msg.startswith("天气") or msg.startswith("今日天气") or msg.startswith("1日天气"): await report(app, group, text) elif msg.startswith("昨日天气"): await reporttomorrow(app, group, text, 0) elif msg.startswith("明日天气"): await reporttomorrow(app, group, text, 2) elif msg.startswith("后日天气"): await reporttomorrow(app, group, text, 3) elif is_int(msg[0]): day = int(msg[0]) if day < 0 or day > 7: return await reporttomorrow(app, group, text, day) else: await app.sendGroupMessage(group, MessageChain.create([Plain('查询被取消了切噜噜——')])) return event
async def handle(self, app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member): message_text = message.asDisplay() if message.has(At) and message_text.startswith("摸"): await update_user_call_count_plus1(group, member, UserCalledCount.functions, "functions") set_result(message, await self.petpet(message.get(At)[0].target)) else: return None
async def markfinish(app, s: Session, group, member, msg: str): text = msg.split(' ') if len(text) == 1: await app.sendGroupMessage(group, MessageChain.create([Plain('请输入标题!')])) elif len(text) != 2: return event_title = text[1] url = 'http://canvas.tongji.edu.cn/api/v1/planner/items?per_page=50&start_date=' + \ datetime.now().strftime('%Y-%m-%d') r = s.get(url) data = json.loads(r.text.replace('while(1);', '')) plannable_id = '' event_id = None for i in data: if i['context_type'] == 'User' and i['plannable'][ 'title'] == event_title: plannable_id = i['plannable_id'] if i['planner_override'] != None: event_id = i['planner_override']['id'] break else: await app.sendGroupMessage( group, MessageChain.create([Plain('查无此事件,请检查标题是否输入正确')])) data = { 'id': event_id, 'marked_complete': True, 'plannable_id': plannable_id, 'plannable_type': 'calendar_event', 'user_id': get_id(member.id), 'authenticity_token': parse.unquote( requests.utils.dict_from_cookiejar(s.cookies)['_csrf_token']) } if event_id == None: url = 'http://canvas.tongji.edu.cn/api/v1/planner/overrides' r = s.post(url, data=data) else: url = 'http://canvas.tongji.edu.cn/api/v1/planner/overrides/' + \ str(event_id) r = s.put(url, data=data) if not is_json(r.text) or 'errors' in r.json(): await app.sendGroupMessage(group, MessageChain.create([Plain('标记为完成失败!')])) else: await app.sendGroupMessage(group, MessageChain.create([Plain('标记为完成成功!')]))
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 handle(app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member): if re.match(r"/cp \w+ \w+", message.asDisplay()): await update_user_call_count_plus1(group, member, UserCalledCount.functions, "functions") _, attack, defence = message.asDisplay().split(" ") return await CPGeneratorHandler.generate_article(attack, defence)
async def handle(self, app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member): if re.match("营销号#.*#.*#.*", message.asDisplay()): await update_user_call_count_plus1(group, member, UserCalledCount.functions, "functions") _, somebody, something, other_word = message.asDisplay().split("#") content = f"""{somebody}{something}是怎么回事呢?{somebody}相信大家都很熟悉,但是{somebody}{something}是怎么回事呢,下面就让小编带大家一起了解下吧。\n{somebody}{something},其实就是{somebody}{other_word},大家可能会很惊讶{somebody}怎么会{something}呢?但事实就是这样,小编也感到非常惊讶。\n这就是关于{somebody}{something}的事情了,大家有什么想法呢,欢迎在评论区告诉小编一起讨论哦!""" set_result(message, MessageItem(MessageChain.create([Plain(text=content)]), QuoteSource(GroupStrategy()))) else: return None
async def handle(self, app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member): if re.match(r"lol .* .*", message.asDisplay()): pass elif re.match(r"lol .*", message.asDisplay()): pass else: return await super().handle(app, message, group, member)
async def group_message_handler(app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member): if (group.id == 729054809 or group.id == 791894520 or group.id == 702968511): msg = message.asDisplay() rmsg = personal(msg) await app.sendGroupMessage(group, MessageChain(__root__=[Plain(rmsg)]))
async def dd_monitor(app: GraiaMiraiApplication, group: Group, member: Member, tag: MessageChain): dd_data = yaml.safe_load( (Path(__file__).parent / 'dd_info.yml').read_text(encoding='UTF-8')) if name := tag.asDisplay().strip() not in dd_data: await app.sendGroupMessage(group, MessageChain.create([Plain('未发现你要D的组织')])) return
async def priv_handler(app, message: MessageChain): if (message.asDisplay() == 'get'): await priv_get(app) if (message.asDisplay().startswith('se')): await priv_se(app, message) if (message.asDisplay().startswith('mute')): await priv_mute(app, message) if (message.asDisplay().startswith('toQQ')): await priv_toqq(app, message)
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 startRacing(self, app: Slave, group: int, racing: HorseRacing): if await racing.start(racing.ready_time): field = await racing.display() await app.sendGroupMessage(group, MeCh.create([Plain('赛马开始\n' + field)])) await self.startTicking(app, group, racing) else: await app.sendGroupMessage(group, MeCh.create([Plain('人数不足,赛马结束,押注已退回')]))
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
def reply_definition_message(self, message: MessageChain): if message.asDisplay() in self.define_data: if type(self.define_data[message.asDisplay()]) == list: Msg = self.define_data[message.asDisplay()][0] is_image = True else: Msg = self.define_data[message.asDisplay()] is_image = False return [is_image, Msg]
async def groupMessage(app: GraiaMiraiApplication, group: Group, member: Member, message: MessageChain): if message.has(At): if message.get(At)[0].target == 993422335: str_reply = reply(message[Plain][0].text.strip()) await app.sendGroupMessage( group, MessageChain.create([Plain(str_reply + ' '), At(member.id)]))