So, I tried to create a discord bot and I wrote this code:
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = discord.Client()
@client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})'
)
client.run(TOKEN)
Then VSCode shown me this:
f'{client.user} is connected to the following guild:\n'
UnboundLocalError: local variable 'guild' referenced before assignment
Idk where it found "guild" variable, please help me removing this error!
The problem is most likely that, guild may not be defined. For example:
This works:
for my_var in [0, 1]:
pass
print(my_var)
This gives a NameError, because my_var is never defined.
for my_var in []:
pass
print(my_var)
You need to set a default value for guild (you can do this by putting guild=None
above your for-loop) or by putting the print statement inside the for-loop.
It was little big for comment.
I have changed your code a litte. As eror is unknown. This code will at least help you to identify error import os
import discord
import os
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = discord.Client()
@client.event
async def on_ready():
print(client.guilds) # try to print number of child of client.guilds. I think they are Zero
for guild in client.guilds:
if guild.name == GUILD:
break # This break does not gurantee guild is initalized
# safety check to make code showing proper error
if guild is not None:
print(dir(guild))
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})'
)
client.run(TOKEN)
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.