Hello, today I tried to code a function that retrieves from a file the prefix used for the bot I made
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()
But when I make a command, I have this error in the console:
24.02 20:13:10 [Bot] Bot started. Logged in on Discord BOT Client as HELLO#0767.
24.02 20:13:13 [Bot] Ignoring exception in on_message
24.02 20:13:13 [Bot] Traceback (most recent call last):
24.02 20:13:13 [Bot] File "/.local/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
24.02 20:13:13 [Bot] await coro(*args, **kwargs)
24.02 20:13:13 [Bot] File "/bot.py", line 113, in on_message
24.02 20:13:13 [Bot] if message.content.startswith(prefix+command):
24.02 20:13:13 [Bot] NameError: name ‘prefix’ is not defined
Can you help me please ?
>Solution :
As it’s written, setprefix() does not return anything or set any value visible outside the function itself.
If prefix is meant to be a global variable, you need to declare it so:
def setprefix():
with open("prefix.txt") as f:
global prefix
prefix = "\n".join(f.readlines())
That’s how Python will know that you mean to modify a global variable rather than just create a local variable.
If, instead, it’s supposed to return the prefix for on_ready() to use, return it:
def setprefix():
with open("prefix.txt") as f:
return "\n".join(f.readlines())
...
async def on_ready():
...
prefix = setprefix()
# do stuff with prefix