gpt4 book ai didi

python - 如何让 Discord Bot 播放 YouTube 音频

转载 作者:行者123 更新时间:2023-12-03 17:02:59 25 4
gpt4 key购买 nike

我是一名高中生,正在制作一个 Discord 机器人作为最终项目,我在寻找在 Discordpy Rewrite 中播放 YouTube 音频的工作教程或基线时遇到了问题。如果有我缺少的教程或可以执行此操作的基本代码,我将非常感激。

我已经看过一些教程并尝试过它们,但由于某种原因它们似乎不起作用。我花了很多项目时间进行搜索,但似乎找不到我要找的东西。下面,我找到了一些让机器人播放 MP3 文件的代码,但我不确定如何使用 YouTube 链接来实现。

@bot.command()
async def mp3play(context):
user = context.message.author
voice_channel = user.voice.voice_channel
channel = None
if voice_channel != None:
channel=voice_channel.name
vc = await channel.connect()
audio = vc.play("holder.mp3", after=lambda: print("Complete."))
vc.start()
while vc.is_playing():
await asyncio.sleep(1)
vc.stop()
else:
await ctx.send("User must be in a voice channel.")

最佳答案

您好,这个新版本的discord.py 1.2.2对方法进行了一些更改,您可以按照文档本身的方法迁移

首先,您需要实现一个名为 YTDLSource 的类控制yotube_dl

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)


在你的音乐命令中使用这个类,注意我的 def play 属于我称之为 Voice 的其他类。

 @commands.command(pass_context=True)
async def play(self, ctx, *, url):
print(url)
server = ctx.message.guild
voice_channel = server.voice_client

async with ctx.typing():
player = await YTDLSource.from_url(url, loop=self.bot.loop)
ctx.voice_channel.play(player, after=lambda e: print('Player error: %s' % e) if e else None)
await ctx.send('Now playing: {}'.format(player.title))


在此之前,只需添加您的齿轮并享受!

关于python - 如何让 Discord Bot 播放 YouTube 音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56060614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com