Home > OS >  UnboundLocalError: local variable 'guild' referenced before assignment
UnboundLocalError: local variable 'guild' referenced before assignment

Time:12-20

I want to make something so that when script starts, it gets information about members in guilds like the id, guild id.

I have this code:

    async def on_ready(self):
        for guild in guild:
            for member in guild.members:
                values = {
                    "_id":member.id,
                    "guild_id":guild.id,
                    "warns": 0 ,
                    "reasons": []
                }
                server_values = {
                    "_id": guild.id,
                    "case": 0
                }
                if collusers.count_documents({"_id": member.id, "guild_id": guild.id}) == 0:
                    collusers.insert_one(values)    
                if collservers.count_documents ({"_id": guild.id}) == 0:
                    collservers.insert_one(server_values)

But I also get an error:

Ignoring exception in on_ready
Traceback (most recent call last):
  File "C:\Users\Andriyko\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 351, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Andriyko\Desktop\Ghostbot\modules\warn.py", line 18, in on_ready       
    for guild in guild:
UnboundLocalError: local variable 'guild' referenced before assignment

CodePudding user response:

You didn't assign anything to variable guild. You can get all guilds that your bot is in with:

for guild in self.client.guilds:

You can also get the guild object first (if you want to run it only for one guild) with:

guilds = client.get_guild(id)

for guild in guilds:
    ...

Also, remember that you have to enable intents.Members to get guild.members.

  • Related