Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set prefix discord.py from a .txt file

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading