【发布时间】:2021-07-15 16:50:49
【问题描述】:
我最近正在为朋友之间的小型服务器编写一个机器人。我正在尝试向机器人添加一个测验小游戏,但遇到了问题。
这是我的代码:
@bot.command(aliases = ['popquiz', 'trivia'])
async def quiz(ctx, *, arg):
if arg == 'league':
QA = leagueQA
else:
await ctx.send('The quiz you asked for is not yet available.')
return
Q = random.randrange(len(QA))
await ctx.send(QA[Q][0])
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel
answer = await bot.wait_for('message', check=check, timeout=20)
print(answer.content.lower())
if (substring in answer.content.lower() for substring in QA[Q][1]):
await ctx.send('Close but not quite.')
return
elif (substring in answer.content.lower() for substring in QA[Q][2]):
await ctx.send('Correct!')
return
else:
await ctx.send('Incorrect')
return
leagueQA 本质上是一个嵌套列表,格式如下:
leagueQA = [
['Question 1', ['close answer1', 'close answer2'], ['right answer']],
['Question 2', ['close answer1', 'close answer2'],['right answer1','right answer2']],
['Question 3', ['close answer'], ['right answer']]]
现在,当我运行机器人并输入 $quiz League 时,机器人会从列表中随机询问我一个问题,当我回答问题时,无论我说什么,它都会以第一个响应进行响应:关闭但不完全。
我尝试打印答案以确保它确实包含正确的答案。我仔细检查了我的嵌套列表,看起来还不错。我尝试了许多不同的问题和回答,结果都是一样的。即使像“fadsfcasjdl”这样的完全错误的答案,第一个 if 条件仍然成立。我也尝试过使用 substring == answer.content.lower(),使用 contains,并删除返回值,但似乎没有任何效果。请发送帮助。
【问题讨论】:
-
(substring in answer.content.lower() for substring in QA[Q][1])是一个生成器表达式。它将永远是真实的。您的意思是检查 all 子字符串是否在答案中是否有 any 这些子字符串在答案中? -
你能重写你的minimal reproducible example 以便不需要
@bot...和asyncio 吗? - 尽可能简单,但仍能说明问题。 -
既然这很可能是一个不和谐的机器人,你为什么不直接使用一个子命令/组呢?如果你想要的只是类似于 $quiz League 的东西,那么拥有 *, args 似乎毫无意义,它会消耗整个字符串之后你可以拥有 $quiz League、$quiz general 等,而不必复制大量代码.
-
以@wwii 的评论为基础:删除
quiz()的所有参数。硬编码QA = ...。使用print()写入控制台,使用input()获取输入。你需要创建一个minimal reproducible example,这样人们就不必为了测试你的代码而创建一个完整的不和谐机器人。 -
您显然希望
(substring in answer.content.lower() for substring in QA[Q][1])解析为True或False。它没有。根据您的意思尝试any(substring in answer.content.lower() for substring in QA[Q][1])或all(substring in answer.content.lower() for substring in QA[Q][1])。
标签: python python-3.x if-statement discord.py