My discord.py script gives me an unexpected error. It basically marks all the variables that I defined outside of async def on_message():
but used under that as "not defined".
Well, you could easily fix it by defining them under on_message()
too. Which I tried. But then, here's the problem: The variables would be set back to what you defined each time a message is sent, even if you did add, like a line saying change it to another value if this hapens. (eg prefix, as you can see below in the code, I want to change the bot's prefix using a command called "changeprefix" and it works, HOWEVER when another message is sent with that prefix, it wouldn't recognize it; because the line defining the variable at the beginning ran again and it all got reset.
Is there a way else than just removing on_message()
and using discord.ext.commands
or something? I'm more familiar with the on-message()
system, moreover I would change the whole script if I switch to it.
import discord
client = discord.Client()
token= "some nice token"
#defining here results in "UnboundLocalError: local variable 'prefix' referenced before assignment", in the first line using the variable defined here
@client.event
async def on_message(message):
#defining here results variables being refreshed each time a message is sent
I believe what you are looking for is global
here is a simple example on how to use it.
something = 1
@client.event
async def on_message(message):
global something
something = something + 1
print(something) # 2 at first iteration
#outside of on_message
print(something) # 2 it is the same
In case you want to use it with prefix make it a dict with guild.id
as key and the value is the prefix.
btw using commands would be much easier to do so.
NOTE: If you restart your bot you are going to lose this info
If I understood your question correctly you want a variable that will change it's value everytime a command is invoked, you can use a global variable (I don't recommend it) or a bot var. Also use commands.Bot
so you can use the command system
bot = commands.Bot(command_prefix='.')
# Using a global variable
my_var = 'my value'
@bot.command()
async def foo(ctx, arg):
global my_var
my_var = arg
await ctx.send(f"Changed `my_var` value to `arg`")
# Using a bot var
bot.my_var = 'my value'
@bot.command()
async def foo(ctx, arg):
bot.my_var = arg
await ctx.send(f"Changed `bot.my_var` value to `arg`")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.