Teaspoon
Teaspoon

Reputation: 35

How to access member when calling on_member_update in discord.py?

I am trying to create a discord bot that adds a specific role to a member once the member goes offline/invisible.

This is my code.

@ bot.event
async def on_member_update(before, after):
    if str(before.status) == "online":
        if str(after.status) == "offline":
            guild = bot.get_guild(1234567890)
            role = discord.utils.find(lambda r: r.name == 'rolename', guild.roles)
            await member.add_roles(role)

Every time I run it, I get an error saying that member is not defined. How do I define member as the person who updated their status? Thanks.

Upvotes: 3

Views: 8870

Answers (1)

Diggy.
Diggy.

Reputation: 6944

The parameters before and after are both member objects, meaning that you can just use either for adding the roles:

@bot.event
async def on_member_update(before, after):
    if str(before.status) == "online":
        if str(after.status) == "offline":
            # also would be able to get the guild via after.guild or before.guild
            guild = bot.get_guild(1234567890)
            role = discord.utils.find(lambda r: r.name == 'rolename', guild.roles)
            await after.add_roles(role)

The parameters are simply;

  • The discord.Member object prior to the update, i.e. before
  • The discord.Member object after the update, i.e. after

References:

Upvotes: 4

Related Questions