How to create invite when bot joins server

Viewed 228

I am trying to create a discord bot and I want it to create an invite to any server it joins. All I need help with is one line of code. I need to actually create the invite but I get:

Atribute Error: 'Guild' object has no attribute 'channel'

It happens on this line:

invite = await guild.channel.create_invite(reason=None, max_age=0, max_uses=0, temporary=False, unique=True)

The full block:

@client.event
async def on_guild_join(guild):
    invite = await guild.channel.create_invite(reason=None, max_age=0, max_uses=0, temporary=False, unique=True)
    
    with open("invites.json", "r") as f:
        invites = json.load(f)

    invites[guild.name] = invite # This line might have an issue but i havent got to test it yet

    with open("invites.json", "w") as f:
        json.dump(invites, f)

I know how to create an invite with a command but theres no ctx on on_guild_join (i dont think). Would i just have to add 'ctx' somewhere in the event arguments?

3 Answers

there is an issue with your code that is explained in the Error you are getting. You are trying to get a channel from a Guild, although they are stored by another name text_channels. You can access this list and select any one, and then create_invite on the particular channel.

Here is how your code should look like:

@client.event
async def on_guild_join(guild):
    invite = await guild.text_channels[0].create_invite(reason=None, max_age=0, max_uses=0, temporary=False, unique=True)

    print(invite)
    with open("invites.json", "r") as f:
        invites = json.load(f)

    invites[guild.name] = invite
    with open("invites.json", "w") as f:
        json.dump(invites, f)

You need to specify channle to create an invite. For example:

@client.event
async def on_guild_join(guild):
    try:
        invite = await guild.text_channels[0].create_invite(reason=None, max_age=0, max_uses=0, temporary=False, unique=True)
    except IndexError:
        pass

This code creates an invite to the first of text channels in guild.

Hey i know its old post but i found an answer for this problem (Its workin for me so..)

Its easy, you can use the code that @Monka posted. But you need to edit this line

invites[guild.name] = invite

to:

invites[str(guild.name)] = invite

New to stackoverflow so sorry for formatting.. Hope you understand it :D

Related