Discord.py on_message for循环不起作用

问题描述 投票:0回答:1

这是我想要做的:

@bot.event
async def on_message(message):

ans1GuessList = []
ans2GuessList = []
ans3GuessList = []

if message.content.startswith("!1"):

    guessName1 = message.author.name
    ans1GuessList.append(guessName1)

if message.content.startswith("!2"):

    guessName2 = message.author.name
    ans2GuessList.append(guessName2)

if message.content.startswith("!3"):

    guessName3 = message.author.name
    ans3GuessList.append(guessName3)

if message.content.startswith("!ans1correct"):

    if "admin" in [y.name.lower() for y in message.author.roles]:

        rewardListRaw = open("bank.txt", "rt")
        rewardList = rewardListRaw.read()
        rewardListRaw.close()
        print("Hello")

        for name in ans1GuessList:

            print("Goodbye")

            for item in rewardList.split("\n"):

                if name in item:

                    itemList = item.split(":")
                    rewardLine = itemList[1]
                    balance = re.search(r'(\d+)', rewardLine)
                    print(balance)
                    newBalance = balance + 50
                    finalLine = string.replace(rewardLine, balance, newBalance)
                    print(finalLine)

                    l = fileinput.nput('bank.txt', inplace=1)

                    for z in l:

                        newLine = z.replace(rewardLine, finalLine)
                    l.close()

    else:

        await bot.send_message(message.channel, "You do not have permission to use that command!")

我知道这有点乱,但基本上人们会使用!1!2或!3提交他们的答案然后管理员将使用命令!ans1correct如果答案是正确的。然后,它将遍历列表中的每个名称,并通过名为“bank.txt”的文本文件。然后它扫描每一行(一行的示例格式是“Joe Smith:100个硬币”(没有引号))当它到达该行时,它将其拆分为“:”(包括任何用户名包含数字)然后正则表达式将提取他们的余额数字。然后它会将50个硬币的奖励添加到他们的余额中,然后将其替换回该行。然后,它将使用fileinput将旧行替换为包含新余额的新行。 print(hello)和print(goodbye)用于调试。启动时,不会抛出任何错误。当我使用任一命令(!1或!ans1correct)时,也不会抛出任何错误。它打印Hello而不是Goodbye,所以我知道代码在for循环处停止。有谁知道我的代码有什么问题。我知道这是一团糟,但我发现它搞砸了。它成功地将用户的名称附加到列表中,但出于某种原因,当在.ans1correct中访问列表时,它显示为空白。当我打印(ans1GuessList)并且它只打印[]时就证明了这一点。当我在!1命令期间打印它时,它显示它已成功修改。我很困惑为什么列表在!ans1correct之前清空自己。任何帮助表示赞赏,谢谢!

编辑:我认为该列表仅附加在该命令内部,并不影响任何其他命令。反正是否有附加列表并让它保持在该命令之外?谢谢!

python python-3.x for-loop discord discord.py
1个回答
0
投票

问题是,每当机器人收到消息时,列表都会重新定义,没有值。要解决此问题,您需要做的就是将列表移出on_message,并在需要时重置命令

希望这可以帮助

© www.soinside.com 2019 - 2024. All rights reserved.