Dev
Dev

Reputation: 1

Discord bot not joining to play audio on voice channel

I have created a discord bot that is meant to join a channel and play youtube audio in that channel.

I dont recieve any errors but It doesnt join the voice channel of the user who sent a message containing '?play'. I have checked to see if it was a permissions issue and the bot has every permission aside from admin. I have also noticed that the error message doesnt trigger either. I would like any solutions to get the bot to correctly join a voice channel.

Heres the code

Ive removed the token just for this post

# Importing libraries
import discord
import os
import asyncio
import youtube_dl
import time

# Discord bot Initialization
client = discord.Client(intents=discord.Intents.default())
key = ""

voice_clients = {}

yt_dl_opts = {'format': 'bestaudio/best'}
ytdl = youtube_dl.YoutubeDL(yt_dl_opts)

ffmpeg_options = {'options': "-vn"}


# This event happens when the bot gets run
@client.event
async def on_ready():
    print(f"Bot logged in as {client.user}")


# This event happens when a message gets sent
@client.event
async def on_message(msg):
    if msg.content.startswith("?play"):

        try:
            voice_client = await msg.author.voice.channel.connect()
            voice_clients[voice_client.guild.id] = voice_client
        except:
            print("error")

        try:
            url = msg.content.split()[1]

            loop = asyncio.get_event_loop()
            data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=False))

            song = data['url']
            player = discord.FFmpegPCMAudio(song, **ffmpeg_options)

            voice_clients[msg.guild.id].play(player)

        except Exception as err:
            print(err)


    if msg.content.startswith("?pause"):
        try:
            voice_clients[msg.guild.id].pause()
        except Exception as err:
            print(err)

    # This resumes the current song playing if it's been paused
    if msg.content.startswith("?resume"):
        try:
            voice_clients[msg.guild.id].resume()
        except Exception as err:
            print(err)

    # This stops the current playing song
    if msg.content.startswith("?stop"):
        try:
            voice_clients[msg.guild.id].stop()
            await voice_clients[msg.guild.id].disconnect()
        except Exception as err:
            print(err)


client.run(key)

Upvotes: 0

Views: 173

Answers (1)

Jonath Kane
Jonath Kane

Reputation: 1

So it just so happens I tested a bot on a new computer tonight and we figured out the issue with a good old try catch:

        try:
...
        except Exception as e:
            await ctx.send("Exception: " + str(e))

In our case it was because I hadn't installed the PyNaCl library and so testing the command I got the message

Exception: PyNaCl library needed in order to use voice

In your case it could be another exception however.

Upvotes: 0

Related Questions