Is there a way to play audio without calling the connect command? (pycord)

Question:

In my implementation whenever I call the play method while the bot is connected to the voice channel, it will throw an error. However, the official documentation, including other videos on the matter, use the same method. The main reason I found is that the call for the connect method is necessary, as it values ‘voice’ as a VoiceProtocol, which is further necessary to use the play method for playing audio.

@bot.slash_command(guild_ids=[])
async def play(ctx, audio):
channel = ctx.author.voice.channel
voice = await channel.connect()
audio_source = discord.FFmpegPCMAudio(source=f'audio/{audio}.mp3', executable='C:/FFmpeg/bin/ffmpeg.exe')
voice.play(audio_source)
await ctx.respond(f'Now playing `{audio}`')

If the bot is already in the voice channel when I call

voice = await channel.connect()

then it will throw the error

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ClientException: Already connected to a voice channel.

This is the exact method the official documentation of pycord uses to play audio here

Asked By: Sprunk

||

Answers:

You can get the voice client from guild.voice_client. Check than before connecting

if ctx.guild.voice_client:
    voice = ctx.guild.voice_client
else:
    voice = await channel.connect()
Answered By: The om