async def receive(x: Event = Received("receive"), y: Event = LastReceived(), z: Event = Received()): assert str(x.get_message()) == "text" assert str(z.get_message()) == "text" assert x is y await test_receive.pause("pause", at_sender=True)
async def handle(bot: Bot, event: Event, state: T_State): try : args = str(event.get_message().split(" ")[1]).strip() except Exception as e: args = str(event.get_message()).strip() if args: state["phrase"] = args
async def combine(a: str = ArgStr(), b: str = ArgStr(), r: Event = Received()): if a == "text": await test_combine.reject_arg("a") elif b == "text": await test_combine.reject_arg("b") elif str(r.get_message()) == "text": await test_combine.reject_receive() assert a == "text_next" assert b == "text_next" assert str(r.get_message()) == "text_next"
async def test_handler(bot: Bot, event: Event, state: T_State): args = str(event.get_message()).strip() print("[!] Command:", state["_prefix"], "Args:", args) if args: state["help"] = args else: await bot.send(message="命令:\n1. test1\n2. test2", event=event)
async def deal_event(bot: Bot, event: Event, state: T_State): """ 说明 """ cmd_words = ['song_name', 'index'] cmd_flag = ['song_name_flag', 'index_flag'] state['song_name_flag'] = False state['index_flag'] = False des = event.get_event_description() des = des.split(' ')[3].split('@') args = str(event.get_message()).strip() if len(des) == 1: state['type'] = 'friend' state['user_id'] = int(des[0]) # await music_listen.finish('该命令不支持私聊,请通过群聊进行') else: des = des[1].split(':')[1].replace(']', '') state['type'] = 'group' state['group_id'] = int(des) if args: args = args.split('#') args.remove('') for i in range(len(args)): state[cmd_words[i]] = args[i] state[cmd_flag[i]] = True
async def handle_first_receive(bot: Bot, event: Event, state: T_State): args = str(event.get_message()).strip() logger.debug(args) if args: state["content"] = args else: state["content"] = ""
def get_value(cls, bot: Bot, event: Event, state: T_State) -> CMD_RESULT: prefix = CMD_RESULT( command=None, raw_command=None, command_arg=None, command_start=None ) state[PREFIX_KEY] = prefix if event.get_type() != "message": return prefix message = event.get_message() message_seg: MessageSegment = message[0] if message_seg.is_text(): segment_text = str(message_seg).lstrip() pf = cls.prefix.longest_prefix(segment_text) if pf: value: TRIE_VALUE = pf.value prefix[RAW_CMD_KEY] = pf.key prefix[CMD_START_KEY] = value.command_start prefix[CMD_KEY] = value.command msg = message.copy() msg.pop(0) new_message = msg.__class__(segment_text[len(pf.key) :].lstrip()) for new_segment in reversed(new_message): msg.insert(0, new_segment) prefix[CMD_ARG_KEY] = msg return prefix
async def handle_first_receive(bot: Bot, event: Event, state: T_State): args = str(event.get_message()).strip() if args.isdigit(): if "songName" in state: state["songNum"] = int(args) elif args: state["songName"] = args
async def help(bot: Bot, event: Event, state: T_State, matcher: Matcher): # get real command content logger.debug(f"event: {event}") logger.debug(f"state: {state}") msg = event.get_message().extract_plain_text() logger.debug(f"got message '{msg}'") _, origin_command, command_text = re.match(regex, msg, flags=re.MULTILINE).groups() logger.debug(f"got command text '{command_text}'") extra_prompt = "" if not command_text.startswith(" ") and command_text != "": extra_prompt += f"treat '{origin_command + command_text}' as '{origin_command}'\n" logger.warning(extra_prompt) command_text = "" else: command_text = command_text.strip() command_without_help = origin_command.split()[-1] logger.debug(f"{command_without_help} => {self.cmd}") logger.debug(f"planning to call with '{self.cmd}', '{command_text}', '{self.help_long}'") help_long_text = await self.help_long_async_factory(self.cmd, command_text, self.help_long) sub_commands_texts = await asyncio.gather(*[command.help_short_async_factory(command.cmd, command_text, command.help_short) for command in self.sub_commands]) newline = '\n' output = \ f""" {extra_prompt}{help_long_text.strip()} sub-commands: {newline.join(f'{k}[{u}]:{v.strip()}' for k,u,v in zip( ('|'.join(comm.cmd_in_dice) for comm in self.sub_commands), (f'{comm.run_as}' for comm in self.sub_commands), sub_commands_texts ) ).strip()} """.strip() await matcher.finish(output)
async def _(bot: Bot, event: Event, state: dict): qq = int(event.get_user_id()) argv = str(event.get_message()).strip().split(' ') try: nickname = binding_map[qq] if len(argv) != 2: await sancheck.send("你这白痴又弄错命令格式了!给我记好了,正确的格式是.sc <成功> <失败>!") return role = role_cache[nickname] value = random.randint(1, 100) sanity = role['stats']['san'] if value > sanity: s, v = roll_expression(argv[1]) role['stats']['san'] -= v await sancheck.send( "【%s】的理智检定:%d/%d 失败,理智扣除%s点,剩余%d点" % (nickname, value, sanity, s, role['stats']['san'])) else: s, v = roll_expression(argv[0]) role['stats']['san'] -= v await sancheck.send( "【%s】的理智检定:%d/%d 成功,理智扣除%s点,剩余%d点" % (nickname, value, sanity, s, role['stats']['san'])) except KeyError: await sancheck.send("【%s】看起来还没绑定角色呢。输入.bind <角色名称> 进行绑定吧?" % (event.sender.nickname)) return
async def _(bot: Bot, event: Event, state: dict): t = int(str(event.get_message()).strip().split(' ')[-1]) s = flush_buffer(t) if s == "": await time.send("经过了%d小时,但没有玩家的能力值发生变化。" % t) else: await time.send("经过%d小时后,玩家的能力发生了如下变化:\n%s" % (t, s))
async def _(bot: Bot, event: Event, state: dict): name = str(event.get_message()).strip() qq = int(event.get_user_id()) try: var = binding_map[qq] except KeyError: try: var = role_cache[name] except KeyError: text = requests.get("http://47.100.50.175:25565/query", { "name": name }).text if text == "{}": await bind.send("千雪没能找到角色【%s】,下次再出错就把你拉入黑名单了哦!" % name) return role_cache[name] = demjson.decode(text, encoding='utf-8') if check_map(name): binding_map[qq] = name else: await bind.send("这个角色已经绑定过啦!难道还想两个人控制一个角色吗?!") return await bind.send("绑定成功!现在千雪已经认为【%s】就是【%s】了哦!" % (event.sender.nickname, name)) return await bind.send("你已经绑定过角色了哟~")
async def _(bot: Bot, event: Event, state: T_State): r = "([绿黄红紫白])(?:id)?([0-9]+)" argv = str(event.get_message()).strip().split(" ") if len(argv) == 1 and argv[0] == '帮助': await query_score.send(query_score_mes) elif len(argv) == 2: try: grp = re.match(r, argv[0]).groups() level_labels = ['绿', '黄', '红', '紫', '白'] level_labels2 = [ 'Basic', 'Advanced', 'Expert', 'Master', 'Re:MASTER' ] level_index = level_labels.index(grp[0]) chart_id = grp[1] line = float(argv[1]) music = total_list.by_id(chart_id) chart: Dict[Any] = music['charts'][level_index] tap = int(chart['notes'][0]) slide = int(chart['notes'][2]) hold = int(chart['notes'][1]) touch = int(chart['notes'][3]) if len(chart['notes']) == 5 else 0 brk = int(chart['notes'][-1]) total_score = 500 * tap + slide * 1500 + hold * 1000 + touch * 500 + brk * 2500 break_bonus = 0.01 / brk break_50_reduce = total_score * break_bonus / 4 reduce = 101 - line if reduce <= 0 or reduce >= 101: raise ValueError await query_chart.send( f'''{music['title']} {level_labels2[level_index]} 分数线 {line}% 允许的最多 TAP GREAT 数量为 {(total_score * reduce / 10000):.2f}(每个-{10000 / total_score:.4f}%), BREAK 50落(一共{brk}个)等价于 {(break_50_reduce / 100):.3f} 个 TAP GREAT(-{break_50_reduce / total_score * 100:.4f}%)''' ) except Exception: await query_chart.send("格式错误或未找到乐曲,输入“分数线 帮助”以查看帮助信息")
async def push_start(bot: Bot, event: Event, state: T_State): push_infor = Push_information() state['push_infor'] = push_infor des = event.get_event_description() des = des.split(' ')[3].split('@') args = str(event.get_message()).strip() # msg = str(event.get_message()) if len(des) == 1: for i in push_list: if i.num == int(des[0]): await push_start_event.finish('start push already') break else: push_infor.type = 'friend' push_infor.num = int(des[0]) else: des = des[1].split(':')[1].replace(']', '') for i in push_list: if i.num == int(des): await push_start_event.finish('start push already') break else: push_infor.type = 'group' push_infor.num = int(des) if args: state['citys'] = args if len(start_time) == 0: start_time.append('0') push_schedule.add_job(weather_push, 'cron', hour='7, 19', minute='30', jitter=120) push_schedule.start()
async def handle(bot: Bot, event: Event, state: T_State): args = str(event.get_message()).strip() print("狗屁不通生成器", args) logger.debug('开始进行狗屁不通生成器' + args) print(type(args)) if args: state["theme"] = args
async def _(bot: Bot, event: Event, state: dict): qq = int(event.get_user_id()) try: nickname = binding_map[qq] except KeyError: await rollcheck.send("【%s】看起来还没绑定角色呢。输入.bind <角色名称> 进行绑定吧?" % (event.sender.nickname)) return argv = str(event.get_message()).strip().split(' ') try: stat_name = argv[0] if len(argv) == 2: value = int(argv[1]) await rollcheck.send(check(nickname, stat_name, value)) return try: role = role_cache[nickname] value, err = search_check(role, stat_name) if not err: await rollcheck.send("未找到能力值【%s】!真的有这个能力吗?" % stat_name) return await rollcheck.send(check(nickname, stat_name, value)) except KeyError: await rollcheck.send("【%s】看起来还没绑定角色呢。输入.bind <角色名称> 进行绑定吧?" % (event.sender.nickname)) return except Exception: await rollcheck.send("你这白痴又弄错命令格式了!给我记好了,正确的格式是.rc <技能/属性> [值]!") return
async def _(bot: Bot, event: Event, state: dict): result = roll_expression(str(event.get_message()).strip()) name = event.sender.nickname try: name = binding_map[int(event.get_user_id())] except KeyError: pass await roll.send("【%s】的掷骰结果:%s" % (name, result[0]))
async def handle_first_receive(bot: Bot, event: Event, state: T_State): args = str(event.get_message()).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 if args: state["city"] = args # 如果用户发送了参数则直接赋值 city_weather = await get_weather(state["city"]) if city_weather == -1: await weather.finish("查询城市有误请重新查询") await weather.finish(city_weather)
async def handle(bot: Bot, event: Event, state: T_State): args = str(event.get_message()).strip() if args: state["date"] = args logger.debug(args) else: state["date"] = "0" logger.debug("None")
async def _key_getter(event: Event, matcher: "Matcher"): matcher.set_target(ARG_KEY.format(key=key)) if matcher.get_target() == ARG_KEY.format(key=key): matcher.set_arg(key, event.get_message()) return if matcher.get_arg(key): return await matcher.reject(prompt)
async def handle(bot: Bot, event: Event, state: T_State): # print(event.get_event_name().split(".")[1]) if not ENABLE_PRIVATE and event.get_event_name().split(".")[1] != "group": await twqd.send(Message(PRIVATE_PROMPT)) args = str(event.get_message()).strip() if args: state["stu_nums"] = args
async def handle(bot: Bot, event: Event, state: T_State): args = str(event.get_message()).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 if args: for city in args.split(): msg = await api.get_city(city) await yiqing.send(Message(msg)) else: msg = await api.get_sum() await yiqing.send(Message(msg))
async def handle(bot: Bot, event: Event, state: T_State): state['message'] = str(event.get_message()).strip() logger.success(f'tuling_ai: {event}\n') if state['message'] == "": response = await get_none_response() await tuling_ai.send(response) else: response = await get_tuling_ai_response(state['message']) await tuling_ai.send(response)
async def handle_first_receive(bot: Bot, event: Event, state: T_State): dats = re.findall("\+ img ([\S]+):%\[[\S]+url=([\S]+)\]%", str(event.get_message()))[0] key = dats[0] url = dats[1] if update_img(key, url): await add_img.finish(Message(f"图片添加成功,可通过命令:{key}.jpg触发")) else: await add_img.finish(Message("添加失败,请联系工作人员"))
async def analysis_main(bot: Bot, event: Event, state: dict): text = str(event.get_message()).strip() if "b23.tv" in text: # 提前处理短链接,避免解析到其他的 text = await b23_extract(text) msg = await bili_keyword(text) if msg: await analysis_bili.send(msg)
async def faq_local(bot: Bot, event: Event): raw_question = str(event.get_message()) question = raw_question.replace(' ', '') question = question.replace('\r\n', '') if question: reply, confidence = await test_local(question, event.is_tome()) if event.is_tome(): if confidence < config.CONFIDENCE: reply = '我现在还不太明白,但没关系,以后的我会变得更强呢!' reply = add_at(reply, event.get_user_id()) await faq.send(message.Message(reply))
async def handle_fund(bot: Bot, event: Event, state: T_State): args = str(event.get_message()).split() result = "" if len(args) == 0: await fund.finish("#fund <fundid> <compareddate(y-m-d)>") elif len(args) >= 3: result += "超过的参数会被忽略\n" result = result + await fund_impl.fund_impl(args) msg = Message(result) print(msg) await bot.send(event, msg, False)
async def handle_first_receive(bot: Bot, event: Event, state: T_State): args = str(event.get_message()).strip() if args: if " " in args: # 首先判断文本中间有没有空格 arg_list = args.split(' ') if len(arg_list) == 2: # 当参数为两个时,直接执行 state["server"] = arg_list[0] state["flower"] = arg_list[1] else: await flower_price.finish("参数错误!") else: # 没有空格的话就直接赋值给参数server state["server"] = args
async def _(bot: Bot, event: Event): arg = event.get_message() # try: base, img = await img_template_parser(arg) b64 = await edit_base_img(base, img) await img_template.send( Message([{ "type": "image", "data": { "file": f"base64://{str(b64, encoding='utf-8')}" } }]))
async def _(bot: Bot, event: Event, state: T_State): argv = str(event.get_message()).strip().split(' ') if len(argv) != 2: await jlpx.send("gocho 需要两个参数") i = generate(argv[0], argv[1]) await gocho.send( Message([{ "type": "image", "data": { "file": f"base64://{str(image_to_base64(i), encoding='utf-8')}" } }]))