【问题标题】:Is there a way to make my discord bot disconnect from the voice channel after finishing playing a song?有没有办法让我的不和谐机器人在播放完歌曲后断开与语音频道的连接?
【发布时间】:2020-09-01 23:05:03
【问题描述】:

我想知道是否有办法让我的不和谐机器人在播放 youtube 视频的音频后离开语音频道。我尝试使用sleep(duration of the video),但为了获取和下载要播放的视频,我使用了pafy,它给了我视频的持续时间,但格式为 00:00:00,它算作字符串,而不是整数。我将代码更改为在after=lamda e: await vc.disconnect 处断开连接,但它给了我一个错误提示'await' outside async function。我播放音乐的代码如下:

channel = message.author.voice.channel
vc = await channel.connect()
url = contents
url = url.strip("play ")
video = pafy.new(url)
await message.channel.send("Now playing **%s**" % video.title)

audio = video.getbestaudio()
audio.download()
duration = video.duration
player = vc.play(discord.FFmpegPCMAudio('%s.webm' % video.title), after=lambda e: await vc.disconnect)

【问题讨论】:

    标签: python discord python-asyncio pafy


    【解决方案1】:

    这是一种在歌曲播放完毕后断开连接的方法(删除after=)。

    vc.play()之后添加

        while vc.is_playing():
            await sleep(1)
        await vc.disconnect()
    

    【讨论】:

    • 谢谢,但它给了我一个错误,说我不能在睡眠时使用 await。即使我将 await 带走,它仍然无法正常工作。
    • 你需要导入-from asyncio import sleep
    • 哦,我做了from time import sleep
    • 在那之后我仍然得到RuntimeWarning: coroutine 'sleep' was never awaited 和许多其他的东西。
    • 你是否把 await 放回去并正确缩进?
    【解决方案2】:

    我在机器人中使用的代码:

    stop_event = asyncio.Event()
    loop = asyncio.get_event_loop()
    def after(error):
        if error:
            logging.error(error)
        def clear():
            stop_event.set()
        loop.call_soon_threadsafe(clear)
    
    audio = PCMVolumeTransformer(discord.FFmpegPCMAudio(file_path), 1)
    client.play(audio, after=after)
    
    await stop_event.wait()
    await client.disconnect()
    

    【讨论】:

    • 以前我使用的是接受答案中的一种解决方案,但上面提出了一种更清洁的方法
    【解决方案3】:

    在这种情况下,vc.disconnect() 是一个必须等​​待的协程。 discord 播放器的after 函数不能等待这样的异步函数。而是使用这样的东西:

    def my_after(error):
    coro = vc.disconnect()
    fut = asyncio.run_coroutine_threadsafe(coro, client.loop)
    try:
        fut.result()
    except:
        # an error happened sending the message
        pass
    voice.play(discord.FFmpegPCMAudio(url), after=my_after)
    

    You can also read about it here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 2021-04-13
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      相关资源
      最近更新 更多