Discord.py 当在播放命令中给出 youtube link 时,音乐机器人引发 TypeError

Discord.py music bot raising TypeError when a youtube link is given in the play command

当我在播放命令中输入 youtube url 时,我的 discord 机器人会引发 TypeError。 当我给出一个音乐名称时它会起作用,但当我给出一个 url 比如 https://youtu.be/ylVnYh-b3Qg..... 时它不起作用。 我无法理解问题出在哪里...... 是在我的播放命令中还是在 MusicSource 中.... 在此先感谢您的帮助。

这是我写的代码:

class MusicSource(discord.PCMVolumeTransformer):
    youtube_dl.utils.bug_reports_message = lambda: ''  # Suppressing Random Youtube_Dl warnings
    ytdl_format_options = {  # options for the youtube_dl module, for the audio quality
        'format': 'bestaudio/best',
        'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
        'restrictfilenames': True,
        'noplaylist': True,
        'nocheckcertificate': True,
        'ignoreerrors': False,
        'logtostderr': False,
        'quiet': True,
        'no_warnings': True,
        'default_search': 'ytsearch',  # We will use Youtube for searching musics
        'source_address': '0.0.0.0',  # IPv6 causes problem sometimes so we are using IPv4
        'youtube_include_dash_manifest': False  # Turning off dash manifest
        # (Enabling it sometimes makes the bot not play anything)
    }
    ytdl = youtube_dl.YoutubeDL(ytdl_format_options)  # Sending the options to the Youtube_DL class

    def __init__(self, source: discord.AudioSource, *, data):
        self.volume = 0.4
        super().__init__(source, self.volume)
        self.data = data
        self.title = data.get('title')
        self.url = data.get('url')
        self.link = data.get('webpage_url')  # Fetching the youtube link for the song and
        # will be used later for sending it to the user
        self.time = data.get('duration')
        self.img = data.get('thumbnail')
        self.artist = data.get('artist')
        self.likes = data.get('like_count')
        self.dislikes = data.get('dislike_count')
        self.albm = data.get('album')

    @classmethod
    async def from_url(cls, url, *, loop=None, stream=False, timestamp=0):  # The player that plays the
        # audio from the url
        ffmpeg_options = {
            'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
            'options': f'-vn -ss {timestamp}'
        }
        loop = loop or asyncio.get_event_loop()
        data = await loop.run_in_executor(None, lambda: cls.ytdl.extract_info(url, download=not stream))
        if 'entries' in data:
            data = data['entries'][0]  # Taking the first item from the search results
            filename = data['url'] if stream else cls.ytdl.prepare_filename(data)
            return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)

以及加入和播放命令:

class Music(commands.Cog):
    def __init__(self, client):
        self.client = client
        self.player = dict()
        self.links = dict()
        self.auto_loop_is_on = dict()

    @commands.command(name="join", aliases=["j", "connect", "come", "fuck-on"])
    async def join_voice(self, ctx: commands.Context):
        voice_channel = ctx.author.voice
        if voice_channel is None:
            return await ctx.send("`Please connect to a voice channel first!`")
        if ctx.voice_client is not None:
            await ctx.voice_client.move_to(voice_channel.channel)
            return await ctx.send("`Voice channel shifted!`")
        elif ctx.voice_client is None:
            self.player[str(ctx.guild.id)] = None
            self.links[str(ctx.guild.id)] = list()
            self.auto_loop_is_on[str(ctx.guild.id)] = False
            await voice_channel.channel.connect()
            return await ctx.send("`Voice channel connected! Use <play> command to play a music`")


    @commands.command(name="play", aliases=["p"])
        async def play_(self, ctx: commands.Context, timestamp: Optional[int] = 0, *, url):
            if ctx.voice_client is None or ctx.author.voice is None:
                return await ctx.send("`Not connected to any voice!`")
            if ctx.voice_client.is_playing():
                self.links[str(ctx.guild.id)].append(url)
                await ctx.send(f"`Song {url} added to queue. `")
            elif not ctx.voice_client.is_playing():
                self.links[str(ctx.guild.id)].append(url)
                await ctx.send("`Loading awesomeness! Wait a bit. `")
                async with ctx.typing():
                    self.player[str(ctx.guild.id)] = await MusicSource.from_url(url=self.links[str(ctx.guild.id)][0],
                                                                            loop=self.client.loop, stream=True,
                                                                            timestamp=timestamp)
                ctx.voice_client.play(self.player[str(ctx.guild.id)], after=lambda x: self.play_next(ctx))

我得到的错误:

Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\Ronny\Python3.9\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\Ronny\PycharmProjects\XENON_DISCORD\Bot_Features\music.py", line 108, in play_
    ctx.voice_client.play(self.player[str(ctx.guild.id)], after=None)
  File "C:\Users\Ronny\Python3.9\lib\site-packages\discord\voice_client.py", line 561, in play
    raise TypeError('source must an AudioSource not {0.__class__.__name__}'.format(source))
TypeError: source must an AudioSource not NoneType

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Ronny\Python3.9\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Ronny\PycharmProjects\XENON_DISCORD\XENON.py", line 82, in on_command_error
    raise err
  File "C:\Users\Ronny\Python3.9\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Ronny\Python3.9\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Ronny\Python3.9\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: source must an AudioSource not NoneType

试试这个,它应该适用于 YouTube 歌曲名称和 YouTube URL:

import asyncio

import discord
import youtube_dl

from discord.ext import commands

# Suppress noise about console usage from errors
youtube_dl.utils.bug_reports_message = lambda: ''


ytdl_format_options = {
    'format': 'bestaudio/best',
    'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
    'restrictfilenames': True,
    'noplaylist': True,
    'nocheckcertificate': True,
    'ignoreerrors': False,
    'logtostderr': False,
    'quiet': True,
    'no_warnings': True,
    'default_search': 'auto',
    'source_address': '0.0.0.0' # bind to ipv4 since ipv6 addresses cause issues sometimes
}

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

ytdl = youtube_dl.YoutubeDL(ytdl_format_options)


class YTDLSource(discord.PCMVolumeTransformer):
    def __init__(self, source, *, data, volume=0.5):
        super().__init__(source, volume)

        self.data = data

        self.title = data.get('title')
        self.url = data.get('url')

    @classmethod
    async def from_url(cls, url, *, loop=None, stream=False):
        loop = loop or asyncio.get_event_loop()
        data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))

        if 'entries' in data:
            # take first item from a playlist
            data = data['entries'][0]

        filename = data['url'] if stream else ytdl.prepare_filename(data)
        return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)


class Music(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(description="joins a voice channel")
    async def join(self, ctx):
        if ctx.author.voice is None or ctx.author.voice.channel is None:
            return await ctx.send('You need to be in a voice channel to use this command!')

        voice_channel = ctx.author.voice.channel
        if ctx.voice_client is None:
            vc = await voice_channel.connect()
        else:
            await ctx.voice_client.move_to(voice_channel)
            vc = ctx.voice_client

    @commands.command(description="streams music")
    async def play(self, ctx, *, url):
        async with ctx.typing():
            player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
            ctx.voice_client.play(player, after=lambda e: print('Player error: %s' % e) if e else None)
        await ctx.send('Now playing: {}'.format(player.title))