Python Discord音乐机器人在任何歌曲播放几分钟后停止播放。

huangapple go评论65阅读模式
英文:

Python Discord music bot stops playing a couple of minutes into any song

问题

我正在尝试组建一个Python Discord音乐机器人,作为一个有趣的小项目。除了必需的discord库,我目前正在使用YouTube API来搜索视频并解析URL(代码中未显示),yt-dlp,它是yt_download的分支,仍在维护中,用于从YT URL获取信息,并使用FFMPEG通过机器人播放yt-dlp获取的歌曲。我的播放命令似乎可以正常工作,第1个YT视频结果将开始播放,但在音频进行大约30-90秒后,它停止播放。我在控制台中收到以下消息:

2023-02-23 14:54:44 IN discord.player ffmpeg process 4848 successfully terminated with return code of 0.  <= 音频停止

所以我没有错误信息可以参考。我已经在下面包含了完整的控制台输出...

我目前正在Windows 11机器上开发此项目,但在我的Ubuntu机器上运行时也出现了此问题。我只是从VSCode终端直接托管机器人进行开发。

我一直在尝试研究这个问题,问题是我找不到最近的信息来解决此问题。有另一个帖子提到了类似的问题,并提出了建议使用以下FFMPEG选项,但我尝试了无效:

FFMPEG_OPTIONS = {
    'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
    'options': '-vn',
}

以下是你提供的代码的部分翻译,只包括与问题相关的部分:

import discord
from discord.ext import commands
from discord import FFmpegPCMAudio
import responses
import youtubeSearch as YT
import yt_dlp

# 创建一个Discord客户端
def run_discord_bot():
    intents = discord.Intents.default()
    intents.message_content = True

    TOKEN = 'xxxxxx'  # 你的Discord机器人令牌
    client = commands.Bot(command_prefix='-', intents=intents)

    @client.event
    async def on_ready():
        print('-----------------------------------')
        print(f'{client.user} is up and running')
        print('-----------------------------------')

    # 播放音乐命令
    @client.command(name='play', aliases=['p'], pass_context=True)
    async def play(ctx, *, search_term: str = None):
        if ctx.author.voice:
            voice = None
            if search_term is None:
                await ctx.send('No song specified.')
                return
            if not ctx.voice_client:
                channel = ctx.message.author.voice.channel
                voice = await channel.connect()
            else:
                voice = ctx.guild.voice_client

            # 从YouTube搜索获取URL
            url = YT.singleSearch(search_term)

            # YT-DLP选项
            YTDLP_OPTIONS = {
                'format': 'bestaudio/best',
                'extractaudio': True,
                'audioformat': 'mp3',
                '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',
                'source_address': '0.0.0.0',
            }

            # FFMPEG选项
            FFMPEG_OPTIONS = {
                'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
                'options': '-vn',
            }

            with yt_dlp.YoutubeDL(YTDLP_OPTIONS) as ydl:
                info = ydl.extract_info(url, download=False)
                playUrl = info['url']

            # 播放音乐
            source = FFmpegPCMAudio(playUrl, options=FFMPEG_OPTIONS)
            voice.play(source)
        else:
            await ctx.send('You must be in a voice channel to play a song!')

    # 其他命令部分...

    client.run(TOKEN)  # 运行Discord机器人

# 启动Discord机器人
run_discord_bot()

希望这些信息有助于解决你的问题。如果你有任何其他问题,请随时提出。

英文:

I am trying to put together a Python Discord music bot as a fun little project. Outside of the required discord library I'm currently using the YouTube API to search for videos and parse the URL (not shown in code), yt-dlp which is a fork of yt_download that is still maintained to get the info from the YT URL, and FFMPEG to play the song obtained from yt-dlp through the bot. My play command seems to work as the 1st YT video result will start to play, but roughly 30-90 seconds into the audio, it stops playing. I get this message in the console:

2023-02-23 14:54:44 IN discord.player ffmpeg process 4848 successfully terminated with return code of 0.

So there is no error for me to go off of. I've included the full output from the console below...

-----------------------------------
groovy-jr#6741 is up and running
-----------------------------------
2023-02-23 14:53:23 INFO     discord.voice_client Connecting to voice...
2023-02-23 14:53:23 INFO     discord.voice_client Starting voice handshake... (connection attempt 1)
2023-02-23 14:53:24 INFO     discord.voice_client Voice handshake complete. Endpoint found us-south1655.discord.media
2023-02-23 14:54:44 INFO     discord.player ffmpeg process 4848 successfully terminated with return code of 0.  &lt;= AUDIO STOPS

I'm currently developing this project on a Windows 11 machine, but I've had the issue running it on my Ubuntu machine as well. I am just hosting the bot directly from the VSCode terminal for development.

I've been trying to do research on this problem, the problem is I can't find many recent information for the issue. There was another post that talked about a similar problem and had an answer suggesting the following FFMPEG options be used which I tried to no avail.

FFMPEG_OPTIONS = {
&#39;before_options&#39;: &#39;-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5&#39;,
&#39;options&#39;: &#39;-vn&#39;,
}

I'll include the problem file below:

