有没有办法在播放完歌曲后使我的不和谐机器人与语音通道断开连接?

时间:2020-05-16 01:34:41

标签: python discord python-asyncio pafy

我想知道是否有办法让我的不和谐机器人在播放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)

3 个答案:

答案 0 :(得分:1)

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

vc.play()之后添加

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

答案 1 :(得分:0)

我在漫游器中使用的代码:

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()

答案 2 :(得分:0)

在这种情况下,vc.disconnect()是一个协程,必须等待。 不和谐播放器的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