Search code examples
pythondiscorddiscord.pynextcord

Nonetype object has no a attribute leave nextcord


CODE:

@client.event
async def on_guild_join(guild):
    with open('Servers.txt', "w", encoding="utf-8")as f:
        server_id = guild.id
        str_id = str(server_id)
        f.write("\n " + str_id)
    server = client.get_guild("server_id")
    await server.leave()

Error:

await server.leave("server_id") ^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'leave' Can someone help me find solution for this error?

I'm trying to get server ID upon joining. Write it into text file and then leave the server. I don't know how to leave the server. Upon reading documentation I'm completly clueless.


Solution

  • The guild object provided already has an attribute for the id. Using the provided id from the guild object, you can save an API call (or most likely an internal cache lookup).

    Fixed version

    @client.event
    async def on_guild_join(guild):
        #  Depending on your intention you might have meant to append to the existing "Servers.txt". 
        #  If so use "a" instead of "w" when you are opening the file.
        with open('Servers.txt', "w", encoding="utf-8")as f:
            f.write("\n " + str(guild.id))
        await guild.leave()