【问题标题】:trying to make my discord python bot write to a file试图让我的不和谐 python 机器人写入文件
【发布时间】:2022-01-16 12:06:57
【问题描述】:

我正在尝试编写一个不和谐的机器人,当你输入 !create 时,你可以输入每个人的分数,它应该将分数保存到一个文本文件以便以后检索它们,但它没有写任何东西到文本文件,我不知道为什么会这样。

我的代码:

import discord

client = discord.Client()
channel = client.get_channel("channelid")

file = open("TournamentScores.txt", "a")

tournament = False
scoreset1 = False
scoreset2 = False


@client.event
async def on_ready():
    print("~Bot Started~")
    channel = client.get_channel("channelid")

@client.event
async def on_message(message):
    print("received message") 
    channel = client.get_channel("channelid")
    
    global tournament, scoreset1, scoreset2

    if message.content.startswith("!create") and not tournament:
        print("Tournament Created")
        tournament = True
        await message.channel.send("Goals for Conner:")
        file.write("~Tournament~ \n")

    
    elif message.content.isdigit():
        if tournament and not scoreset1:
            scoreset1 = True
            ConnerTemplate = "Conner - " + message.content
            file.writelines(ConnerTemplate + " \n")
            await message.channel.send("Goals for Ewan:")

        elif scoreset1 and not scoreset2:
            scoreset2 = True
            EwanTemplate = "Ewan - " + message.content
            file.writelines(EwanTemplate + " \n")
            await message.channel.send("Goals for Jack:")
        
        elif scoreset2 == True and tournament == True:
            JackTemplate = "Jack - " + message.content
            file.writelines(JackTemplate + " \n")
            await message.channel.send("Goals for Thomas:")

            tournament = False
            
        elif not tournament and file == open:
            ThomasTemplate = "Thomas - " + message.content
            file.writelines(ThomasTemplate + " \n")          

            file.close()

            tournament = False

【问题讨论】:

  • 可能写文件的if语句的条件都不成立?
  • 或者当您查看文件时,文件可能从未关闭并且尚未刷新?例如file 永远不会等于 open 函数,所以最后一个 elif 永远不会被执行。
  • 尝试使用调试器单步执行函数。

标签: python discord bots


【解决方案1】:

以下其中一项肯定出错了:

代码可能永远不会进入这个 if 语句。也许tournament 是True,或者消息实际上不是以!create 开头的?

if message.content.startswith("!create") and not tournament:

如果代码确实进入了 if 语句(你可以通过在 if 中打印一些东西来确认),那么这个 await 可能永远不会完成:

await message.channel.send("Goals for Conner:")

如果您超过了那一行,那么该行由于某种原因没有写入文件:

file.write("~Tournament~ \n")

如果您可以在此处打印 Tournament 并看到它,那么文件写入由于某种原因失败。

您可以尝试在写入文件时打开和关闭文件,如下所示:

with open("TournamentScores.txt", "a") as infile:
     infile.write("~Tournament~ \n")

【讨论】:

    猜你喜欢
    • 2021-07-27
    • 1970-01-01
    • 2019-05-06
    • 2021-07-07
    • 2021-10-30
    • 2021-05-27
    • 2021-07-15
    • 2021-05-08
    • 2023-04-04
    相关资源
    最近更新 更多