I am making a Python Discord bot with discord.py. I am relatively new to Python but have about eight years of experience with other languages. My problem is that I get the UnboundLocalError: local variable 'prefix' referenced before assignment
even though I have defined prefix
as a global variable. (I am using Python 3.6.8)
I have tried defining the variables outside the on_ready
function, but I get the same result.
import discord;
client = discord.Client();
@client.event
async def on_ready():
print('Loading complete!')
...
global prefix
prefix = 'hello world'
@client.event
async def on_message(message):
if message.author == client.user:
return
messageContents = message.content.lower()
splitMessage = messageContents.split()
try:
splitMessage[0] = splitMessage[0].upper()lower()
except:
return
if splitMessage[0]==prefix:
...
(later in that if statement and a few nested ones)
prefix = newPref
client.run('token')
I expected the output would be that it runs the code within the if statement, but instead I get the error UnboundLocalError: local variable 'prefix' referenced before assignment
and no code is run.
The only thing I can think of being the problem is prefix = newpref
. I tried:
global prefix
prefix = newpref
But then I got the error: SyntaxError: name 'prefix' is used prior to global declaration
and the bot didn't start at all. What should I do?