如何在Python的Nextcord库中实现带答案校验的交互式问答命令
Nextcord交互式问答命令实现方案
核心实现思路
使用nextcord内置的wait_for()方法监听用户消息,通过过滤规则限定仅响应触发命令的用户在同频道的回复,再做答案校验返回结果即可。
完整修改后代码
from nextcord.ext import commands class Fun(commands.Cog, name="Fun Cog"): def __init__(self, bot:commands.Bot): self.bot = bot # 可扩展为多题库,后续配合随机函数实现随机出题 self.qa_pair = { "How many centimeters is in 1 meter?": "100 cm" } @commands.command(aliases = ["q/a"]) async def question(self, ctx: commands.Context): # 取出问题和对应正确答案 question, correct_answer = next(iter(self.qa_pair.items())) await ctx.send(question) # 消息过滤规则:仅接受触发命令的用户、当前频道的非机器人消息 def check(msg): return msg.author == ctx.author and msg.channel == ctx.channel and not msg.author.bot try: # 监听用户回复,超时时间设为30秒,可自行调整 user_reply = await self.bot.wait_for('message', check=check, timeout=30) except TimeoutError: await ctx.send("回答超时,请重新发起问答命令。") return # 答案模糊校验:忽略大小写、前后空格,提升容错率 if user_reply.content.strip().lower() == correct_answer.lower(): await ctx.send("Correct!") else: await ctx.send(f"Wrong answer. The correct answer is: {correct_answer}") def setup(bot: commands.Bot): bot.add_cog(Fun(bot))
关键逻辑说明
- 过滤函数
check避免了其他用户、其他频道的消息干扰问答流程 - 超时设置避免命令进程无限挂起,超时后自动结束当前问答
- 答案校验做了兼容处理,用户输入多空格、大小写不符的场景也可以正常识别
- 你可以扩展
self.qa_pair字典添加更多题库,配合random.choice实现随机出题效果
内容的提问来源于stack exchange,提问作者Aaseer
相关产品推荐
相关产品推荐

