Python 有没有办法让我的discord机器人在播放完一首歌后与语音频道断开连接?

Python 有没有办法让我的discord机器人在播放完一首歌后与语音频道断开连接?,python,discord,python-asyncio,pafy,Python,Discord,Python Asyncio,Pafy,我想知道是否有办法让我的discord机器人在播放youtube视频的音频后离开语音频道。我试着使用sleepduration来播放视频,但是为了获取和下载视频,我使用了pafy,它给了我视频的持续时间,但是是00:00:00格式,它是一个字符串,而不是整数。我在after=lamda e:await vc.disconnect中将代码更改为diconnect,但在异步函数外显示“await”时出错。我播放音乐的代码如下: channel = message.author.voice.chann

我想知道是否有办法让我的discord机器人在播放youtube视频的音频后离开语音频道。我试着使用sleepduration来播放视频,但是为了获取和下载视频,我使用了pafy,它给了我视频的持续时间,但是是00:00:00格式,它是一个字符串,而不是整数。我在after=lamda e:await vc.disconnect中将代码更改为diconnect,但在异步函数外显示“await”时出错。我播放音乐的代码如下:

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)

这里有一种在歌曲完成删除after=后断开连接的方法

在vc.play之后添加

当vc.U在玩的时候: 等待睡眠 等待vc断开连接 我在bot中使用的代码:

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()
在这种情况下,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)

谢谢,但它给了我一个错误,说我不能在睡眠中使用wait。即使我把等待拿走了,它仍然不能工作。你需要导入-从asyncio导入sleep哦,我从time导入sleep中导入了。我仍然收到RuntimeWarning:coroutine'sleep'从来没有被等待过,之后还有很多其他东西。你把等待放回去并正确缩进了吗?以前我使用的是来自公认答案的解决方案,但是想出了一个更干净的方法