0

I've searched a lot on stack overflow, but cant seem to find anything about this. Is there an event that makes something happen when the bot leaves the server?

I have it so that when a command is run, it sets a variable to be on, and when that variable is on it makes a message happen in every channel created like so:

@client.command(pass_context=True)
async def channel(ctx):
    global Toggle
    Toggle = True
    await ctx.send("Channel messages enabled!")

@client.event
async def on_guild_channel_create(channel):
    if Toggle == True:
        await channel.send("HELLO :D")
    else:
        pass

Problem is, when !channel is run, it makes this server wide. How would i make it so that when a bot leaves, toggle is reverted to false?

4m w31rd
  • 23
  • 5

1 Answers1

1

There's a on_guild_remove event that fires when:

  • The client got banned.
  • The client got kicked.
  • The client left the guild.
  • The client or the guild owner deleted the guild.
@client.event
async def on_guild_remove(guild: discord.Guild):
    # one of the above has just happened
    global Toggle
    print(f"Removed from: {guild.id}")
    Toggle = False

For reference, all the possible events are here. Very useful to consult when looking to add functionality and you're not sure if there's an existing event or not. Additionally, the discord events docs are here.

On a side note, with Python you don't need to do if Toggle == True:. If Toggle is a boolean (or can be inferred to be either True/False) then if Toggle: is sufficient.

@client.event
async def on_guild_channel_create(channel):
    if Toggle:
        await channel.send("HELLO :D")

There's an answer here with more details.

ESloman
  • 1,961
  • 1
  • 10
  • 14