async def get_data(msgs: Message) -> str: data = '' for seg in msgs: seg: MessageSegment if seg.type == 'image': url = seg.data['url'] async with AsyncClient() as client: headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36' } re = await client.get(url=url, headers=headers) pic = base64.b64encode(re.content).decode() seg = MessageSegment.image(f'base64://{pic}') data += str(seg).strip() return data
async def to_msg(illusts) -> Message: msg = Message() async with PixivClient(proxy=proxy, timeout=20) as client: aapi = AppPixivAPI(client=client, proxy=proxy) await aapi.login(refresh_token=pixiv_config.pixiv_token) for illust in illusts: try: url: str = illust["image_urls"]["large"] url = url.replace("_webp", "").replace("i.pximg.net", "i.pixiv.re") async with httpx.AsyncClient() as client: resp = await client.get(url, timeout=20) result = resp.content if result: msg.append("{} ({})".format(illust["title"], illust["id"])) msg.append(MessageSegment.image(result)) except Exception as e: logger.warning(f"Error downloading image: {e}") return msg
async def _(bot: Bot, event: GroupMessageEvent, state: T_State): engine = None apikey = "" re = MessageSegment.text("无法识别图片") if state['cmd'] == '搜图': engine = Ascii2D elif state['cmd'] == '搜番': engine = TraceMoe elif state['cmd'] == '搜名场景': engine = SauceNAO apikey = cfg.snao_apikey elif state['cmd'] == '识图': engine = Google pic = Message(state['pic']).pop() if pic.type == 'image': url = pic.data['url'] async with Network() as client: session = engine(api_key=apikey, client=client) re = format_data(await session.search(url)) await search.finish(re)
async def get_jiki(keyword: str) -> Tuple[str, Union[str, Message]]: keyword = quote(keyword) search_url = "https://jikipedia.com/search?phrase={}".format(keyword) async with httpx.AsyncClient() as client: resp = await client.get(url=search_url) result = resp.text if "对不起!小鸡词典暂未收录该词条" in result: return "", "" dom = etree.HTML(result, etree.HTMLParser()) card_urls = dom.xpath( "//div[contains(@class, 'masonry')]/div/div/div/a[contains(@class, 'title-container')]/@href" ) if not card_urls: return "", "" card_url = card_urls[0] async with httpx.AsyncClient() as client: resp = await client.get(url=card_url) result = resp.text dom = etree.HTML(result, etree.HTMLParser()) title = dom.xpath( "//div[@class='section card-middle']/div[@class='title-container']/div/h1/text()" )[0] content = dom.xpath( "//div[@class='section card-middle']/div[@class='content']/div")[0] content = content.xpath("string(.)").strip() img_urls = dom.xpath( "//div[@class='section card-middle']/div/div/div[@class='show-images']/img/@src" ) if fuzz.ratio(str(title).lower(), keyword.lower()) < 90: return "", "" msg = Message() msg.append(title + ":\n---------------\n") msg.append(content) for img_url in img_urls: msg.append(MessageSegment.image(file=img_url)) return title, msg
async def download(self, ids: list): # 下载音乐 data: list = self.api.track.GetTrackAudio(song_ids=ids, bitrate=3200 * 1000)["data"] # logger.info(data) name: list = self.detail(ids) # logger.info(name) num = 1 for i in range(len(ids)): if data[i]["code"] == 404: logger.error("未从网易云读取到下载地址") return url = data[i]["url"] nid = data[i]["id"] filename = f"{name[i]}.{data[i]['type']}" file = Path.cwd().joinpath("music").joinpath(filename) config = { "id": nid, "file": file.__str__(), # 获取文件位置 "filename": filename, # 获取文件名 "from": "song" if len(ids) == 1 else "list", # 判断来自单曲还是歌单 "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 获取时间 } info = music.search(Q["id"] == nid) if info: # 数据库储存 music.update(config, Q["id"] == nid) else: music.insert(config) async with httpx.AsyncClient() as client: # 下载歌曲 async with client.stream("GET", url=url) as r: async with aiofiles.open(file, 'wb') as out_file: async for chunk in r.aiter_bytes(): await out_file.write(chunk) if len(ids) > 1: if num // 10 == 0 or num == len(ids): await self.bot.send( event=self.event, message=Message( MessageSegment.text(f"下载进度:{num}/{len(ids)}"))) num += 1
async def PushAnswer(matcher: Matcher, msg: Message = CommandArg()): matcher.stop_propagation() if (str(msg) == ""): await matcher.finish(Message("? 翻译啥呢")) page_text = await spider.GetPage( "https://www.youdao.com/w/" + str(msg) + r"/", "get") answers = [] l1 = await spider.ParsePage( page_text, "/html/body/div[1]/div[2]/div[1]/div[2]/div[2]/div[1]/div/p/text()") l2 = await spider.ParsePage( page_text, "/html/body/div[1]/div[2]/div[1]/div[2]/div[2]/div[1]/div[2]/ul/li/text()" ) l3 = await spider.ParsePage( page_text, "/html/body/div[1]/div[2]/div[1]/div[2]/div[2]/div[@id='ydTrans']/div/div/p[2]/text()" ) l4 = await spider.ParsePage( page_text, "/html/body/div[1]/div[2]/div[1]/div[2]/div[2]/div[1]/div[2]/ul/p/span/a/text()" ) answers.extend(l1 + l2 + l3 + l4) if (not answers): await matcher.finish(Message("说的是人话吗" + MessageSegment.face(14))) res = "" res += Message(f"原词(句):{msg}\n\n结果=========\n") for i in answers: i = i.strip() if (i == '' or (i[0] == "[" and i[len(i) - 1] == "]")): continue res += Message(i + "\n") await matcher.finish(str(res))
async def download(self, json_result: dict, bot: Bot, event: Event): """ 下载图片 :param json_result: json :param bot: BOT :param event: EVENT :return: """ meta_pages = json_result["illust"]["meta_pages"] names = list() if meta_pages: await bot.send(event=event, message=Message( MessageSegment.text( f"存在{str(len(meta_pages))}个图片,正在下载..."))) image_url: list = [ ii["image_urls"]["original"] for ii in meta_pages ] else: image_url: list = [ json_result["illust"]["meta_single_page"]["original_image_url"] ] for i in image_url: url_basename = os.path.basename(i) ff = await self.api.download(url=i, replace=True, path="pids", name=url_basename) if ff: png_path = f"file:///{Path.cwd().joinpath('pids', url_basename)}" names.append(png_path) logger.info(png_path) # messages.append(MessageSegment.image(png)) else: logger.error(f"{url_basename}下载失败") # await bot.send(event=event, message=messages) return names
async def get_av_data(av): av = str(av) if av[0:2] == "BV": avcode = bv2av(av) else: avcode = av.replace("av", "") new_url = url + f"?aid={avcode}" async with httpx.AsyncClient() as client: headers = {'Content-Type': "application/x-www-form-urlencoded"} r = await client.get(new_url, headers=headers) rd = json.loads(r.text) if rd['code'] == "0": if not rd["data"]: return None try: title = rd['data']['title'] pic = rd['data']['pic'] stat = rd['data']['stat'] view = stat['view'] danmaku = stat['danmaku'] reply = stat['reply'] fav = stat['favorite'] coin = stat['coin'] share = stat['share'] like = stat['like'] link = f"https://www.bilibili.com/video/av{avcode}" desc = rd['data']['desc'] msg = "标题:" + title + "\n" + MessageSegment.image( pic ) + f"播放:{view} 弹幕:{danmaku} 评论:{reply} 收藏:{fav} 硬币:{coin} 分享:{share} 点赞:{like} \n点击连接进入: \n{link}\n简介: {desc}" print(msg) if b_comments: msg += await get_top_comments(avcode) return msg except: return "错误!!! 没有此av或BV号。"
async def test_music( app: App, mocker: MockerFixture, ): """测试音乐""" from nonebot import get_driver from nonebot.adapters.onebot.v11 import Adapter, Bot, Message, MessageSegment from nonebug.mixin.call_api.fake import make_fake_adapter, make_fake_bot from src.plugins.music import music_cmd get = mocker.patch("httpx.AsyncClient.get", side_effect=mocked_get) async with app.test_matcher(music_cmd) as ctx: adapter = make_fake_adapter(Adapter)(get_driver(), ctx) bot = make_fake_bot(Bot)(adapter, "1") event = fake_group_message_event(message=Message("/music test")) ctx.receive_event(bot, event) ctx.should_call_send(event, MessageSegment.music("163", 1825190456), "result") ctx.should_finished() get.assert_called_once_with("http://netease:3000/search?keywords=test")
async def handle_emoji(matcher: Type[Matcher], dirname: str, filename: str): img = get_emoji(dirname, filename) if img: await matcher.send(MessageSegment.image(img)) else: await matcher.send("找不到该表情")
async def test_ban_group_bot_is_admin( app: App, mocker: MockerFixture, sender: dict, ): """测试群聊天,直接请求禁言 1 分钟 机器人为管理员,禁言对象为群主,管理员或普通群员 """ from nonebot import get_driver from nonebot.adapters.onebot.v11 import Adapter, Bot, Message, MessageSegment from nonebug.mixin.call_api.fake import make_fake_adapter, make_fake_bot from src.plugins.ban import EXPR_NEED_HELP, EXPR_OK, EXPR_OWNER, ban_cmd render_expression = mocker.patch("src.plugins.ban.render_expression") render_expression.return_value = Message("test") async with app.test_matcher(ban_cmd) as ctx: adapter = make_fake_adapter(Adapter)(get_driver(), ctx) bot = make_fake_bot(Bot)(adapter, "1") event = fake_group_message_event(message=Message("/ban 1"), sender=sender) ctx.receive_event(bot, event) ctx.should_call_api("get_group_list", data={}, result=[{ "group_id": 10000 }]) ctx.should_call_api( "get_group_member_info", data={ "group_id": 10000, "user_id": 1 }, result={"role": "admin"}, ) if event.sender.role == "owner": ctx.should_call_send(event, Message("test"), True, at_sender=True) elif event.sender.role == "admin": ctx.should_call_api( "get_group_member_list", data={"group_id": 10000}, result=[{ "role": "owner", "user_id": 100 }], ) ctx.should_call_send(event, Message("test"), True) else: ctx.should_call_api( "set_group_ban", data={ "group_id": 10000, "user_id": 10, "duration": 60 }, result=[], ) ctx.should_call_send(event, Message("test"), True, at_sender=True) ctx.should_finished() if event.sender.role == "admin": render_expression.assert_called_once_with( EXPR_NEED_HELP, duration=1, at_owner=MessageSegment.at(100), at_user=MessageSegment.at(10), ) elif event.sender.role == "owner": render_expression.assert_called_once_with(EXPR_OWNER) else: render_expression.assert_called_once_with(EXPR_OK, duration=1)
async def _(): await welcome.finish(MessageSegment.image(welcome_path.read_bytes()))
async def send_illust_detail(self, pid: Union[str, int], bot: Bot, event: Union[GroupMessageEvent, PrivateMessageEvent]): """ 发送p站图片 :param pid: pixiv 图片id :param bot: BOT :param event: EVENT :return: """ await self.login() flag = False try: res = await self.api.illust_detail(int(pid)) if "illust" in res.keys(): r = re.match( "([0-9]*)-([0-9]*)-([0-9]*)T([0-9]*):([0-9]*):([0-9]*)\+([0-9]*):([0-9]*)", res['illust']['create_date']) date = datetime.datetime.strftime( datetime.datetime(int(r[1]), int(r[2]), int(r[3]), int( r[4]), int(r[5]), int(r[6])) - datetime.timedelta(hours=int(r[7]) - 8, minutes=int(r[8])), '%Y-%m-%d %H:%M:%S') msg = f"PID:{res['illust']['id']}\n标题:{res['illust']['title']}\n内容:{res['illust']['caption']}\n" \ f"作者:\n {res['illust']['user']['name']}\n UID:{res['illust']['user']['id']}\n" \ f"创建时间:{date}\n尺寸:{res['illust']['width']}x{res['illust']['height']}\n" \ f"标签: " tags = [i['name'] for i in res['illust']['tags']] if "R-18" in tags: flag = True msg += ",".join(tags) if flag and not pixiv_config.r18: return await bot.send( event=event, message=Message( MessageSegment.image( "https://i.niupic.com/images/2022/01/17/9TwY.jpg" ) + MessageSegment.text("小孩子不能看涩涩的東西!"))) resp = await self.download(res, bot, event) if pixiv_config.on_temp: pixivlist.insert({"pid": pid, "msg": msg, "data": resp}) if pixiv_config.pic_msg: await bot.send( event=event, message=Message( [MessageSegment.image(i) for i in resp] + MessageSegment.text(msg + "\n") + MessageSegment.at(event.get_user_id()))) else: mid = await bot.send( event=event, message=Message( MessageSegment.reply(event.message_id) + [MessageSegment.image(i) for i in resp])) pixivhistory.insert({ "mid": mid['message_id'], "msg": msg, "data": resp }) else: return await bot.send(event=event, message=Message( MessageSegment.text( res['error']["user_message"]))) except Exception as e: logger.error(e) await bot.send(event=event, message=Message(MessageSegment.text("发生了奇怪的错误捏~")))
async def set_receive(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): # 功能设置接收 true = ["True", "T", "true", "t"] false = ["False", "F", "false", "f"] # logger.info(bot.__dict__) # logger.info(event.dict()) logger.debug( f"权限为{event.sender.role}的用户<{event.sender.nickname}>尝试使用命令{cmd}ncm {args}" ) if event.sender.role not in ncm_config.ncm_admin: logger.debug( f"执行错误:用户<{event.sender.nickname}>权限{event.sender.role }不在{ncm_config.ncm_admin}中" ) elif str(event.get_user_id()) in ncm_config.superusers: logger.debug(f"执行错误:用户<{event.sender.nickname}>非超级管理员(SUPERUSERS)") if event.dict()['sender']['role'] in ncm_config.ncm_admin or str( event.get_user_id()) in ncm_config.superusers: if args: args = args.__str__().split() mold = args[0] else: msg = f"{cmd}ncm:获取命令菜单\r\n说明:网易云歌曲分享到群内后回复机器人即可下载\r\n{cmd}ncm t:开启解析\r\n{cmd}ncm f:关闭解析" await set.finish(message=MessageSegment.text(msg)) info = setting.search(Q["group_id"] == event.dict()["group_id"]) #logger.info(info) if info: if mold in true: # logger.info(info) info[0]["song"] = True info[0]["list"] = True setting.update(info[0], Q["group_id"] == event.dict()["group_id"]) msg = "已开启自动下载功能" await bot.send(event=event, message=Message(MessageSegment.text(msg))) elif mold in false: info[0]["song"] = False info[0]["list"] = False setting.update(info[0], Q["group_id"] == event.dict()["group_id"]) msg = "已关闭自动下载功能" await bot.send(event=event, message=Message(MessageSegment.text(msg))) logger.debug(f"用户<{event.sender.nickname}>执行操作成功") else: if mold in true: setting.insert({ "group_id": event.dict()["group_id"], "song": True, "list": True }) elif mold in false: setting.insert({ "group_id": event.dict()["group_id"], "song": False, "list": False }) else: await bot.send(event=event, message=Message(MessageSegment.text("你咩有权限哦~")))