0
votes

I'm trying to make a discord bot that gives a user role when they join a voice channel and removes the role when they leave it. I know about on_voice_state_update and how to give a user a role but I don't know how to get what user joined the channel to give them the role.

Right now my code is slightly modified version of the answer from How to use discord.py event handler on_voice_state_update to run only when a user joins a voice channel.

@client.event
async def on_voice_state_update(before, after ):
    if before.voice.voice_channel is None and after.voice.voice_channel is not None:
        for channel in before.server.channels:
            if channel.name == 'general':
                await client.send_message(channel, "User joined")

elif before.voice.voice_channel is not None and after.voice.voice_channel is None:
    for channel in before.server.channels:
        if channel.name == 'general':
            await client.send_message(channel, "User left");
2

2 Answers

1
votes

Three months late, but for anyone who stumbles upon this later, here's the rewite (1.0) branch version.

# VC PROCESSING
@client.event
async def on_voice_state_update(member, before, after):
    if not before.channel and after.channel:
        role = discord.utils.get(member.guild.roles, name="role name")
        await member.add_roles(role)
    elif before.channel and not after.channel:
        role = discord.utils.get(member.guild.roles, name="role name")
        await member.remove_roles(role)
0
votes

after is the Member object as it exists "now", after the voice state has changed. That would be the member object that you pass to add_roles

@client.event
async def on_voice_state_update(before, after ):
    role = discord.utils.get(after.server.roles, name="YOUR ROLE NAME")
    if not before.voice.voice_channel and after.voice.voice_channel:
        await client.add_roles(after, role)
    elif before.voice.voice_channel and not after.voice.voice_channel:
        await client.remove_roles(after, role)