import discord
from discord.ext import commands
from discord import FFmpegPCMAudio
import responses
import youtubeSearch as YT
import yt_dlp
async def send_message(message, user_message, is_private = False):
try:
response = responses.handle_response(user_message)
await message.author.send(response) if is_private else await message.channel.send(response)
except Exception as e:
print(e)
def run_discord_bot():
intents = discord.Intents.default()
intents.message_content = True
TOKEN = &#39;xxxxxx&#39;
client = commands.Bot(command_prefix = &#39;-&#39;, intents=intents)
@client.event
async def on_ready():
print(&#39;-----------------------------------&#39;)
print(f&#39;{client.user} is up and running&#39;)
print(&#39;-----------------------------------&#39;)
@client.command(name=&#39;play&#39;, aliases=[&#39;p&#39;], pass_context = True)
async def play(ctx, *, search_term:str = None):
if ctx.author.voice:
voice = None
if search_term == None:
await ctx.send(&#39;No song specified.&#39;)
return
if not ctx.voice_client:
channel = ctx.message.author.voice.channel
voice = await channel.connect()
else:
voice = ctx.guild.voice_client
url = YT.singleSearch(search_term)
YTDLP_OPTIONS = {
&#39;format&#39;: &#39;bestaudio/best&#39;,
&#39;extractaudio&#39;: True,
&#39;audioformat&#39;: &#39;mp3&#39;,
&#39;outtmpl&#39;: &#39;%(extractor)s-%(id)s-%(title)s.%(ext)s&#39;,
&#39;restrictfilenames&#39;: True,
&#39;noplaylist&#39;: True,
&#39;nocheckcertificate&#39;: True,
&#39;ignoreerrors&#39;: False,
&#39;logtostderr&#39;: False,
&#39;quiet&#39;: True,
&#39;no_warnings&#39;: True,
&#39;default_search&#39;: &#39;ytsearch&#39;,
&#39;source_address&#39;: &#39;0.0.0.0&#39;,
}
=====&gt;     FFMPEG_OPTIONS = {
&#39;before_options&#39;: &#39;-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5&#39;,
&#39;options&#39;: &#39;-vn&#39;,
}
with yt_dlp.YoutubeDL(YTDLP_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
playUrl = info[&#39;url&#39;]
source = FFmpegPCMAudio(playUrl, options=FFMPEG_OPTIONS)
voice.play(source)
else:
await ctx.send(&#39;You must be in a voice channel to play a song!&#39;)
return
@client.command(pass_context = True)
async def leave(ctx):
if ctx.voice_client:
await ctx.guild.voice_client.disconnect()
else:
await ctx.send(&quot;I&#39;m not in a voice channel!&quot;)
@client.command(pass_context = True)
async def pause(ctx):
voice = discord.utils.get(client.voice_clients, guild = ctx.guild)
if voice.is_playing():
voice.pause()
else:
await ctx.send(&#39;No audio playing...&#39;)
@client.command(pass_context = True)
async def resume(ctx):
voice = discord.utils.get(client.voice_clients, guild = ctx.guild)
if voice.is_paused():
voice.resume()
else:
await ctx.send(&#39;No audio paused...&#39;)
@client.command(pass_context = True)
async def stop(ctx):
voice = discord.utils.get(client.voice_clients, guild = ctx.guild)
voice.stop()
client.run(TOKEN)

I appreciate any guidance I can get!

答案1

得分: 1

以下是翻译好的部分:

我也遇到了相同的问题。像下面这样传递选项对我有用:

source = FFmpegPCMAudio(source=playUrl,before_options="-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5",options="-vn")
英文:

I was also facing the same issue. Passing in the options like below worked for me

source = FFmpegPCMAudio(source=playUrl,before_options=&quot;-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5&quot;,options=&quot;-vn&quot;)

答案2

得分: -1

不正常运行在Ubuntu上可能是与库安装有关,因此某些软件包可能无法正常安装,但可以使用wgetcurlbrew可以在这里检查

我注意到一件事,YouTube可能会在一定时间后阻止流的播放。这是YouTube流常见的问题,因为它们不打算长时间连续播放,因为其高级功能可能会受到影响。解决这个问题的方法是使用不同的音乐来源。有许多其他音乐来源,如SoundCloud或Spotify,可能更可靠用于播放长时间的歌曲,或者可以使用不同的库,如wavelink。

此外,检查FFMPEG日志以查找可能提供有关问题的更详细信息的错误或警告可能对您有帮助。您可以尝试通过在FFMPEG命令中添加-v选项来增加日志的详细信息。

如果有问题,首先尝试这个,您可能需要尝试将FFMPEG安装更新到最新版本以查看是否解决了问题。

英文:

It's not running on Ubuntu properly might be issue with libraries installation there so some packages won't be installed normally but by using wget, curl or brew. Can check here

One thing I noticed is that YouTube may be blocking the stream after a certain amount of time has elapsed. This is a common issue with YouTube streams, as they are not intended to be played continuously for long periods of time because of their premium feature availability I think.
Solution for this is use different source for your music. There are many other sources for music, such as SoundCloud or Spotify, that may be more reliable for streaming long songs or can use different library like wavelink.

Also it may be helpful for you to check the FFMPEG logs for any errors or warnings that may provide more detailed info on the issue. You can try increasing the verbosity of the logs to get more detailed information by adding the -v option to your FFMPEG command.

Try this first if may fix, you may have to try updating your FFMPEG installation to the latest version to see if that resolves the issue.

huangapple
  • 本文由 发表于 2023年2月24日 06:38:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定