Python Nextcord Discord bot MusicCog doesn't play music from Spotify

44 Views Asked by At

I was trying to make a Discord bot for my server and i decided to add music using the Spotipy lib. The bot joins the channel but when i call the command "!play ..." nothing happens: the bot simply just says "Now playing: ..." and then everything is mute. (I'm sorry for my shitty english, it's not my main language...)

I checked the permissions, but thats not the problem: it has every permission and Administrator, then I checked the Spotify Developer codes (That I will censor for security reasons) and they are also good. I don't know if it's my code since I'm not that good with third-party libs.

Here's my code:

main.py:

import nextcord, os, config
from nextcord.ext import commands

intents = nextcord.Intents.all()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

@bot.event
async def on_ready():
    
    print("_______________________________________________________________")
    print(f"\nSuccessfully logged in as {bot.user.name} ({bot.user.id})\n")
    print("_______________________________________________________________")
    

# LOAD COGS
for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        bot.load_extension(f"cogs.{filename[:-3]}")
    

bot.run(config.TOKEN)

And here's the music.py Cog:

import nextcord
from nextcord.ext import commands
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

class Music(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.voice = None
        self.sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id='//////', client_secret='/////'))

    @commands.command()
    async def join(self, ctx):
        if ctx.author.voice:
            self.voice = await ctx.author.voice.channel.connect()
            await ctx.send(f"Joined {ctx.author.voice.channel.name} voice channel.")
        else:
            await ctx.send("You need to be in a voice channel to use this command.")

    @commands.command()
    async def leave(self, ctx):
        if self.voice:
            await self.voice.disconnect()
            self.voice = None
            await ctx.send("Left the voice channel.")
        else:
            await ctx.send("I'm not connected to a voice channel.")

    @commands.command()
    async def play(self, ctx, *, query: str):
        if not self.voice or not self.voice.is_connected():
            await ctx.send("I'm not connected to a voice channel. Use `!join` first.")
            return

        try:
            # Search for the track on Spotify
            track_info = self.sp.search(q=query, type='track', limit=1)
            
            # Check if any tracks were found
            if not track_info or not track_info['tracks']['items']:
                await ctx.send("Couldn't find any matching tracks.")
                return

            # Get the first track found
            track = track_info['tracks']['items'][0]
            track_url = track['external_urls']['spotify']

            # Load and play the track
            source = await nextcord.FFmpegOpusAudio.from_probe(track_url)
            self.voice.play(source)

            # Send a message indicating the track is playing
            await ctx.send(f"Now playing: {track['name']} by {', '.join(artist['name'] for artist in track['artists'])}")
        except Exception as e:
            # Handle any errors that occur during track playback
            await ctx.send(f"An error occurred while playing the track: {e}")

    @commands.command()
    async def skip(self, ctx):
        if ctx.voice_client:
            ctx.voice_client.stop()
            await ctx.send("Skipped the current song.")

    @commands.command()
    async def stop(self, ctx):
        if ctx.voice_client:
            await ctx.voice_client.disconnect()
            self.voice = None
            await ctx.send("Stopped and disconnected from the voice channel.")

def setup(bot):
    bot.add_cog(Music(bot))
    print("MusicCog was loaded")

I also tried using the help of some AI's but they didn't even have the idea of what to do... Does someone know how to fix this?

0

There are 0 best solutions below