def change_question_to_answer(content): content = content.split(',')[-1] if find_string(content, '那么') == 0: content = content[2:] if find_string(content, '那') == 0: content = content[1:] elif find_string(content, '所以') == 0: content = content[2:] elif find_string(content, '于是') == 0: content = content[2:] elif find_string(content, '然后') == 0: content = content[2:] content = content.replace('我','嶤') content = content.replace('你','我') content = content.replace('嶤','你') msg = content.replace('吗','').replace('嘛','').replace('?','').replace('?','') if find_string(content, '有') != -1: msg = render_expression(['有','有的','没有',msg,msg,msg]) elif find_string(content, '会') != -1: msg = render_expression(['会','会的','不会',msg,msg,msg]) elif find_string(content, '是') != -1: msg = render_expression(['是','是的','不是',msg,msg,msg]) else: msg = render_expression([content,msg,msg,msg]) return msg
async def ban(session: CommandSession): duration = session.get('duration', prompt='你想被禁言多少分钟呢?') duration_sec = duration * 60 user_id = session.ctx['sender']['user_id'] # 如果在群里发送,则在当前群禁言/解除 if session.ctx['message_type'] == 'group': role = session.ctx['sender']['role'] group_id = session.ctx['group_id'] if role == 'member': await session.bot.set_group_ban( group_id=group_id, user_id=user_id, duration=duration_sec ) elif role == 'owner': await session.send(render_expression(EXPR_OWNER), at_sender=True) elif role == 'admin': await session.send( render_expression( EXPR_ADMIN, user_id=user_id, duration=duration_sec, ), at_sender=True ) # 如果私聊的话,则在所有小誓约支持的群禁言/解除 elif session.ctx['message_type'] == 'private': for group_id in session.bot.config.GROUP_ID: await session.bot.set_group_ban( group_id=group_id, user_id=user_id, duration=duration_sec )
async def alarm(session: CommandSession): time: datetime = session.get("time") target: str = session.get("target") # 过滤时间 now = datetime.now() # 过去的时间 if time <= now: session.finish(render_expression(EXPR_COULD_NOT)) # 超过30天的时间 elif time - now > timedelta(days=30): session.finish(render_expression(EXPR_TOO_LONG)) # 添加job time_str = time.strftime("%Y-%m-%d %H:%M:%S") scheduler.add_job( # type: ignore remind, "date", run_date=time, args=[target, session.event]) session.finish( render_expression( EXPR_OK, time=time_str, action=target, escape_args=False) + f"\n提醒创建成功:\n" f"> 提醒时间:{time_str}\n" f"> 内容:{target}")
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 alarm(session: CommandSession): time: datetime = session.get("time") target: str = session.get("target") # 过滤时间 now = datetime.now() # 过去的时间 if time <= now: session.finish(render_expression(EXPR_COULD_NOT)) time_str = time.strftime("%Y-%m-%d %H:%M:%S") await add_job( remind, trigger="date", run_date=time, id=make_job_id( PLUGIN_NAME, session.event, (random_string(1, string.ascii_lowercase) + random_string(7, string.ascii_lowercase + string.digits)), ), args=[target, session.event], kwargs={"remark": target}, ) cmd, current_arg = CommandManager().parse_command(session.bot, target) if cmd: tmp_session = CommandSession(session.bot, session.event, cmd, current_arg=current_arg) if await cmd.run(tmp_session, dry=True): await add_scheduled_commands( ScheduledCommand(cmd.name, current_arg), job_id=make_job_id( PLUGIN_NAME, session.event, (random_string(1, string.ascii_lowercase) + random_string(7, string.ascii_lowercase + string.digits)), ), event=session.event, trigger="date", run_date=time, replace_existing=True, ) session.finish( render_expression( EXPR_OK, time=time_str, action=target, escape_args=False) + f"\n提醒创建成功:\n" f"> 提醒时间:{time_str}\n" f"> 内容:{target}")
async def tuling(session: CommandSession): # 获取可选参数,这里如果没有 message 参数,命令不会被中断,message 变量会是 None message = session.state.get('message') user = session.ctx['user_id'] if user in LIMITATION_LIST.keys(): if LIMITATION_LIST[user] > 0: LIMITATION_LIST[user] = LIMITATION_LIST[user] - 1 else: await session.send('[debug] maximun number of requests reached for %i' % user) return else: LIMITATION_LIST[user] = 20 # 通过封装的函数获取图灵机器人的回复 reply = await call_tuling_api(session, message) match = re.search(pattern=r'http[:/\.\w]*', string=reply) if match is not None: reply = reply.replace(match.group(), 'https://www.ucas.ac.cn/') # await session.send('[debug] response via Turing api]') if reply: # 如果调用图灵机器人成功,得到了回复,则转义之后发送给用户 # 转义会把消息中的某些特殊字符做转换,以避免 酷Q 将它们理解为 CQ 码 await session.send(escape(reply)) else: # 如果调用失败,或者它返回的内容我们目前处理不了,发送无法获取图灵回复时的「表达」 # 这里的 render_expression() 函数会将一个「表达」渲染成一个字符串消息 await session.send('[debug] %s' % render_expression(EXPR_DONT_UNDERSTAND))
async def music(session: CommandSession): name = session.get('name', prompt='你想听哪首歌呢?') music = await call_netease_api(name) if music: await session.send(music) else: await session.send(render_expression(EXPR_NOT_FOUND), at_sender=True)
async def ban(session: CommandSession): duration = int(session.get('duration', prompt='你想被禁言多少分钟呢?')) duration_sec = duration * 60 user_id = session.ctx['sender']['user_id'] name = session.ctx['sender']['nickname'] # await bot.send_private_msg(user_id=1327960105, message=str(session.ctx['sender'])) time = datetime.datetime.now().hour # 如果在群里发送,则在当前群禁言/解除 if session.ctx['message_type'] == 'group': role = session.ctx['sender']['role'] group_id = session.ctx['group_id'] if group_id != 702052462 and user_id != 1327960105: return if role not in ['owners', 'admin']: await session.bot.set_group_ban(group_id=group_id, user_id=user_id, duration=duration_sec) if 0 <= time <= 6 and duration <= 480: score = int(duration / 10) try: await bot.send_msg(group_id=group_id, message=f'{name}禁言成功,获得{score}积分') except: await bot.send_msg( group_id=group_id, message=f'{int(user_id)} 禁言成功,获得{score}积分') zjjf(user_id, score) elif role == 'owner': await session.send(render_expression(EXPR_OWNER), at_sender=True)
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 tuling(session: CommandSession): message = session.state.get('message') reply = await call_tuling_api(session, message) if reply: await session.send(escape(reply)) else: await session.send(render_expression(EXPR_DONT_UNDERSTAND))
def return_random_with_additional_element(main_reply, additional_reply): for reply in additional_reply: main_reply.append(reply) msg = render_expression(main_reply) for reply in additional_reply: main_reply.remove(reply) return msg
async def hard_curse(session: CommandSession): member = session.get('member', prompt='你想喷谁呢?') text = await get_high_level_curse_text() await session.send( render_expression(('[CQ:at,qq={at_id}] {text}'), at_id=member, text=text))
async def gate(session: CommandSession): door_number = session.get('door_number', prompt='总共有多少个门呢?') direction = get_direction(int(door_number)) await session.send(render_expression(TEXTS, direction=direction), at_sender=True)
async def tuling(session: CommandSession): # 获取可选参数,这里如果没有 message 参数,命令不会被中断,message 变量会是 None message = session.state.get('message') imgurl = session.state.get('imgurl') msg = session.state.get('msg') print(msg) print("*" * 40) # print(msg) print(imgurl) if imgurl: # 获取图片返回的文字 s = await call_tupian_api(session, imgurl) # 有文字返回,爬取斗图网,搜索关键字 if s: # 调用回复内容,随机获取关键字 reply = await call_tuling_api(session, s) duanyu = jieba.lcut(reply) guanzijian = random.choice(duanyu) print(guanzijian) try: reply = await call_doutu_api(str(guanzijian)) reply = str(reply).split('\'')[1] # 图片链接 if reply: await session.send(f'[CQ:image,file={reply}]') # 没图片链接 else: await session.send(message=reply) except: await session.send(render_expression(EXPR_DONT_UNDERSTAND)) # 没文字,直接返回图片 else: await session.send(message=msg) # await session.send(message) # 通过封装的函数获取图灵机器人的回复 elif message: reply = await call_tuling_api(session, message) # 如果调用图灵机器人成功,得到了回复,则转义之后发送给用户 # 转义会把消息中的某些特殊字符做转换,以避免 酷Q 将它们理解为 CQ 码 if reply: await session.send(escape(reply)) else: await session.send(render_expression(EXPR_DONT_UNDERSTAND)) # await session.send(message) else: await session.send(message=msg)
async def call_NLP_api(session: CommandSession, text: str) -> Optional[str]: config = nonebot.get_bot().config url = "https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat" data = { 'app_id': config.TENCENT_APP_ID, 'session': context_id(session.ctx, mode='group', use_hash=True), 'question': str(text), 'time_stamp': int(time.time()), 'nonce_str': ''.join(random.choice(string.ascii_lowercase) for _ in range(32)) } data['sign'] = get_req_sign(data, config.TENCENT_APP_KEY) try: async with aiohttp.ClientSession() as sess: async with sess.post(url, data=data) as response: logger.debug(f"Send data to api: {data}") if response.status != 200: logger.error( f"Cannot connect to {url}, Status: {response.status}") await session.send("对话api调用发生错误 :(") return None r = json.loads(await response.text()) logger.debug(f"Response from API: {r}") if not r['ret']: return r['data']['answer'] elif r['msg'] == 'chat answer not found': logger.debug( "Chat answer not found. Render not understanding instead." ) return render_expression(config.EXPR_DONT_UNDERSTAND) elif r['msg'] == 'app_id not found' or r[ 'msg'] == 'app_key not found': logger.warning( "API config invalid / unfilled. Please fill them in config.py to enable NL conversation function." ) await session.send("对话api配置错误!请联系管理员") return None else: logger.error(f"Error response from API: {r['msg']}") await session.send("对话api调用发生错误 :(") return None except (aiohttp.ClientError, json.JSONDecodeError, KeyError) as e: logger.error(f"An error occupied when calling api: {e}") await session.send("对话api调用发生错误 :(") return None
async def gate(session: CommandSession): door_number = session.get('door_number', prompt='总共有多少个门呢?') direction = get_direction(int(door_number)) if not direction: session.finish('暂时只支持两个门或者三个门的情况,请重新输入吧。') session.finish(render_expression(TEXTS, direction=direction), at_sender=True)
async def _(session: NoticeSession): # 发送欢迎消息 if sql_read("User.db", "group_info", "group_id", session.ctx["group_id"], field="New_add", in_where=True)[0][0]: await session.send(render_expression(EXL))
async def morning_love(session: CommandSession): DEFAULT_CITY = "随州" CITY_HOME1 = "太原" CITY_HOME2 = "西安" weather = await get_today_weather_info(DEFAULT_CITY) weather1 = await get_today_weather_info(CITY_HOME1) weather2 = await get_today_weather_info(CITY_HOME2) one = await one_msg() weekday = ['一', '二', '三', '四', '五', '六', '日'] date = datetime.now().strftime("%m ") + '月' + datetime.now().strftime(" %d") class_info = "" # 获取用户群信息 if 'group_id' in session.ctx.keys(): group_id = session.ctx['group_id'] else: group_id = await get_user_group(session.ctx['user_id']) classes = await data_source.get_today_class_info(group_id) group_name = "" for c in classes: class_info += message.morningcall_class_msg.format( class_num=c['class_num'], class_name=c['class_name'] ) love_days = (datetime.now() - datetime(year=2018,month=12,day=13)).days msg = message.morningcall_love_msg.format( **{'date': date, 'weekday': weekday[datetime.now().weekday()], 'main_weather': weather['cond_d'], 'main_pos': DEFAULT_CITY, 'pos1': CITY_HOME1, 'pos2': CITY_HOME2, 'tmp_max': weather['tmp_max'], 'tmp_min': weather['tmp_min'], 'weather1': weather1['cond_d'], 'tmp_max1': weather1['tmp_max'], 'tmp_min1': weather1['tmp_min'], 'weather2': weather2['cond_d'], 'tmp_max2': weather1['tmp_max'], 'tmp_min2': weather2['tmp_min'], 'class': class_info, 'comf': weather['comf'], 'uv': weather['uv'], 'one': one, 'love_days': love_days, 'love_msg': render_expression(message.love_msg), }) await session.send(msg)
async def chat(session: CommandSession): message = session.state.get('message') if message.strip() == '': return reply = await AI.text_request(text=message) if reply: await session.send(escape(reply), at_sender=True) else: await session.send(render_expression(EXPR_DONT_UNDERSTAND), at_sender=True)
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 get_weather_of_city(city, url, days=1): self_debug('city is: ' + city) location = city if url == ' ': url = get_weather_url(location) if url == 'error': return render_expression(GET_WEATHER_FAILED_REPLY) if len(url) < 9: if url[0] == 0: weather_dict = get_game_weather(url) data_from = '饥饿的猫' else: weather_dict = get_game_weather_new(url) data_from = 'https://nenge.net/skywatcher/' if weather_dict['valid'] == False: return render_expression(GET_WEATHER_FAILED_REPLY) else: send_msg = location + ' 当前时间: ' + weather_dict['time'] + '\n' for key in weather_dict['weather_data'].keys(): send_msg = send_msg + key + ' : ' + weather_dict[ 'weather_data'][key] + '\n' return send_msg + "数据来自 " + data_from else: #8 代表 明天 #9 代表 后天 #10 代表 大后天 #11 代表 大大后天 #12 代表 大大大后天 #13 代表 大大大大后天 weather_dict_list = get_weather(url, days) weather_msg = '来咯来咯,新鲜的天气预报 ' + location + ':\n' if days > 7 or days == 1: weather_msg += weather_dict_list[-1][ 'date'] + ' 最高温度' + weather_dict_list[-1][ 'high_temp'] + ',最低温度' + weather_dict_list[-1][ 'low_temp'] + ',天气是' + weather_dict_list[-1]['weather'] else: for weather_dict in weather_dict_list[1:]: weather_msg += weather_dict['date'] + ' 最高温度' + weather_dict[ 'high_temp'] + ',最低温度' + weather_dict[ 'low_temp'] + ',天气是' + weather_dict['weather'] + '\n' return weather_msg
async def lick(session: CommandSession): # 从会话状态(session.state)中获取成员名称(member),如果当前不存在,则询问用户 member = session.get('member', prompt='你想舔谁呢?') text = await get_lick_text() await session.send( render_expression( ('[CQ:at,qq={at_id}] {text}'), at_id=member, text=text ) )
async def justSpeak(session: CommandSession): # 获取可选参数,这里如果没有 message 参数,命令不会被中断,message 变量会是 None message = session.state.get('message') # 获取回复 reply = await call_response(str(message), 0) if reply: await session.send(reply) else: # 这里的 render_expression() 函数会将一个「表达」渲染成一个字符串消息 await session.send(render_expression(EXPR_DONT_UNDERSTAND))
async def run(self, session, *, check_perm: bool = True, dry: bool = False) -> bool: """ Run the command in a given session. :param session: CommandSession object :param check_perm: should check permission before running :param dry: just check any prerequisite, without actually running :return: the command is finished (or can be run, given dry == True) """ has_perm = await self._check_perm(session) if check_perm else True if self.func and has_perm: if dry: return True if session.current_arg_filters is not None and \ session.current_key is not None: # argument-level filters are given, use them arg = session.current_arg for f in session.current_arg_filters: try: res = f(arg) if isinstance(res, Awaitable): res = await res arg = res except ValidateError as e: # validation failed failure_message = e.message if failure_message is None: config = session.bot.config failure_message = render_expression( config.DEFAULT_VALIDATION_FAILURE_EXPRESSION ) # noinspection PyProtectedMember session.pause(failure_message, **session._current_send_kwargs) # passed all filters session.state[session.current_key] = arg else: # fallback to command-level args_parser_func if self.args_parser_func: await self.args_parser_func(session) if session.current_key is not None and \ session.current_key not in session.state: # args_parser_func didn't set state, here we set it session.state[session.current_key] = session.current_arg await self.func(session) return True return False
async def robot(session: CommandSession): # 获取可选参数,这里如果没有 message 参数,命令不会被中断,message 变量会是 None message = session.state.get('message') # 通过封装的函数获取机器人的回复 reply = await call_tencent_api(session, message) if reply: await session.send(escape(reply), at_sender=True) return # 如果调用失败,或者它返回的内容我们目前处理不了,发送无法获取回复时的「表达」 # 这里的 render_expression() 函数会将一个「表达」渲染成一个字符串消息 await session.send(render_expression(EXPR_DONT_UNDERSTAND), at_sender=True)
async def tuling(session: CommandSession): message = session.state.get('message') at_msg = '' if session.ctx['message_type'] == 'group': at_msg = '[CQ:at,qq={}] '.format(str(session.ctx['user_id'])) reply = await get_content(message.strip()) if reply: await session.send(at_msg + escape(reply)) else: await session.send(render_expression(EXPR_DONT_UNDERSTAND))
async def tuling(session: CommandSession): # 获取可选参数,这里如果没有 message 参数,命令不会被中断,message 变量会是 None message = session.state.get('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 ai_chat(session: CommandSession): # 获取可选参数,这里如果没有 message 参数,message 变量会是 None message = session.state.get('message') # 通过封装的函数获取腾讯智能机器人机器人的回复 reply = await call_tencent_bot_api(session, message) if reply: # 如果调用腾讯智能机器人成功,得到了回复,则转义之后发送给用户 # 转义会把消息中的某些特殊字符做转换,避免将它们理解为 CQ 码 await session.send(escape(reply)) else: # 如果调用失败,或者它返回的内容我们目前处理不了,发送无法获取腾讯智能机器人回复时的「表达」 # 这里的 render_expression() 函数会将一个「表达」渲染成一个字符串消息 await session.send(render_expression(EXPR_DONT_UNDERSTAND))
async def ai_reply(bot, context): if switch.gpid not in g_open_groups and switch.gpid != 0: if not random.randint(1, 100) <= 0.5: #拙劣的概率开关 return msg = str(context['message']) if msg.startswith(f'[CQ:at,qq={context["self_id"]}]'): return text = re.sub(cq_code_pattern, '', msg).strip() if text == '': return global salt if salt is None: salt = rand_string() session_id = md5((str(context['user_id']) + salt).encode()).hexdigest() param = { 'app_id': app_id, 'session': session_id, 'question': text, 'time_stamp': str(int(time())), 'nonce_str': rand_string(), } sign = getReqSign(param) param['sign'] = sign async with aiohttp.request( 'POST', 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat', params=param, ) as response: code = response.status if code != 200: raise ValueError(f'bad server http code: {code}') res = await response.read() #print (res) param = json.loads(res) if param['ret'] != 0: raise ValueError(param['msg']) reply = param['data']['answer'] if reply: await bot.send(context, reply, at_sender=False) else: # 如果调用失败,或者它返回的内容我们目前处理不了,发送无法获取回复时的「表达」 # 这里的 render_expression() 函数会将一个「表达」渲染成一个字符串消息 await bot.send(render_expression(EXPR_DONT_UNDERSTAND))
def get_message(): """ 获得消息 不同的问候语 """ try: # 获得不同的问候语 res = requests.get('http://timor.tech/api/holiday/tts').json() except: res = {'code': -1} if res['code'] == 0: message = res['tts'] else: message = '好像没法获得节假日信息了,嘤嘤嘤' return render_expression(EXPR_MORNING, message=message)