【问题标题】:Discord.py music_cog, bot joins channel but plays no soundDiscord.py music_cog,机器人加入频道但不播放声音
【发布时间】:2021-09-03 21:42:58
【问题描述】:

我大约一周前开始使用python。我已经在 YT 上观看了所有相关视频并检查了谷歌页面等。但仍然没有运气。我的机器人完美地加入了语音通道,当我使用播放时,它会下载并可能会启动播放功能,但没有声音或任何东西,它只是加入并等待 1-2 分钟然后离开并出现超时错误。

from discord.ext import commands
import logging

from youtube_dl import YoutubeDL

logging.basicConfig(level=logging.INFO)


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

        # all the music related stuff
        self.is_playing = False

        # 2d array containing [song, channel]
        self.music_queue = []
        self.YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True', 'no_warnings': 'False'}
        self.FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
                               'options': '-vn'}

        self.vc = ""

    # searching the item on youtube
    def search_yt(self, item):
        with YoutubeDL(self.YDL_OPTIONS) as ydl:
            try:
                info = ydl.extract_info("ytsearch:%s" % item, download=False)['entries'][0]
            except Exception:
                return False

        return {'source': info['formats'][0]['url'], 'title': info['title']}

    def play_next(self):
        if len(self.music_queue) > 0:
            self.is_playing = True

            # get the first url
            m_url = self.music_queue[0][0]['source']

            # remove the first element as you are currently playing it
            self.music_queue.pop(0)

            self.vc.play(discord.FFmpegPCMAudio(m_url, **self.FFMPEG_OPTIONS), after=lambda e: self.play_next())
        else:
            self.is_playing = False

    # infinite loop checking
    async def play_music(self):
        if len(self.music_queue) > 0:
            self.is_playing = True

            m_url = self.music_queue[0][0]['source']

            # try to connect to voice channel if you are not already connected

            if self.vc == "" or not self.vc.is_connected() or self.vc == None:
                self.vc = await self.music_queue[0][1].channel.connect()
            else:
                await self.vc.move_to(self.music_queue[0][1])

            print(self.music_queue)
            # remove the first element as you are currently playing it
            self.music_queue.pop(0)

            self.vc.play(discord.FFmpegPCMAudio(m_url, **self.FFMPEG_OPTIONS), after=lambda e: self.play_next())
        else:
            self.is_playing = False

    @commands.command(name="play", help="Plays a selected song from youtube")
    async def p(self, ctx, *args):
        query = " ".join(args)

        voice_channel = ctx.author.voice
        if voice_channel is None:
            # you need to be connected so that the bot knows where to go
            await ctx.send("Connect to a voice channel!")
        else:
            song = self.search_yt(query)
            if type(song) == type(True):
                await ctx.send(
                    "Could not download the song. Incorrect format try another keyword. This could be due to playlist or a livestream format.")
            else:
                await ctx.send("Song added to the queue")
                self.music_queue.append([song, voice_channel])

                if self.is_playing == False:
                    await self.play_music()

    @commands.command(name="queue", help="Displays the current songs in queue")
    async def q(self, ctx):
        retval = ""
        for i in range(0, len(self.music_queue)):
            retval += self.music_queue[i][0]['title'] + "\n"

        print(retval)
        if retval != "":
            await ctx.send(retval)
        else:
            await ctx.send("No music in queue")

    @commands.command(name="skip", help="Skips the current song being played")
    async def skip(self, ctx):
        if self.vc != "" and self.vc:
            self.vc.stop()
            await ctx.send("Stopped!")
            # try to play next in the queue if it exists
            await self.play_music()
            await ctx.send("Skipped!")


def setup(bot):
    bot.add_cog(music_cog(bot))

我确实启用了日志,当它连接时只有那个信息:

INFO:discord.voice_client:Connecting to voice... | INFO:discord.voice_client:Starting voice handshake... (connection attempt 1)

我还检查了 FFMPEG 及其路径,尝试了不同的代码和方法,但即使它们有效,也没有声音。我也安装了 discord.py[voice]。

感谢您的帮助,谢谢。

【问题讨论】:

    标签: python ffmpeg discord discord.py youtube-dl


    【解决方案1】:

    我在 19 小时后发现了它的意图

    intents = discord.Intents(messages=True, guilds=True, reactions=True, members=True, presences=True)
    

    阻止机器人连接到 voice_channel 服务器,即使它看起来像是在语音通道中。

    删除它解决了我的问题。

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 2021-12-08
      • 2021-05-05
      • 2020-08-30
      • 2019-04-08
      • 2019-05-05
      • 2014-06-13
      • 1970-01-01
      • 2023-02-25
      相关资源
      最近更新 更多