1

我编写了一个相当复杂的 Discord 机器人,但引起问题的是一个简单的音乐功能,它使用 youtube_dl 和 ffmpeg。这是一个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)

在我相当普通的笔记本电脑上运行代码,它几乎总是适用于较短的视频。但是,我注意到如果视频下载或转换为 mp3 格式的时间过长,则会出现以下错误(或类似错误):

[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

一旦发生错误,整个机器人似乎停止正常工作。我已经进行了广泛的搜索,但无法提出解决方案。理想情况下,我希望修复此错误,但如果这不可能(例如,它依赖于快速下载速度),那么我至少希望正确处理此错误,以便机器人的其余部分仍然可以运行。

4

0 回答 0