我让机器人加入并播放了音频,但似乎并非一直如此。有时它会加入并从一半开始播放。我假设这与异步的性质有关。有没有一种方法可以确保漫游器加入播放音频然后按该顺序离开?我的代码在下面
@bot.command(name='play_audio')
async def play_audio(ctx):
if ctx.message.author == client.user:
return
voice = await join(ctx)
voice.play(discord.FFmpegPCMAudio(f"{os.path.dirname(os.path.abspath(__file__))}/audio.mp3"))
await leave(ctx)
@bot.command(name='j')
async def join(ctx):
if ctx.message.author == client.user:
return
channel = ctx.message.author.voice.channel
voice = get(bot.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
print(f"The bot has connected to {channel}\n")
return voice
@bot.command(name='l')
async def leave(ctx):
if ctx.message.author == client.user:
return
channel = ctx.message.author.voice.channel
voice = get(bot.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.disconnect()
print(f"The bot has left {channel}\n")
bot.run(TOKEN)
答案 0 :(得分:1)
似乎在播放完成之前您正在执行leave()
。
您可以选中is_playing()以等待mp3播放完毕。
此外,使用asyncio.sleep来放松while循环。
请在离开前尝试添加以下while
:
@bot.command(name='play_audio')
async def play_audio(ctx):
if ctx.message.author == client.user:
return
voice = await join(ctx)
voice.play(discord.FFmpegPCMAudio(f"{os.path.dirname(os.path.abspath(__file__))}/audio.mp3"))
while voice.is_playing():
await sleep(1)
await leave(ctx)