python - 如何让我的 Discord 机器人在语音 channel 中停留特定 mp3 文件的时间长度?

标签 python python-3.6 discord.py

我一直在为我的个人discord服务器开发一个机器人,到目前为止它播放的mp3都是固定长度的,所以我告诉机器人根据mp3的长度休眠一定的时间。现在,使用我的新命令,将会播放不同长度的 mp3,但我不知道从这里到哪里去。您可以在我的代码中看到我如何让它休眠,但这将不再起作用,因为 mp3 可能很长或可能很短。我正在尝试找出一种通过 python 获取有关 mp3 的信息并告诉它在 mp3 长度内休眠的方法。有人可以帮我解决这个问题或为我指出正确的方向吗?谢谢。

过去,我尝试使用类似于 vc.wait 的命令,但机器人不断加入,然后立即离开。 sleep 命令非常适合我过去的使用,所以我只是使用它。

@client.command(pass_context=True)
async def tts(ctx):
    #get message content and send to google text to speech api
    msg = ctx.message.content
    tts = gTTS(msg[5:])

    #here is where the mp3 is made and saved
    tts.save('message.mp3')

    #find length of mp3

    channel = ctx.message.author.voice.channel
    vc = await channel.connect()
    source = FFmpegPCMAudio('./message.mp3')
    player = vc.play(source)

    #the method I've been using for mp3s, increasing or decreasing manually 
#per command based on mp3 length. This is the command that I now need to be 
#dynamic. Replace 15 with length of mp3.
    await asyncio.sleep(15)
    await vc.disconnect(force=True)

我不期待任何东西,但我希望找到一些帮助或正确方向的插入,以便当场找到 mp3 的长度并相应地调整机器人在语音 channel 中花费的时间。谢谢。抱歉,我的代码太草率了,这只是一个个人项目,我没想到有人会看到它。

最佳答案

根据文档查到here对于语音客户端,您可以在 vc.play(source) 中创建回调函数,可能如下所示:

async def playCallback(error):
    await vc.disconnect(force=True)
.
.
.

player = vc.player(source, after=playCallback)

让我知道这是否有效 - 快乐编码!

关于python - 如何让我的 Discord 机器人在语音 channel 中停留特定 mp3 文件的时间长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57262187/

相关文章:

python - 如何使用pypdf将字符串插入pdf?

python - 为什么我得到 "UserWarning: Module dap was already imported from None ..."

python - 当我从 python 运行可执行文件并传递参数时,我什么也没得到

Python3.6 属性错误: module 'asyncio' has no attribute 'run'

python - discord py音乐机器人停止播放

python - 如何使用discord.py更改所有文本 channel 的权限?

python - 如何让机器人在discord.py 中发布剧透图片?

python - GPIO 设置错误和键盘中断 - Python

python-3.6 - 应用简单训练模型时未命名向量上的 Spacy 错误

windows - 在 Windows 10 上安装 spaCy 不起作用