async def graceful_reply_call_me(session: CommandSession): msg = session.get_optional('message') command = session.get_optional('command') if msg is None or command is None or command != 'call_me': return if find_string(msg, '你好') != -1 or \ find_string(msg, '嗨') != -1 or \ find_string(msg, 'hello') != -1 or \ find_string(msg, 'hi') != -1 or \ find_string(msg, '晚上好') != -1 or \ find_string(msg, '见面') != -1 or \ find_string(msg, '早安') != -1: #greetings await session.send("你好呀") elif find_string(msg, '再见') != -1 or \ find_string(msg, '拜拜') != -1 or \ find_string(msg, '晚安') != -1 or \ find_string(msg, '好梦') != -1 or \ find_string(msg, '撒有啦啦') != -1 or \ find_string(msg, '回见') != -1: await session.send("拜拜") elif len(msg) == 2: if session.ctx['user_id'] in session.bot.config.SUPERUSERS: await session.send("至高无上的主人,您叫我?") else: await session.send("请问您是?") else: await session.send(render_expression(CALL_ME_REPLY))
async def del_info(session: rcnb.CommandSession): user = session.get_optional('user') roomid = session.get_optional('roomid') if await del_subscription_info(user=user, roomid=roomid): await session.finish(f'取消订阅{roomid}号房间成功') else: await session.finish(f'你好像没订阅{roomid}号房间哦')
async def weather(session: CommandSession): self_debug("in weather command") # 获取城市的天气预报 receive_command = session.current_arg city = session.get_optional('city') url = session.get_optional('url') days = session.get_optional('days') if days == None: if len(receive_command) == 1: days = 1 elif len( receive_command) == 2 and receive_command[1].isdigit() == True: days = receive_command[1] else: days = 1 if (receive_command == '' and city == None) or (city == 'None' and url == 'None'): weather_report = "想知道天气嘛?可是你好像没告诉我地区呀" elif url is not None and url == 'unknown' and city is not None: weather_report = '#(' + city + ') 这个地方我好像不知道诶,抱歉没帮上忙' else: if city != None and city != 'None': receive_command = city if url == None: url = ' ' weather_report = await get_weather_of_city(receive_command, url, days) # 向用户发送天气预报 await session.send(weather_report)
async def teach_search(session: CommandSession): global t_global message = session.get_optional('message') image = session.get_optional('image') send_msg = search_teach(message, t_global.teach_dict, t_global.teach_mode, image) if send_msg != '': await session.send(send_msg)
async def say(session: rcnb.CommandSession): text = session.get_optional('text') s_type = session.get_optional('type') report = await tts(text, s_type) if report: # [CQ:image,file=base64://] await session.finish(f'[CQ:record,file=base64://{report}]') return
async def subscribe(session: CommandSession): message = session.get('message', prompt='你想订阅什么内容呢?') hour = session.get_optional('hour') minute = session.get_optional('minute') if hour is None or minute is None: time = session.get('time', prompt='你希望我在每天的什么时候给你推送呢?\n' '(请使用24小时制,并使用阿拉伯数字表示小时和分钟)') m = re.match(r'(?P<hour>\d{1,2})[.::](?P<minute>\d{1,2})', time) if not m: m = re.match( r'(?P<hour>\d{1,2})\s*[点时]\s*' r'(?:(?P<minute>\d{1,2}|半|一刻)\s*[分]?)?', time) if m: hour = int(m.group('hour')) session.args['hour'] = hour try: minute = int(m.group('minute') or 0) except ValueError: if m.group('minute') == '半': minute = 30 elif m.group('minute') == '一刻': minute = 15 session.args['minute'] = minute else: session.pause('时间格式不对啦,请重新发送') repeat_str = session.get('repeat', prompt='是否希望我在推送消息的时候重复你上面发的消息内容呢?(请回答是或否)') repeat = nlp.check_confirmation(repeat_str) if repeat is None: session.pause('我听不懂呀,请用是或否再回答一次呢') escaped_message = message.replace('\\', '\\\\').replace('"', '\\"') if repeat: switch_arg = f'--repeat "{escaped_message}"' else: switch_arg = f'"{escaped_message}"' try: job = await scheduler.add_scheduled_commands( ScheduledCommand('switch', switch_arg), job_id=scheduler.make_job_id( PLUGIN_NAME, context_id(session.ctx), (random_string(1, string.ascii_lowercase) + random_string(7, string.ascii_lowercase + string.digits))), ctx=session.ctx, trigger='cron', hour=hour, minute=minute, replace_existing=False) session.finish(f'订阅成功啦,下次推送时间 ' f'{job.next_run_time.strftime("%Y-%m-%d %H:%M")}') except scheduler.JobIdConflictError: session.finish('订阅失败,有可能只是运气不好哦,请稍后重试~')
async def lunch(session: CommandSession): where = ['去一食堂', '去二食堂', '吃日夜', '点外卖', '出去吃'] kind = ['面条', '饭', '炒饭', '早点', '砂锅'] next1 = session.get_optional('next1') next2 = session.get_optional('next2') if next1 is None: # 先随机一个去处,问可不可以 await session.send(__(EXPR_WAIT)) await asyncio.sleep(1) session.get('next1', prompt=random.choice(where) + '吧,' + __(EXPR_HOW)) if next2 is None and check_confirmation(next1) is not True: # 去处被否决 session.finish(__(EXPR_CANCEL)) # 去处 OK if next2 is None: session.get('next2', prompt=__(EXPR_REQU)) if check_confirmation(next2) is not True: session.finish(__(EXPR_CANCEL)) await asyncio.sleep(0.8) await session.send('经奶茶精选,今天' + random.choice(kind) + '与你更配哦🤔') await asyncio.sleep(0.3) await session.send(__(EXPR_EMOJI))
async def tq2a(session: CommandSession): msg = session.get_optional('msg') if msg == None or FUNCTION_SWITCH == False: return global call_up_times global last_call_time current_time = time.time() if (find_string(msg, '奥雷') != -1 or \ find_string(msg, '亚莉') != -1 or \ find_string(msg, '亚丽') != -1 or \ find_string(msg, '奥莉') != -1 or \ find_string(msg, '莉奥') != -1) and \ current_time - last_call_time < 60: call_up_times += 1 if call_up_times > 3: send_msg = SYSTEM_ERROR_REPLY else: index1 = find_string(msg,'吗') index2 = find_string(msg,'嘛') if index1 != -1 and msg[index1-1] == '好' or msg[index1-1] == '对': send_msg = msg[index-1] + '的' elif index2 != -1 and msg[index2-1] == '好' or msg[index2-1] == '对': send_msg = msg[index-1] + '的' else: send_msg = change_question_to_answer(msg) self_debug("send by function ------> response for change question to answer") self_debug("call up times = %d" %(call_up_times)) last_call_time = time.time() await session.send(send_msg)
async def _(session: rcnb.CommandSession): room = session.get_optional('roomid') cid = rcnbid(session.ctx) if await get_live_status(room) == '房间不存在': await session.finish(f'你订阅的房间{room}是不存在的哦!') return await save_subscription_info(room, cid) await session.finish(f'订阅 {room}号房间成功~')
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 repeatSetter(session: CommandSession): getSettings = PluginManager.settings(__plugin_name__, ctx=session.ctx) getRate = session.get_optional("rate", False) getRate = getRate if getRate else getSettings.settings["rate"] groupID = session.ctx["group_id"] if not getSettings.status: getSettings.status = True getSettings.settings = {"rate": getRate} return f"群{groupID}复读概率已被设置为{1/getRate:.3%}"
async def graceful_blessing(session: CommandSession): global BLESSING global BLESSING_REPLY global BLESSING_LENGTH global BLESSING_INDEX from random import randint msg = session.get_optional('message') command = session.get_optional('command') if msg is None or command is None or command != 'blessing': return sender_name = session.ctx['sender']['card'].split('-')[0] await session.send( render_expression(BLESSING) + sender_name + '大佬' + '新年快乐!猪年大吉!心想事成!万事如意!!') if randint(1, 3) > 1: if BLESSING_INDEX == BLESSING_LENGTH: BLESSING_INDEX = 0 await session.send(BLESSING_REPLY[BLESSING_INDEX]) BLESSING_INDEX += 1
async def signup_show(session: CommandSession): code = session.get_optional('code') if code: # show one event = await dao.get_event(code) if not event: session.finish(f'没有找到你输入的活动码对应的活动哦') if event.context_id != dao.ctx_id_by_user(session.ctx): session.finish(f'此活动不是由你发起的哦,无法查看报名信息') qq_group = event.qq_group_number or '未绑定' start_date = dt.beijing_from_timestamp( event.start_time).strftime('%Y-%m-%d') end_date = dt.beijing_from_timestamp( event.end_time).strftime('%Y-%m-%d') if event.end_time else '未结束' signup_count = await dao.get_signup_count(event) if signup_count is None: signup_count = '查询失败' if event.max_signups > 0: signup_count = f'{signup_count}/{event.max_signups}' info = f'活动名称:{event.title}\n' \ f'活动码:{event.code}\n' \ f'活动官方群:{qq_group}\n' \ f'报名开始日期:{start_date}\n' \ f'报名结束日期:{end_date}\n' \ f'报名人数:{signup_count}' await session.send(info) else: # show all show_ended = session.get_optional('show_ended', False) events = list( filter(lambda e: bool(e.end_time) == show_ended, await dao.get_all_events(session.ctx))) p = '已结束的' if show_ended else '正在进行中的' if not events: session.finish(f'你目前没有{p}活动报名') await session.send(f'你发起的{p}活动报名有:') await session.send('\n\n'.join( map(lambda e: f'活动名称:{e.title}\n活动码:{e.code}', events)))
async def _(session: CommandSession): jobs = session.get_optional('jobs') or \ await get_subscriptions(session.ctx) if not jobs: session.finish(f'你还没有订阅任何内容哦') for i, job in enumerate(jobs): await session.send(format_subscription(i + 1, job)) await asyncio.sleep(0.2) session.finish(f'以上是所有的 {len(jobs)} 个订阅')
async def graceful_reply(session: CommandSession): msg = session.get_optional('message') command = session.get_optional('command') if msg is None or command is None or command != 'praise': return sender_name = session.ctx['sender']['card'].split('-')[0] to_personal_reply = sender_name + '大佬过奖了' #praise to master if find_string(msg, '奥雷') != -1 or find_string(msg, '黯') != -1: reply_msg = return_random_with_additional_element( PRAISE_MASTER_REPLY, (to_personal_reply, (msg))) #praise to me elif find_string(msg, '小雷') != -1 or find_string(msg, '雷导') != -1: reply_msg = return_random_with_additional_element( PRAISE_ME_REPLY, (to_personal_reply, (msg))) #send reply else: reply_msg = msg await session.send(reply_msg)
async def index(session: CommandSession): now = dt.beijing_now() year = session.get_optional('year', now.year) month = session.get_optional('month', now.month) month = math.ceil(month / 3) * 3 - 3 + 1 anime_list = await get_anime_list(year, month) if not anime_list: session.finish('没有查询到相关番剧……') reply = f'{year}年{month}月番剧\n按追番人数排序,前20部如下:\n\n' for anime in anime_list: title = anime.get('title') index_show = anime.get('index_show', '不详') if not title: continue reply += f'{title} {index_show}\n' web_url = WEB_URL.format(year=year, month=month) reply += f'\n更多详细资料见BiliBili官网 {web_url}' session.finish(reply)
async def log_details(session: CommandSession): receive_command = session.get_optional('nlp_result') if receive_command is None: receive_command = session.current_arg if receive_command == '': global LOG_DETAILS_HELP_REPLY await session.send(LOG_DETAILS_HELP_REPLY) return element = receive_command.split(' ') if element[0] == 'None': send_data = render_expression(LEAK_OF_CHARACTER_REPLY) elif len(element) == 1: send_data, player_num, server_name = get_log_details_search_player( element[0]) if player_num == 0: await session.send(send_data) return elif player_num > 1: send_data = '查询到多个重名角色:\n' + send_data send_data += '\n请指定服务器名查询' await session.send(send_data) return else: element.append(server_name) if element[1] == 'None': await session.send(render_expression(LEAK_OF_SERVER_REPLY)) return analy = get_log_details_url(element) self_debug("send by function ------> -log-details get log-details") if analy['error'] == 0: data = await get_log_details(analy['url']) if data is None: send_data = '与fflogs网站通信错误' else: send_data = element[0] + ' - ' + analy[ 'server_official_name'] + '\n' if len(data.keys()) == 0: send_data += '小雷偷偷去看了眼,发现这个人什么记录都没有!' else: for boss in data.keys(): send_data += 'boss:' + boss + '\n' + \ ' ' + '职业: [' + data[boss]['job'] + ']\n' + \ ' ' + '最优秀logs: [' + data[boss]['blogs'] + ']\n' + \ ' ' + '最优秀rdps: [' + data[boss]['dps'] + ']\n' + \ ' ' + '击杀并上传次数: [' + data[boss]['kills'] + ']\n' + \ ' ' + '最快用时: [' + data[boss]['fkill'] + ']\n' + \ ' ' + '平均logs: [' + data[boss]['mlogs'] + ']\n' + \ ' ' + '得分: [' + data[boss]['point'] + ']\n' send_data.rstrip('\n') else: send_data = render_expression( SEARCH_ERROR_REPLY) + '\n错误原因:' + analy['error_msg'] await session.send(send_data)
async def unsubscribe(session: CommandSession): jobs = session.get_optional('jobs') or \ await get_subscriptions(session.ctx) index = session.get_optional('index') if index is None: session.args['jobs'] = jobs await call_command(session.bot, session.ctx, ('subscribe', 'show'), args={'jobs': jobs}, disable_interaction=True) index = session.get('index', prompt='你想取消哪一个订阅呢?(请发送序号)') index = int(index) - 1 if not (0 <= index < len(jobs)): session.finish('没有找到你输入的序号哦') job = jobs[index] if await scheduler.remove_job(job.id): session.finish('取消订阅成功') else: session.finish('出了点问题,请稍后再试吧')
async def _(session: CommandSession): try: delay = float(session.get_optional('delay', 1)) except ValueError: delay = 1 delay = min(delay, 10) delay = max(delay, 0.1) await asyncio.sleep(delay) await call_command(session.bot, session.ctx, 'echo', current_arg=session.current_arg, args=session.args)
async def tuling(session: CommandSession): # 获取可选参数,这里如果没有 message 参数,命令不会被中断,message 变量会是 None message = session.get_optional('message') # 通过封装的函数获取图灵机器人的回复 reply = await call_tuling_api(session, message) if reply: # 如果调用图灵机器人成功,得到了回复,则转义之后发送给用户 # 转义会把消息中的某些特殊字符做转换,以避免 酷Q 将它们理解为 CQ 码 await session.send(escape(reply)) else: # 如果调用失败,或者它返回的内容我们目前处理不了,发送无法获取图灵回复时的「表达」 # 这里的 render_expression() 函数会将一个「表达」渲染成一个字符串消息 await session.send(render_expression(EXPR_DONT_UNDERSTAND))
async def lib_command(session: CommandSession): lib_name = session.get_optional('lib') if not lib_name: message = "标准库链接:\n镜像链接:{}\n官方链接:{}".format(LOCAL_LIB_URL, LIB_URL) await session.send(message) return lib = find_lib(lib_name) if lib: message = "{}链接:{}".format( lib.comment, lib.url.replace(DOC_ROOT_URL, LOCAL_DOC_ROOT_URL)) await session.send(message) else: # message = await spider_third_lib(lib_name) message = "未找到" await session.send(message)
async def tuling(session: CommandSession): message = session.get('message', prompt='我已经准备好啦,来跟我聊天吧~') finish = message in ('结束', '拜拜', '再见') if finish: session.finish('拜拜啦,你忙吧,下次想聊天随时找我哦~') return # call tuling api reply = f'你说了:{message}' one_time = session.get_optional('one_time', False) if one_time: session.finish(reply) else: session.pause(reply)
async def music(session: CommandSession): # 和炸毛互动 if session.ctx['message_type'] == 'group' and \ session.bot.config.GROUPS_TO_PLAY_WITH_ZHAMAO and \ session.ctx['group_id'] in \ session.bot.config.GROUPS_TO_PLAY_WITH_ZHAMAO and \ not session.get_optional('from_nlp'): ts = int(time.time() / 30) if ts % 2 == 1: # 奇数炸毛发,奶茶附和 await asyncio.sleep(2) session.finish('炸毛哥哥已经回复你啦~') keyword = session.get('keyword', prompt='你想听什么歌呢?') song_id = await search_song_id(keyword) if song_id is None: session.finish('没有找到这首歌呢') session.finish(MessageSegment.music('qq', song_id))
async def lang_command(session: CommandSession): lang_ref_name = session.get_optional('lang') if not lang_ref_name: titles = list(set([lang.title1 for lang in find_lang_ref(True, **{})])) titles_text = ",".join([title for title in titles]) message = "语言参考:\n镜像链接:{}\n包含内容:{}\n试着发送{}".format( LOCAL_LANG_REF_ROOT_URL, titles_text, "lang " + titles[0]) await session.send(message) return lang_ref = find_lang_ref(many=True, title1=lang_ref_name) if lang_ref: href = lang_ref[0].url.split('#')[0].replace(DOC_ROOT_URL, LOCAL_DOC_ROOT_URL) message = f"{lang_ref[0].title1}---{href}\n{','.join([lang.title2 for lang in lang_ref])}" await session.send(message) else: message = "未找到" await session.send(message)
async def vtuber_audio(session: nonebot.CommandSession): key_word: str = session.get_optional('key_word') if key_word is None: file = await get_random_file(f'{os.getcwd()}/data/dl/audio') elif '盘子' in key_word: file = '05-1.mp3' elif '恋口上' in key_word: file = 'a0616-12.mp3' elif 'seaside' in key_word.lower(): file = '34-1.mp3' elif '恩' in key_word or '嗯' in key_word: file = '71.mp3' elif '唱歌' in key_word: file = 'a-207.mp3' else: file = await get_random_file(f'{os.getcwd()}/data/dl/audio') await session.finish(f'[CQ:record,file=file:///{file}]')
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 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 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
async def logs(session: CommandSession): receive_command = session.get_optional('nlp_result') if receive_command is None: receive_command = session.current_arg global LOGS_HELP_REPLY if receive_command == '': await session.send(LOGS_HELP_REPLY) return element = receive_command.split(' ') if len(element) != 2: await session.send(LOGS_HELP_REPLY) return #boss is None if element[0] == 'None': send_data = render_expression(LEAK_OF_BOSS_REPLY) elif element[1] == 'None': send_data = render_expression(LEAK_OF_JOB_REPLY) else: analy = get_logs_url(element) self_debug("send by function ------> -logs") if analy['error'] == 0: data = await get_logs(analy['url']) send_data = "boss: " + analy['boss'] + " job: " + analy[ 'job'] + "\n(两周数据)" if '国服' in receive_command: send_data += ' 国服' send_data += ":\n" for key in data.keys(): send_data = send_data + key + "%: " + data[key] if analy['logs_dps'] != 0: send_data += '\n' + str(analy['logs_dps']) + ' 大概在 ' dps_percent = calc_dps_percent(analy['logs_dps'], data) send_data += '{:.2f}'.format(dps_percent) + '% 左右哦~' if dps_percent > 80: send_data += '\n你好厉害啊,这个水平已经是绝对的大佬了!' elif dps_percent < 25: send_data += '\n小雷觉得你的上升空间很大嘛,别灰心,多练习,继续加油吧~' #send_data = send_data + "100%的就别看了吧,怕伤你自尊" else: send_data = render_expression( SEARCH_ERROR_REPLY) + '\n错误原因:' + analy['error_msg'] await session.send(send_data)
async def tuling(session: CommandSession): message = session.get('message', prompt=__(e.I_AM_READY)) ctx_id = context_id(session.ctx) if ctx_id in tuling_sessions: del tuling_sessions[ctx_id] tmp_msg = Message(message) text = tmp_msg.extract_plain_text() images = [ s.data['url'] for s in tmp_msg if s.type == 'image' and 'url' in s.data ] # call tuling api replies = await call_tuling_api(session, text, images) logger.debug(f'Got tuling\'s replies: {replies}') if replies: for reply in replies: await session.send(escape(reply)) await asyncio.sleep(0.8) else: await session.send(__(e.I_DONT_UNDERSTAND)) one_time = session.get_optional('one_time', False) if one_time: # tuling123 may opened a session, we should recognize the # situation that tuling123 want more information from the user. # for simplification, we only recognize named entities, # and since we will also check the user's input later, # here we can allow some ambiguity. ne_type = tuling_ne_type(replies, { 'LOC': ('哪里', '哪儿', re.compile(r'哪\S城市'), '位置'), 'TIME': ('什么时候', ), }) if ne_type: logger.debug(f'One time call, ' f'and there is a tuling session for {ne_type}') tuling_sessions[ctx_id] = ne_type else: session.pause()