discord.py中wait_for的check函数验证失效问题求助
问题:Discord机器人无法识别正确的句子拆解答案
我正在开发一款Discord机器人,核心功能是向用户发送句子拆解题目并验证答案正确性。但目前遇到问题:明明用户输入的答案和预设答案完全一致,check函数却返回False,导致机器人无法识别正确答案,也不会对正确回答做出反馈。
我的代码:
@commands.Cog.listener() async def on_message(self, message): if message.channel.id == 1051856493764415568: if message.author.bot: return else: rand_num = randint(4,6) if rand_num == 5: ss = open('scrambled sentences.txt','r') sslist = ss.readlines() chosen_sentence = choice(sslist) cs_list = chosen_sentence.split("|") question_msg = await message.reply(f"Unscramble the following sentence in 10 seconds for a chance to win a firework:\n\n{cs_list[0]}") def check(m: discord.Message): print(m.content) print(cs_list[-1]) # 打印后显示内容一致,但判断不通过 return m.channel.id == m.channel.id and m.content.lower == cs_list[-1] try: msg = await self.bot.wait_for('message', check = check, timeout = 10.0) except asyncio.TimeoutError: await question_msg.reply(f"Noone sent the correct answer in the 10 seconds provided...") return else: await msg.channel.send(f"**{msg.author}**, you responded with {msg.content}!") return # await message.channel.send(f"{msg.author.mention} was first! He gets one firework. The answer was:\n\n{cs_list[-1]}")
scrambled sentences.txt文件内容:
Question) `RsgaD si het btse reve!`|drags is the best ever! Question) `RsgaD si het torws reve!`|drags is the worst ever!
问题修复方案
1. 修正字符串比较的语法错误
m.content.lower是方法引用而非调用结果,必须加括号m.content.lower()才能获取小写后的字符串,否则是在比较方法对象和字符串,永远不相等。
2. 处理文件读取的换行符问题
readlines()会保留每行末尾的\n换行符,导致cs_list[-1]末尾多了一个换行符,和用户输入的内容不匹配。可以通过strip()去掉首尾空白字符:
chosen_sentence = choice(sslist).strip()
3. 修正通道判断逻辑
原代码中m.channel.id == m.channel.id永远为True,应该改为判断消息来自题目所在的目标通道:
return m.channel.id == message.channel.id and m.content.lower() == cs_list[-1].lower()
(额外建议:把预设答案也转成小写,避免大小写敏感的问题)
修复后的完整代码片段
@commands.Cog.listener() async def on_message(self, message): target_channel_id = 1051856493764415568 if message.channel.id == target_channel_id: if message.author.bot: return rand_num = randint(4,6) if rand_num == 5: # 用with语句自动关闭文件,避免资源泄漏 with open('scrambled sentences.txt','r') as ss: sslist = ss.readlines() chosen_sentence = choice(sslist).strip() # 去掉换行符和首尾空白 cs_list = chosen_sentence.split("|") question_msg = await message.reply(f"Unscramble the following sentence in 10 seconds for a chance to win a firework:\n\n{cs_list[0]}") def check(m: discord.Message): # 校验通道+大小写不敏感的答案匹配 return m.channel.id == target_channel_id and m.content.lower() == cs_list[-1].lower() try: msg = await self.bot.wait_for('message', check=check, timeout=10.0) except asyncio.TimeoutError: await question_msg.reply(f"Noone sent the correct answer in the 10 seconds provided...") return else: await msg.channel.send(f"**{msg.author}**, you got it right! The answer was: {cs_list[-1]}") # 此处可添加发放奖励的逻辑 return
内容的提问来源于stack exchange,提问作者DRags
相关产品推荐
相关产品推荐

