Счетчик пользователей на голосовом канале

Я пытаюсь создать бота для discord. Нужно написать сообщение в чат, если на голосовом канале есть три человека. Бот понимает, когда человек заходит на канал или выходит из него, но переменная members принимает значения 1 и -1 при входе и выходе из канала соответственно. Также бот не видит, что пользователь ушел, если админ переводит его на другой канал.

@bot.event
async def on_voice_state_update(member, before, after):
    members = 0
    if before.channel != "id" and after.channel is not None: #channel id
        if after.channel.id == "id": #channel id
            members += 1
    else:
        if before.channel == "id" or after.channel is None: #channel id
            if before.channel.id == "id": #channel id
                members -= 1
    if members == 3:
        c = bot.get_channel("id") #txt channel id
        await c.send("text")

Как заставить счетчик работать и чтобы его значение также менялось, если админ перемещает пользователя?


Ответы (2 шт):

Автор решения: ginta_caro

В итоге я сделал то, что хотел:

intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", case_insensitive=True, intents=intents)

@bot.event
    async def on_voice_state_update(members, before, after):
        voice_channel = bot.get_channel(id).members #channel id
        voice_channel = len(voice_channel)
        if before.channel is None:
            if after.channel.id == id and voice_channel == 3: #channel id and 3 - the number of users required to perform actions
                c = bot.get_channel(id) #txt channel id
                await c.send("text")
        elif after.channel is None:
            pass
        else:
            if after.channel.id == id and before.channel.id != id and voice_channel == 3: #channel id and 3 - the number of users required to perform actions
                 c = bot.get_channel(id) #txt channel id
                 await c.send("text")
bot.run("token")

Бот отправляет сообщение на текстовый канал, когда на голосовом канале находится необходимое количество людей (в моем случае это 3).


PS
Если есть возможность как-то сократить код или сделать его лучше, я буду рад вашему совету.

→ Ссылка
Автор решения: Corrygan

Я думаю стоит убрать проверку if before.channel is None:, т.к. в нужный вам канал, пользователь мог зайти из другого.

@bot.event
async def on_voice_state_update(member, before, after):
    voice_channel = bot.get_channel(id)
    
    if after.channel is not None:
        if after.channel.id == id and len(voice_channel.members) >= 3:
            channel = bot.get_channel(id)
            await chaannel.send("text")
→ Ссылка