ARTICLE AD BOX
I'm trying to make a command for my Discord bot that plays music. However, it says that it's not connected to any voice channels.
Error message:
[2025-12-28 15:10:21,086] {_init_.py:173} ERROR - Code error in command play... Traceback (most recent call last): File "C:\Users\rain\.virtualenvs\TWM-LveKoQPz\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped ret = await coro(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rain\Documents\TWM\TWM\cogs\voice.py", line 146, in play voice.play(source) File "C:\Users\rain\.virtualenvs\TWM-LveKoQPz\Lib\site-packages\discord\voice_client.py", line 605, in play raise ClientException('Not connected to voice.') discord.errors.ClientException: Not connected to voice.Here's some of the code. There's more, but I didn't include it.
@commands.command() async def play(self, ctx, *, arg): """ Checks where the command's author is, searches for the requested music, joins the same channel as the command's author, and then plays the audio directly from YouTube. :param ctx: discord.ext.commands.Context :param arg: str arg can be a YouTube URL or a normal search query. :return: None """ try: voice_channel = ctx.author.voice.channel # If the command's author is not connected, return. except AttributeError as e: print(e) await ctx.send("Please connect to the voice channel first!") return # Finds the author's session. session = ctx.guild.voice_client # Searches for the video. with yt_dlp.YoutubeDL({'format': 'bestaudio', 'noplaylist': 'True'}) as ydl: try: requests.get(arg) except Exception as e: print(e) info = ydl.extract_info( f"ytsearch:{arg}", download=False )['entries'][0] else: info = ydl.extract_info(arg, download=False) url = info['formats'][0]['url'] thumb = info['thumbnails'][0]['url'] title = info['title'] # Finds an available voice client for the bot. voice = ctx.guild.voice_client if not voice: await voice_channel.connect() voice = ctx.guild.voice_client await ctx.send(thumb) await ctx.send(f"Playing {title}") source = await discord.FFmpegOpusAudio.from_probe( url, **FFMPEG_OPTIONS ) voice.play(source)