Home > Software engineering >  NameError: name 'guild' is not defined
NameError: name 'guild' is not defined

Time:12-20

I want to make thing like when member join and bot join a guild, I get information about members in guilds like: id, guild id. warns and reason.

    @commands.Cog.listener()
    async def on_member_join(self,member):
        values = {
            "_id":member.id,
            "guild_id": guild.id,
            "warns": 0 ,
            "reasons": []
        }
        if collusers.count_documents({"_id": member.id, "guild_id": self.bot.guild.id}) == 0:
            collusers.insert_one(values) 

    @commands.Cog.listener()
    async def on_guild_join(guild):
        server_values = {
            "_id": guild.id,
            "case": 0,
        }
        if collservers.count_documents ({"_id": guild.id}) == 0:
            collservers.insert_one(server_values)

I have error like this

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 39, in on_member_join
    "guild_id": guild.id,
NameError: name 'guild' is not defined

CodePudding user response:

You don't have guild defined in the first listener on_member_join. You can easily get the guild though with the member argument that is passed through.

Another thing I noticed was that you're passing in self.bot.guild.id which won't work since the bot can be in multiple guilds (and there isn't a guild property of self.bot. Just use member.guild.id again here.

@commands.Cog.listener()
async def on_member_join(self,member):
    guild = member.guild
    values = {
        "_id":member.id,
        "guild_id": guild.id,
        "warns": 0 ,
        "reasons": []
    }
    if collusers.count_documents({"_id": member.id, "guild_id": guild.id}) == 0:
        collusers.insert_one(values) 
  • Related