Discord Bot 在离开前不播放 mp3 文件

时间:2021-04-30 15:59:49

标签: python discord.py

我目前正在编写一个 discord bot,它应该使用命令“!leave”执行 mp3 文件,然后离开频道。不幸的是,机器人要么离开频道,不播放 mp3 文件,要么(没有 await 命令)机器人播放 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 ") 

如果有人能帮助我,我将不胜感激。我没有通过谷歌等找到任何解决方案。

最好的问候 流量

2 个答案:

答案 0 :(得分:0)

据我所知,VoiceClient.play 在继续您的代码之前不会等待源代码完成。尝试改用 aftervoice.play 参数:

@client.command(pass_context=True)
async def leave(ctx):
    if ctx.voice_client:
        voice = ctx.channel.guild.voice_client

        async def leave_vc(exc):
            if exc:
                print("Something went wrong!", exc)
            await voice.disconnect()

        voice.play(
            discord.FFmpegPCMAudio(r"C:\Users\***\Desktop\DiscordBot\bye.mp3"),
            after=lambda exc: ctx.bot.loop.run_until_complete(leave_vc(exc))
        )
    else:
        await ctx.send("test ") 

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

答案 1 :(得分:0)

我自己修好了。不要认为那是一个很好的解决方案,但它正在起作用 ^^ 如果有人有更好的解决方案,请告诉我 :)

@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 ")