python - 如何构建自动播放音乐机器人 Discord.py
问题描述
我想建立一个自动播放音乐机器人。我有一首歌曲,我希望机器人在当前歌曲结束后自动播放下一首歌曲。我怎样才能做到这一点?
async def play(self, ctx, input: str):
YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
voice = discord.utils.get(self.client.voice_clients, guild=ctx.guild)
print(type(voice))
# input = input.strip("<>")
with YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(input, download=False)
description = ""
count = 0
if "entries" in info.keys():
for id, ent in enumerate(info["entries"]):
count += 1
self.queue.add(ent)
description += f"{id}. {str(ent['title'])[:70].rjust(80)}" + \
("..." if len(ent['title'][70:]) else "") + \
f"`{ent['duration'] // 60}:{ent['duration'] % 60}`\n" if count < 4 else ""
else:
URL = info['formats'][0]['url']
self.queue.add(info)
description += f"1. {str(info['title'])[:70].rjust(80)}" + \
("..." if len(info['title'][70:]) else "") + \
f"`{info['duration'] // 60}:{info['duration'] % 60}`\n"
if not voice.is_playing() and re.match(URL_REGEX, input):
voice.play(FFmpegPCMAudio(executable="ffmpeg.exe", source=self.queue._queue[self.queue.position]['url'],
**Music.FFMPEG_OPTIONS))
await ctx.send(embed=self.get_embed(ctx, self.queue._queue, [self.queue.position + 1, self.queue.length]))
elif voice.is_playing():
pass # some staff here
解决方案
你可以做的一件事是你可以有一个 async 函数,它有一段时间 True 并不断检查机器人是否没有播放任何内容,如果不是,则推进队列。
async def check(self, guild):
while True:
voice = discord.utils.get(self.client.voice_clients, guild=ctx.guild)
if not voice.is_playing:
self.queueIndex += 1
await self.playNext()
然后制作一个使用 self.queueIndex 播放歌曲的 playNext 函数。抱歉,如果这不起作用,我还没有使用 Ydl 制作不和谐音乐机器人。
推荐阅读
- python - 熊猫在 csv 上提高 OutOfBoundsDatetime 但不在 sql 上
- .net - 如何在其有效期开始之前使用服务器证书
- ruby-on-rails - Rails:NOT NULL Violation:保存明显的循环关联有时缺少外键
- postgresql - PostgreSQL(带递归)
- webgl - Simplex 3D 噪声动画在移动设备上停止
- java - 使用 `IOUtils.toString(containerRequestContext.getEntityStream(),"UTF-8"); 时无法解码特殊字符 `
- c# - 如何在 C# 中将结构列表写入文件?
- python - Sqlalchemy 模拟:UnifiedAlchemyMagicMock:抑制添加/提交
- java - 在 Java 中创建 Adobe XD 背景模糊效果
- ruby - 使用 Adobe PKCS#7 证书在 Origami 中签名的 PDF 验证