E
E
Evgeny Nikitenko2021-06-25 23:37:11
Python
Evgeny Nikitenko, 2021-06-25 23:37:11

How to make the bot disconnect from the voice channel?

I'm writing a discord bot in python. I wrote an event for connecting the bot to the voice channel (hereinafter referred to as GK), when the user connects to the GK, so that he plays a welcome excerpt from the song. But the problem is that when the bot connects to the channel and plays audio, later, when other users connect, it will not be able to play the passage, since it is already connected. I need to write a code in which, after playing the melody, it disconnected from the GC .

Here is the code:

@bot.event
async def on_voice_state_update(member, before, after):
  if after.channel and after.channel!=before.channel:
    VoiceClient = await after.channel.connect()
    VoiceClient.play(discord.FFmpegPCMAudio(executable = "C:/ffmpeg/bin/ffmpeg.exe" , source = "zvuk-jenskogo-opernogo-peniya-2.mp3"))

Here is the error:
discord.errors.ClientException: Already connected to a voice channel.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shadowzxc, 2021-06-27
@shadowzxc

@bot.event
async def on_voice_state_update(member, before, after):
    if after.channel and after.channel!=before.channel:
        VoiceClient = await after.channel.connect()
        VoiceClient.play(discord.FFmpegPCMAudio(executable = "C:/ffmpeg/bin/ffmpeg.exe" , source = "zvuk-jenskogo-opernogo-peniya-2.mp3"))
while VoiceClient.is_playing():
    await asyncio.sleep(1)
else:
    await asyncio.sleep(15)
    while VoiceClient.is_playing():
        break
    else:
        await VoiceClient.disconnect()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question