【问题标题】:Discord Bot is not playing mp3 file before leavingDiscord Bot 离开前未播放 mp3 文件
【发布时间】:2021-05-01 03:06:59
【问题描述】:

我目前正在编写一个不和谐的机器人,它应该使用命令“!离开”执行 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 ") 

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

最好的问候 交通标签

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

    据我所知,VoiceClient.play 不会等待源代码完成后再继续您的代码。尝试改用voice.playafter 参数:

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

    我没有办法对此进行测试,所以我不能保证它会立即起作用。

    【讨论】:

    • 感谢您的回答。不幸的是它还没有工作。音频正在播放,但之后显示错误:“RuntimeWarning: coroutine 'VoiceClient.disconnect' was never awaited traceback.print_exception(type(exc), exc, exc.__traceback__) RuntimeWarning: E​​nable tracemalloc to get the object allocation traceback”
    • @Traffix 是否离开了语音频道,即使发生了错误?
    • @Traffix 尝试使用asyncio.run(voice.disconnect()) 而不是ctx.bot.loop.run_until_complete(voice.disconnect())。你也必须import asyncio
    • 仍然相同(音频播放但没有断开连接),但错误不同。错误:“RuntimeError:任务
    • @Traffix 我上次编辑了它,如果这不起作用,我不知道会发生什么。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-04-07
      • 2018-11-19
      • 2020-11-29
      • 1970-01-01
      • 2020-09-04
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多