python - 如何使用 discord.py 制作类似于 KDBot 的 TTS 机器人?
问题描述
嗨,我是初学者,我的代码有问题。当我第一次使用该命令时,机器人进入语音通道并且它运行良好,但是当再次使用该命令时它不再起作用。每次使用该命令时,我都尝试断开机器人的连接并且它可以工作,但这不是我真正想要的,如果机器人已经连接到通道,我需要它像 kdbot 那样播放音频。有人可以帮助我吗?
@bot.command()
async def tts(ctx,*, text:str):
global gTTS
language = "es-us"
user = ctx.author
speech = gTTS(text=text,lang=language,slow=False)
speech.save("audio.mp3")
channel = user.voice.channel
try:
vc = await channel.connect()
except:
print("Already connected")
#vc = discord.VoiceClient(bot,channel)
#await vc.connect(reconnect=True,timeout=4)
vc.play(discord.FFmpegPCMAudio('audio.mp3'), after=None)
counter = 0
cwd = os.getcwd()
duration = audio_len(cwd + "/audio.mp3")
while not counter >= duration:
await asyncio.sleep(1)
counter += 1
#await vc.disconnect()
解决方案
当您的机器人位于 a 中VoiceChannel
时,它已经具有VoiceClient
您可以获得的 a:
from discord.utils import get
[...]
voice = get(self.bot.voice_clients, guild=ctx.guild)
下面是你如何使用它:
@bot.command()
async def tts(ctx,*, text:str):
global gTTS
speech = gTTS(text=text, lang="es-us", slow=False)
speech.save("audio.mp3")
voice = get(self.bot.voice_clients, guild=ctx.guild)
if not voice:
voice = await ctx.author.voice.channel.connect()
voice.play(discord.FFmpegPCMAudio('audio.mp3'), after=None)
counter = 0
cwd = os.getcwd()
duration = audio_len(cwd + "/audio.mp3")
while not counter >= duration:
await asyncio.sleep(1)
counter += 1
推荐阅读
- java - 我将使用什么代码在所有出现的术语/子字符串周围加上括号?
- ios - 离散余弦变换的不同结果和代码......这是怎么回事?
- java - Reactor - 使用 Flux.publish() 会阻止 StepVerifier.thenCancel() 工作?
- html - 有没有办法只为孩子而不是孙子应用css?
- c# - 如何确保手臂模板中的唯一名称?
- ios - 对计算属性的领域结果集合进行排序?
- stored-procedures - 是否可以在 db2 的存储过程中添加新列?
- css - :active 对于父 div 类不适用于子 div
- sql - 如何以 varchar 格式格式化日期存储
- swift - 快速格式化高度