def rssSubscribe(session: CommandSession): rssLink: str = session.get("link") session.send(f'开始检查订阅源:"{rssLink}"') # Get feed data rssResource: str = downloadFeed(rssLink) rssResourceParse: dict = rssParser(rssResource) # Check for duplicates with existing subscriptions subscribeToken = rssResourceParse["token"] getSettings = PluginManager.settings(__plugin_name__, session.ctx).settings if getSettings["subscribed"].get(subscribeToken): raise BotExistError(reason="此订阅已存在!") else: getSettings["subscribed"][subscribeToken] = { "link": rssLink, "last_update": rssResourceParse["last_update_stamp"], } # Processing messages repeatMessage = "\n".join([ str(CONFIG.customize.subscribe_repeat).format(**i) for i in rssResourceParse["content"][:CONFIG.customize.size] ]) fullMessage = ( str(CONFIG.customize.subscribe_prefix).format(**rssResourceParse) + f"{repeatMessage}\n" + str(CONFIG.customize.subscribe_suffix).format(**rssResourceParse)) PluginManager.settings(__plugin_name__, session.ctx).settings = getSettings return fullMessage
async def gacha(session: CommandSession): (characters, rare_characters) = await bilibili_gacha(1) num_of_rare = len(rare_characters) output_str = '你抽到了:' + ', '.join(characters) +\ '\n其中三星是:' + ', '.join(rare_characters) +\ '\n共' + str(num_of_rare) + '个.' session.send(output_str)
async def _(session: nonebot.CommandSession): stripped_arg = session.current_arg_text.strip() if session.is_first_run: if stripped_arg: session.state['mapname'] = stripped_arg return if not stripped_arg: session.send('?')
def _(session: CommandSession): session.send("开始获取一图") randomRank = random.choice(["day", "week", "month"]) apiParse = parseMultiImage(pixiv.getRank(randomRank)) choiceResult = random.choice( [data for data in apiParse["result"] if data["type"] == "illust"]) imageLinks = [i["large"] for i in choiceResult["download"]][:Config.customize.size] images = downloadMutliImage(imageLinks) messageRepeat = [str(MessageSegment.image(images[i])) for i in imageLinks] fullMessage = (str(Config.customize.rank_prefix).format(**choiceResult) + "\n".join(messageRepeat) + "\n" + str(Config.customize.rank_suffix).format(**choiceResult)) return fullMessage
async def talk_del(session: CommandSession): logger.debug('执行删除命令') args = session.args['argv'] try: assert len(args) == 2 pattern = args[0] reply = args[1] except AssertionError: session.send('参数错了呢~') try: del_rule(pattern, reply=reply) except Exception: await session.send('你说的这个我没有听说过呢') return await session.send('好吧好吧,删除这一条' + ' ' + pattern + ' ' + reply)
async def blacklist(session: CommandSession): logger.debug('执行添加黑名单指令') args = session.args['argv'] try: assert len(args) == 1 id = int(args[0]) except (AssertionError, ValueError): await session.send('参数错了呢~') return try: add_blacklist(id) except sqlite3.IntegrityError: session.send('是这个人吗? ' + str(id) + ' 之前说过啦') return await session.send('原来 ' + str(id) + ' 是坏人吗,不听ta说话了')
def broadcast(session: CommandSession): broadcastContent = session.get("content") session.send(f"开始广播消息,内容如下:\n{broadcastContent}") beginTime = time() groupsList: List[int] = [i["group_id"] for i in callModuleAPI("get_group_list")] totalSend = 0 for groupID in groupsList: enabled = PluginManager._getSettings( __plugin_name__, type="group", id=groupID ).status if not enabled: continue sendParams = {"group_id": groupID, "message": broadcastContent} callModuleAPI("send_msg", params=sendParams, ignoreError=True) totalSend += 1 return f"消息广播完成,已广播到{totalSend}个群聊\n耗时{time() - beginTime:.3f}s"
def _(session: CommandSession): session.send("开始生成词云") latestTime = datetime.datetime.now() - DELTA_TIME if "group_id" in session.ctx: messageIter = messageGenterator(group_id=session.ctx["group_id"], latestTime=latestTime) else: messageIter = messageGenterator(user_id=session.ctx["user_id"], latestTime=latestTime) wordcloud = WordcloudMaker() for data in messageIter: data: models.RecordsRead sentence = data.content wordcloud.update(sentence) imageData = wordcloud.save() return MessageSegment.image(f"base64://{b64encode(imageData).decode()}")
def NSFWImage(session: CommandSession): rank: str = session.get_optional("rank", Config.send.default) pictureCount: int = session.get_optional("num", 1) pictureCount = ( pictureCount if pictureCount <= Config.send.size else Config.send.size ) session.send(f"{rank.upper()}级涩图加载中,将发送最多{pictureCount}张") imageInfoList: List[Dict[str, Any]] = getImageList() imageList: List[str] = [ i.get("sample_url", i.get("file_url")) for i in imageInfoList if i["rating"].upper() in rank.upper() ] random.shuffle(imageList) images = downloadMultiImage([i for i in imageList if i][:pictureCount]) imageSent = [str(MessageSegment.image(i)) for i in images.values()] return "\n".join(imageSent) + f"\n共筛选出{len(imageList)}张图片"
def login(accent, password, session: CommandSession): global count, header APP_ID = read('baidu_API', 'APP_ID') APP_KEY = read('baidu_API', 'APP_KEY') SECRET_KEY = read('baidu_API', 'SECRET_KEY') client = AipOcr(APP_ID, APP_KEY, SECRET_KEY) r = requests.get('http://aao-eas.nuaa.edu.cn/eams/login.action', headers=header) session = r.cookies passsha = re.findall(r"CryptoJS.SHA1\('(.+?)'", r.text)[0] passsha = hashlib.sha1((passsha + password).encode('utf-8')).hexdigest() r = requests.get('http://aao-eas.nuaa.edu.cn/eams/captcha/image.action', headers=header, cookies=session) options = {'language_type': 'ENG'} if count < 499: yzm = client.basicAccurate(r.content, options)["words_result"] count = count + 1 else: session.send('服务器负载过大,将使用低精度验证码识别,敬请谅解') yzm = client.basicGeneral(r.content, options)["words_result"] with open('wb.png', 'wb') as code: code.write(r.content) code.close() yzm = re.findall(r"words': '(.+?)'", str(yzm))[0] yzm = yzm.replace(' ', "") print(yzm) data = { 'username': accent, 'password': str(passsha), 'captcha_response': yzm } time.sleep(1) r = requests.post('http://aao-eas.nuaa.edu.cn/eams/login.action', data=data, cookies=session, headers=header) if r.text.find('验证码不正确', 0, len(r.text)) != -1: return 1 elif r.text.find('密码错误', 0, len(r.text)) != -1: return 0 elif r.text.find('不存在', 0, len(r.text)) != -1: return 2 else: return session
async def cancel(session: CommandSession): UID_str = session.get('UID', prompt='请输入UID') global _subscribes global _BVs if UID_str in _subscribes.keys(): if len(_subscribes[UID_str]['subs_groups']) == 1: #只有一个群订阅该up投稿 for BV in _BVs[::-1]: if BV.UID == int(UID_str): _BVs.remove(BV) del _subscribes[UID_str] save_config(_subscribes, subs_path) sv.logger.info(f'成功取消up{UID_str}的投稿提醒') session.send(f'成功取消up{UID_str}的投稿提醒') else: gid = session.event['group_id'] _subscribes[UID_str]['subs_groups'].remove(gid) save_config(_subscribes, subs_path) session.send(f'成功取消up{UID_str}的投稿提醒')
async def cancel(session: CommandSession): room = session.get('room', prompt='请输入房间号') global _subscribes global _lives if room in _subscribes.keys(): if len(_subscribes[room]['subs_groups']) == 1: #只有一个群订阅该直播 for lv in _lives[::-1]: if lv.room_id == int(room): _lives.remove(lv) del _subscribes[room] save_config(_subscribes, subs_path) sv.logger.info(f'成功取消直播间{room}的开播提醒') session.send(f'成功取消直播间{room}直播提醒') else: gid = session.event['group_id'] _subscribes[room]['subs_groups'].remove(gid) save_config(_subscribes, subs_path) session.send(f'成功取消直播间{room}直播提醒')
def searchImage(session: CommandSession): enableR18 = PluginManager.settings(SEARCH_IMAGE_METHOD, session.ctx).settings[ "r-18" ] keywords = session.get("keyword") page = session.get_optional("page", 1) session.send(f'开始搜索"{keywords}"的第{page}页') apiGet = pixiv.searchIllust(keyword=keywords, page=page) apiParse = parseMultiImage(apiGet, mosaicR18=not enableR18) sortResult = sorted(apiParse["result"], key=lambda x: x["ratio"], reverse=True) messageRepeat = [ str(Config.customize.search_repeat).format(**data) for data in sortResult ] fullMessage = ( str(Config.customize.search_prefix).format(**apiParse) + "".join(messageRepeat[: Config.customize.size]) + str(Config.customize.search_suffix).format(**apiParse) ) return fullMessage
def wikipedia(session: CommandSession): keyword = session.get("keyword") session.send(f"开始Wiki搜索:{keyword}") _, resultTitles, resultIntros, resultLinks = getWiki(keyword) resultShortLinks = NetworkUtils.shortLink(resultLinks) finalResult = {"keyword": keyword, "size": len(resultTitles)} finalResult["result"] = [{ "title": resultTitles[i], "introduce": resultIntros[i], "link": resultShortLinks[resultLinks[i]], } for i in range(len(resultTitles))] repeatMessage = [ str(CONFIG_READ.customize.repeat).format(**result) for result in finalResult["result"] ] fullMessage = (str(CONFIG_READ.customize.prefix).format(**finalResult) + "".join(repeatMessage[:CONFIG_READ.size]) + str(CONFIG_READ.customize.suffix).format(**finalResult)) return fullMessage
def animeSearch(session: CommandSession): imageLink = session.get("image") session.send("开始以图搜番") imageRes = imageDownload(imageLink) if determineImageType(imageRes) == "GIF": session.send("检测到GIF图片格式,自动截取第一帧上传") imageRes = processGIF(imageRes) if len(imageRes) >= 1024**2: raise BotProgramError("图片大小超过限制,必须小于1MiB," + f"您的图片大小为{len(imageRes)/1024**2:.3f}MiB") searchResult = whatanimeUpload(imageRes) messageRepeat = [ str(Config.customize.repeat).format(**perAnime) for perAnime in searchResult["docs"] ] fullMessage = (str(Config.customize.prefix).format(**searchResult) + "".join(messageRepeat[:Config.customize.size]) + str(Config.customize.suffix).format(**searchResult)) return fullMessage
def getImage(session: CommandSession): allowR18: bool = PluginManager.settings(GET_IMAGE_METHOD, ctx=session.ctx).settings["r-18"] imageID: int = session.get("id") imageResloution: str = session.get_optional("res", "large") session.send(f"开始获取Pixiv ID为{imageID}的{imageResloution}") apiGet = pixiv.getImageDetail(imageID) apiParse = parseSingleImage(apiGet, mosaicR18=not allowR18) imageURLs = [p[imageResloution] for p in apiParse["download"]][:Config.customize.size] imageDownloaded = downloadMutliImage(imageURLs, mosaic=((not allowR18) and apiParse["r-18"])) images = [str(MessageSegment.image(imageDownloaded[i])) for i in imageURLs] repeatMessage = "\n".join(images) finalMessage = (str(Config.customize.image_prefix).format(**apiParse) + f"{repeatMessage}\n" + str(Config.customize.image_suffix).format(**apiParse)) return finalMessage
def memberImage(session: CommandSession): memberID = session.get("id") enableR18 = PluginManager.settings(MEMBER_IMAGE_METHOD, session.ctx).settings[ "r-18" ] page = session.get_optional("page", 1) session.send(f"开始获取Pixiv用户ID为{memberID}的作品第{page}页") apiGet = pixiv.getMemberIllust(memberID, page) apiParse = parseMultiImage(apiGet, mosaicR18=not enableR18) sortResult = sorted(apiParse["result"], key=lambda x: x["ratio"], reverse=True) messageRepeat = [ str(Config.customize.member_repeat).format(**data) for data in sortResult ] fullMessage = ( str(Config.customize.member_prefix).format(**apiParse) + "".join(messageRepeat[: Config.customize.size]) + str(Config.customize.member_suffix).format(**apiParse) ) return fullMessage
def _(session: CommandSession): session.send("开始生成统计") latestTime = datetime.datetime.now() - DELTA_TIME newestTime = _datetimeRound(datetime.datetime.now()) frameMaker = DataFrameMaker({"date": str, "time": float}) if "group_id" in session.ctx: messageIter = messageGenterator( group_id=session.ctx["group_id"], newestTime=newestTime, latestTime=latestTime, ) else: messageIter = messageGenterator(user_id=session.ctx["user_id"], newestTime=newestTime, latestTime=latestTime) for data in messageIter: date = str(data.time.date()) time = _time2Int(data.time.time()) frameMaker.update({"date": date, "time": time}) imageData = Chart.chatFrequency(frameMaker.read()) return MessageSegment.image(f"base64://{b64encode(imageData).decode()}")
async def get(session: CommandSession): args = session.current_arg_text.strip().split() if len(args) == 1: try: with youtube_dlc.YoutubeDL() as yt_dlc: info_dict = yt_dlc.extract_info(args[0], download=False) if is_duplicated(info_dict): session.send('视频:“' + info_dict["title"] + '”已在队列中,请勿重复下载') return info_dict['status'] = '等待中' info_dict['now_time'] = datetime.datetime.now().strftime( '%Y-%m-%d_%H:%M:%S.%f') download_list[info_dict['now_time']] = info_dict download_thread = threading.Thread(target=download_video, args=(session, info_dict['now_time'])) download_thread.start() session.send('视频:“' + info_dict["title"] + '”加入下载队列') except youtube_dlc.utils.UnsupportedError: exception_handler(f'解析失败:视频地址不受支持,请确认地址是否正确后再试。', logging.WARNING, False, session.event.group_id) except youtube_dlc.utils.DownloadError as dl_error: exception_handler(f'解析失败:{dl_error.exc_info}', logging.ERROR) except Exception as e: exception_handler(f'解析失败:未知错误,请查看运行日志。', logging.ERROR, False, session.event.group_id) return else: session.send("参数个数错误,仅支持一个参数,请检查后再试。")
def wikipedia(session: CommandSession): keyword = session.get("keyword") session.send(f"开始Wiki搜索:{keyword}") pages = getWiki(keyword)["query"]["pages"] finalResult = {"keyword": keyword, "size": len(pages)} finalResult["result"] = [] for page in pages.values(): finalResult["result"].append({ "title": page["title"], "introduce": page["extract"], "link": NetworkUtils.shortLink([page["fullurl"]])[page["fullurl"]] }) repeatMessage = [ str(CONFIG_READ.customize.repeat).format(**result) for result in finalResult["result"] ] fullMessage = ( str(CONFIG_READ.customize.prefix).format(**finalResult) + "".join(repeatMessage[: CONFIG_READ.size]) + str(CONFIG_READ.customize.suffix).format(**finalResult) ) return fullMessage
async def gacha10x(session: CommandSession): (characters, rare_characters) = await bilibili_gacha(30) num_of_rare = len(rare_characters) output_str = '你抽到了:' + str(num_of_rare) + '个三星'\ '\n分别是:' + ', '.join(rare_characters) + '.' session.send(output_str)
def botSpeaksMsg(s: str, session: CommandSession, tasks: list): if len(s) > 400: s = s[:400] + '\n文本过长已截断.' tasks.append(session.send(s.replace(r'\n', '\n').replace(r'\t', '\t')))
async def force_welcome(session: nonebot.CommandSession): message = session.current_arg_text.strip() session.send(wt.replace('{new}', message))
async def modifyDefaultMsg(session: CommandSession): ad_message = session.current_arg_text session.send(f'修改默认群发成功,现在的默认群发:{ad_message}')
def _(session: CommandSession): session: CommandSession = SyncWrapper(session) groupID = session.ctx["group_id"] getSettings = PluginManager.settings(__plugin_name__, ctx=session.ctx) getSettings.status = False session.send(f"群{groupID}复读已经关闭")
async def cancel_order(session: CommandSession): order_id = session.get('order_id', prompt='请输入需要撤单的订单号') if not kIntPattern.match(order_id): session.send('无效订单号') return await send_command(f'cancel_order {order_id}')
async def unsubscribe_market_depth(session: CommandSession): contract_id = session.get('contract_id', prompt='请输入股票id') if not kIntPattern.match(contract_id): session.send('无效股票id') return await send_command(f'unsubscribe_market_depth {contract_id}')
async def stop_strategy(session: CommandSession): strategy_id = session.get('strategy_id', prompt='请输入需要停止的策略号') if not kIntPattern.match(strategy_id): session.send('无效的策略号') return await send_command(f'stop_strategy {strategy_id}')