Python Discord Bot在离开前未播放mp3文件

Python Discord Bot在离开前未播放mp3文件,python,discord.py,Python,Discord.py,我目前正在编写一个discord bot,它应该使用命令“!leave”执行mp3文件,然后离开频道。不幸的是,bot离开频道而不播放mp3文件,或者(在没有等待命令的情况下)bot播放mp3文件但不离开频道 @client.command(pass_context=True) async def leave(ctx): if ctx.voice_client: voice = ctx.channel.guild.voice_client voice.pl

我目前正在编写一个discord bot,它应该使用命令“!leave”执行mp3文件,然后离开频道。不幸的是,bot离开频道而不播放mp3文件,或者(在没有等待命令的情况下)bot播放mp3文件但不离开频道

@client.command(pass_context=True)
async def leave(ctx):
    if ctx.voice_client:
        voice = ctx.channel.guild.voice_client
        voice.play(discord.FFmpegPCMAudio(r"C:\Users\***\Desktop\DiscordBot\bye.mp3"))
        await voice.disconnect()
    else:
        await ctx.send("test ") 
如果有人能帮助我,我将不胜感激。我没有通过谷歌等找到任何解决方案

致意 Traffix

据我所知,在继续编写代码之前,不会等待源代码完成。尝试使用
语音的
after
参数。改为播放

@client.command(pass\u context=True)
异步def离开(ctx):
如果ctx.voice\u客户端:
voice=ctx.channel.guild.voice\u客户端
异步def离开vc(exc):
如果exc:
打印(“出错了!”,exc)
等待语音。断开连接()
语音播放(
discord.ffmpegpcaudio(r“C:\Users\***\Desktop\DiscordBot\bye.mp3”),
after=lambda exc:ctx.bot.loop.run_直到_完成(离开_vc(exc))
)
其他:
等待ctx发送(“测试”)

我没有办法测试这个,所以我不能保证它会立即工作。

我自己修复了它。不要认为这是一个很好的解决方案,但它正在发挥作用^^如果有人有更好的解决方案,请让我知道:)


谢谢你的回答。不幸的是,它还不起作用。音频正在播放,但之后显示错误:“RuntimeWarning:coroutine'VoiceClient.disconnect'从未等待过回溯。print_异常(类型(exc)、exc、exc.。uuu回溯_uu)RuntimeWarning:Enable tracemalloc获取对象分配回溯”@Traffix它是否离开了语音频道,即使发生错误?不,它没有离开channel@Traffix尝试使用
asyncio.run(voice.disconnect())
而不是
ctx.bot.loop.run直到完成(voice.disconnect())
。您还必须
导入asyncio
。仍然相同(音频播放,但没有断开连接),但错误不同。错误:“运行时错误:任务”
@client.command(pass_context=True)
async def leave(ctx):
    if ctx.voice_client:
        server = ctx.message.guild
        voice_channel = server.voice_client
        
        voice_channel.play(discord.FFmpegPCMAudio(r"C:\Users\***\Desktop\DiscordBot\bye.mp3"))
        counter = 0
        duration = 3

        while not counter >= duration:
            await asyncio.sleep(1)
            counter = counter + 1
        await ctx.voice_client.disconnect()
    else:
        await ctx.send("test ")