discord.py: music bot keeps throwing OSError

Viewed 134

I've written a fairly complex Discord bot, but the bit that's causing issues is a simple music function, which uses youtube_dl and ffmpeg. Here's an mwe:

import discord
from discord.ext import commands
import youtube_dl

TOKEN = 'blah'
bot = commands.Bot(command_prefix='$')
ydl_opts = {
    'format': 'bestaudio',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
    'outtmpl': 'song.%(ext)s'
}

@bot.command(name='play')
async def play(ctx, url: str):
    voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)

    if not voice:
        v_state = ctx.author.voice
        if not v_state:
            await ctx.send('You\'re not in a voice channel.')
            return
        
        v_channel = v_state.channel
        voice = await v_channel.connect()
    
    if url:                
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download([url])
            
        if not voice.is_playing():
            voice.play(discord.FFmpegPCMAudio('song.mp3'))
            print(f'Now playing {url}')

bot.run(TOKEN)

Running the code on my fairly average laptop, it almost always works ok with shorter videos. However, I've noticed that if the video takes too long to download or convert to mp3 format, the following error (or similar) occurs:

[youtube] RJ0jdO5ZfU4: Downloading webpage
[download] Resuming download at byte 6104816
[download] Destination: song.m4a
[download] 100% of 33.79MiB in 00:04
[ffmpeg] Correcting container in "song.m4a"
[ffmpeg] Destination: song.mp3
Deleting original file song.m4a (pass -k to keep)
Now playing https://www.youtube.com/watch?v=RJ0jdO5ZfU4&t=2s
Exception in voice thread Thread-20
Traceback (most recent call last):
  File "C:\Users\leMingathon\anaconda3\lib\site-packages\discord\player.py", line 603, in run
    self._do_run()
  File "C:\Users\leMingathon\anaconda3\lib\site-packages\discord\player.py", line 596, in _do_run
    play_audio(data, encode=not self.source.is_opus())
  File "C:\Users\leMingathon\anaconda3\lib\site-packages\discord\voice_client.py", line 638, in send_audio_packet
    self.socket.sendto(packet, (self.endpoint_ip, self.voice_port))
OSError: [WinError 10038] An operation was attempted on something that is not a socket

Once the error occurs, the entire bot seems to stop working properly. I've searched far and wide but haven't been able to come up with a fix. Ideally I'd like this error to be fixed, but if that's not possible (e.g. it relies on fast download speeds), then I'd at least like to handle this error properly so that the rest of the bot can still function.

0 Answers
Related