Search code examples
pythonpython-3.xdiscorddiscord.py

on_voice_state_update() not running as expected when going [vc -> vc]


The following code is meant to change the name of a voice channel depending on what game is being played. It works perfectly when the state change is [NONE -> vc] & [vc -> None] but not when going vc -> vc.

@client.event
async def on_voice_state_update(member, before, after):
    
    channel = before.channel
    print("debug 1")
    try:
        print("debug 2")
        if len(channel.members) == 0:
            print("debug 3")
            if str(channel.name).startswith("Currently"):
                print("debug 4")
                await channel.edit(user_limit=0, name="💤|Dormant", overwrites=discord.PermissionOverwrite(read_messages = False))
                await asyncio.sleep(600)
                await channel.edit(name="Waiting for game to be played...", roles=None, reason="The voice channel was empty")
                await channel.set_permissions(role=discord.Role.name())
        else:
            print("debug 5")
    except Exception:
        print("Leaving phase was not called")
        
    try:
        channel = after.channel
        print(f"There was an update in id: {channel.id}")
        if channel.name == "Waiting for game to be played...":
            print(f"user {member.name} joined")
            new_name = f"Currently playing: {discord.utils.get(member.activities, type=discord.ActivityType.playing)}"
            member_names = channel.members
            await channel.edit(name=new_name, roles=None, reason=f"{member_names[0]} started playing {new_name}")
    except Exception:
        print("Joining phase was not called")

Why is that, and how do I fix it?

The expected behavior is that the name of the old channel will be switched to "💤|Dormant" if it's empty, and no changes will be made if it's not. The new channel should also have it's name switched to whatever game is being played in said channel, see: await channel.edit(name=new_name, roles=None, reason=f"{member_names[0]} started playing {new_name}")

Edit:

I made some changes to the code and now it runs the joining phase when going [vc -> vc] but not the leaving phase in any instance ([vc -> vc], [vc -> None])


Solution

  • Maybe for the beginning you should make. This checking when your action take field.

    if before.channel is None and after.channel is not None:
       ## do your stuff here
       
    elif before.channel is not None and after.channel is None:
       ## do your stuff here
       
    

    I use this one for logging and monitoring someone who and when he/she joined channel in my server.