允许您的机器人读取 discord.py 中变量的多个值

时间:2021-06-27 16:30:46

标签: python discord discord.py

我目前正在尝试在 discord.py 中创建一个测验机器人。我试图找到一种方法让我的机器人读取我分配给单个函数的多个值,作为一个问题的多个答案。这是我的代码:

@client.command()
async def ask(ctx):

    _list = [
    'question_1', 
    'question_2']

    list1 = random.choice(_list)

    answer = "default"
    hint = "default1"
    if _list[0] == list1:
        answer = "1" 
        answer = "One"
        hint = "one"
    else: 
        answer = "2"  
        answer = "Two"
        hint = "two"

    await ctx.send("What is the answer to this question?")
    await asyncio.sleep(1)
    await ctx.send(list1)
    def check(m): return m.author == ctx.author and m.channel == ctx.channel

    msg = await client.wait_for('message', check=check, timeout=None)
    if (answer in msg.content):
        await ctx.send("good")

    else:
        await ctx.send("What is the answer to this question? hint:" + hint)
        await ctx.send(list1)
        def check(m): return m.author == ctx.author and m.channel == ctx.channel

        msg = await client.wait_for('message', check=check, timeout=None)
        if (answer in msg.content):
            await ctx.send("good")
        else: 
            await ctx.send("wrong.")

这是我目前使用的概念。目前,机器人只接受给定的第二个值(OneTwo)。我也尝试过不同的方法,但没有找到任何可以正常工作的方法。我希望我能够清楚地解释一切,但请随时提出任何问题。请注意,提示工作正常,代码没有出现任何错误。如果可能,我还想知道是否可以让机器人对答案和变量不敏感。

如果答案应该是显而易见的,而我没有阅读足够的内容,或者这是不可能实现的,那么很抱歉。非常感谢!

1 个答案:

答案 0 :(得分:1)

如果将不同的值重新分配给现有变量,则会替换原始值。您想要的是使用一个列表,以便您可以查看列表中的所有答案,看看其中是否有与用户所说的相符。

使用 dict 来处理问题到答案/提示的映射也将使您在添加更多问题时更容易扩展。

@client.command()
async def ask(ctx):
    quiz_data = {
        'question_1': (["1", "One"], "one"),
        'question_2': (["2", "Two"], "two"),
    }
    question = random.choice(list(quiz_data.keys()))
    answers, hint = quiz_data[question]

    await ctx.send("What is the answer to this question?")
    await asyncio.sleep(1)
    await ctx.send(question)

    def check_sender(msg): 
        return msg.author == ctx.author and msg.channel == ctx.channel

    def check_answer(msg):
        return any(answer in msg.content for answer in answers) 

    msg = await client.wait_for('message', check=check_sender, timeout=None)
    if check_answer(msg):
        await ctx.send("good")
    else:
        await ctx.send(f"What is the answer to this question? hint: {hint}")
        await ctx.send(question)

        msg = await client.wait_for('message', check=check_sender, timeout=None)
        if check_answer(msg):
            await ctx.send("good")
        else: 
            await ctx.send("wrong.")
相关问题