这是我要创建的机器人的代码,可以很好地播放音乐。
ytdl_options = {
'format': 'bestaudio/best',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'quiet':True,
'ignoreerrors': False,
'logtostderr': False,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0' # using ipv4 since ipv6 addresses causes issues sometimes
}
# ffmpeg options
ffmpeg_options= {
'options': '-vn'
}
@bot.command()
async def play(ctx, url:str = None):
queue = {}
channel = ctx.author.voice.channel
if ctx.voice_client is not None:
await ctx.voice_client.move_to(channel)
elif ctx.author.voice and ctx.author.voice.channel:
await channel.connect()
if not url:
await ctx.send("Try adding a URL. e.g. !play https://youtube.com/watch?v=XXXXXXXXX")
if ctx.voice_client is not None:
vc = ctx.voice_client #vc = voice client, retrieving it
ytdl = youtube_dl.YoutubeDL(ytdl_options)
loop = asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url))
if 'entries' in data:
data = data['entries'][0]
svr_id = ctx.guild.id
if svr_id in queue:
queue[svr_id].append(data)
else:
queue[svr_id] = [data]
await ctx.send(data.get('title') + " added to queue")
source = ytdl.prepare_filename(queue[svr_id][0])
def pop_queue():
if queue[svr_id] != []:
queue[svr_id].pop(0)
data = queue[svr_id][0]
else:
vc.stop()
if not vc.is_playing():
vc.play(discord.FFmpegPCMAudio(source, **ffmpeg_options), after=lambda: pop_queue())
下载下一首歌曲并将其排入队列,但是一旦第一首歌曲结束,就不会播放下一首歌曲。第一首歌开始后,我不知道如何播放。我设置了after=
来删除队列的顶部项目,但是如何使它再次播放?谢谢