Python+discord.py开发DM申请问卷机器人 发送首题后无法接收用户回复求助
核心故障原因定位
- 你当前写的
askq函数缺少接收用户作答的等待逻辑:函数内只写了一句无意义的msg空语句,既没有重新调用bot.wait_for()监听用户的DM消息,也没有捕获用户对第一个问题的回复。按照你原代码的执行顺序,Bot发完第一个问题后,会直接把之前用户发的"proceed"内容当成第一个问题的答案,紧接着自动发送第二个问题,走完所有流程退出消息监听状态,这时候用户再输入作答内容,Bot已经没有在对应流程里设监听逻辑,自然不会有任何响应。 - 函数内部引用的
msg变量是之前判断用户输入proceed时的旧消息值,不是用户最新的作答内容,逻辑完全错位。 - 提前定义的索引变量
i没有参与流程控制,原本要做的循环逐题提问变成了手动写两次提问代码,后续加问题需要反复重复相同逻辑,维护成本很高。
可直接复用的修复后代码
@bot.command() async def apply(ctx): # 初始化答案存储容器 answers = {} # 获取申请人信息 applicant = ctx.author applicant_disp_name = ctx.author.display_name # 问卷问题列表,后续新增问题直接追加到这里即可 question_list = [ 'What is your full real name?', 'What is your age?' ] # 构建初始规则提示Embed welcome_content = ( f"Thank you {applicant_disp_name} for taking interest in Narcos City Police Department. " "You will be asked a series of question which you are required to answer to the fullest of your ability. " "Please reply with *proceed* to start your application." ) rule_embed = discord.Embed(title='NARCOS CITY POLICE DEPARTMENT', color=Police) rule_embed.set_thumbnail(url=thumbnail) rule_embed.add_field(name='Human Resources:', value=welcome_content) # 给申请人发送初始规则DM await ctx.author.send(embed=rule_embed) # 全局通用消息校验规则:只接收当前申请人在DM频道发送的消息,过滤其他无关内容 def check(m): return m.author == applicant and m.channel == applicant.dm_channel # 等待用户输入proceed开启申请流程 start_reply = await bot.wait_for('message', check=check) # 做大小写兼容,避免用户输入不同大小写的proceed触发失败 if start_reply.content.lower() != 'proceed': await applicant.send("Reply with *proceed* to start the application, process cancelled.") return # 循环逐题发送问卷、捕获答案 for current_question in question_list: # 发送当前问题 await applicant.send(current_question) # 等待用户对当前问题的作答 answer_reply = await bot.wait_for('message', check=check) # 将答案存入字典 answers[current_question] = answer_reply.content # 所有问题作答完成后的收尾逻辑 await applicant.send("Application submitted successfully! We will review your responses shortly.")
新手开发注意事项
wait_for的调用顺序不能颠倒:必须先给用户发问题,再调用wait_for监听作答,如果反过来,Bot会在发问题之前就等用户输入,流程完全错位。- 不要在函数嵌套的闭包里引用外层的旧消息变量,每次需要等新消息的时候都要重新调用
wait_for获取新的消息对象。 - 存答案优先用字典,不要零散定义单独的变量存每个问题的答案,后续导出、审核答案的时候遍历字典就行,不用重复写零散的取值代码。
内容的提问来源于stack exchange,提问作者Abraham Noel Regodon
相关产品推荐
相关产品推荐

