首页 > 解决方案 > 如何使用 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()

标签: pythondiscord.pytext-to-speech

解决方案


当您的机器人位于 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

推荐阅读