从 .txt 文件设置前缀 discord.py

Set prefix discord.py from a .txt file

你好,今天我尝试编写一个函数,从文件中检索我制作的机器人使用的前缀

def setprefix():
    with open("prefix.txt") as f:
        prefix = "\n".join(f.readlines())

@client.event
async def on_ready():
    print(f'Bot started. Logged in on Discord BOT Client as {client.user}.')
    activity = discord.Activity(type=discord.ActivityType.watching, name="le serveur")
    await client.change_presence(activity=activity)
    setprefix()

但是当我发出命令时,我在控制台中出现了这个错误:

24.02 20:13:10 [Bot] Bot 已启动。以 HELLO#0767 身份登录 Discord BOT 客户端。

24.02 20:13:13 [Bot] 忽略 on_message

中的异常

24.02 20:13:13 [Bot] Traceback(最后一次调用):

24.02 20:13:13 [Bot] 文件“/.local/lib/python3.9/site-packages/discord/client.py”,第 343 行,在 _run_event

24.02 20:13:13 [机器人] await coro(*args, **kwargs)

24.02 20:13:13 [Bot] 文件“/bot.py”,第 113 行,在 on_message

24.02 20:13:13 [机器人] if message.content.startswith(前缀+命令):

24.02 20:13:13 [Bot] NameError: name 'prefix' 未定义

你能帮帮我吗?

正如所写,setprefix() 不会 return 任何东西,也不会设置任何在函数本身之外可见的值。

如果prefix是一个全局变量,你需要声明它:

def setprefix():
    with open("prefix.txt") as f:
        global prefix
        prefix = "\n".join(f.readlines())

这就是 Python 将知道您要修改全局变量而不是仅仅创建局部变量的方式。

如果相反,它应该 return 使用 on_ready() 的前缀,return 它:

def setprefix():
    with open("prefix.txt") as f:
        return "\n".join(f.readlines())

...
async def on_ready():
    ...
    prefix = setprefix()
    # do stuff with prefix