Voice Commands

Guide to creating Voice Channel related commands in Py-cord.

This guide has been moved to https://namantech.me/pycord. Please visit the new guide instead, since this one might be outdated.

The new guide looks better, has better explanations, and is way better overall.

Installing

To use voice commands, you need to update your library first -

# Linux/macOS
python3 -m pip install -U "py-cord[voice]"

# Windows
py -3 -m pip install -U py-cord[voice]

Joining and Leaving

Join Command

First of all, we want to make a command that will make the bot join our VC.

@bot.command()
async def join(ctx):
    voice = ctx.message.author.voice

    if voice != None:
        await voice.channel.connect()
        await ctx.send(f"Connected and bound to {voice.channel.mention}!")
    else:
        await ctx.send(
            "You need to be connected to a voice channel to use this command!"
        )

When the user is not connected to a channel, the voice variable returns none. When it

Next, if the user is connected, we connect the the channel too, using await channel.connect()

Now, we have a problem. We left the VC, but our bot is stuck there. So, we need to make a leave command to make the bot leave the VC.

Leave Command

@bot.command()
async def leave(ctx):
    voice = ctx.voice_client
    if voice != None:
        await voice.disconnect()
        await ctx.send(f"Left the VC!")
    else:
        await ctx.send("I am not connected to any voice channel!")

This command will make the bot leave ANY VC that it is in, as well as inform the user if the bot is not in a VC.

We can also make it necessary for the user to be in a Voice Channel to use this command, similar to the join command, but we don't want it, so lets not do it for now.

Playing Audio

Playing local audio files

@bot.command(name="play")
async def play(ctx):
    voice_channel = ctx.author.voice.channel
    if voice_channel != None:
        vc = await voice_channel.connect()
        vc.play(
            discord.FFmpegPCMAudio(
                executable=r"C:\Path\ffmpeg.exe",
                source=r"C:\Users\HP\Downloads\never_gonna_give_you_up.mp3",
            )
        )
        await ctx.send(f"Connected to {voice_channel.name}, playing audio.")
    else:
        await ctx.send("You need to be in a voice channel to use this command")

This is how you play local audio files.

Remember to replace Path and source with your own values.

Eg. C:\KMPlayer\ffmprg.exe for me. You can find the path through searching in file explorer on windows.

Can you play music through YouTube or Spotify?

Its possible to so by using libraries such as YouTube-dl, however, downloading videos from YouTube is in breach of YouTube's Terms of Service, and the company could sue you.

Last updated