【问题标题】:How can I make a TTS bot similar to KDBot with discord.py?如何使用 discord.py 制作类似于 KDBot 的 TTS 机器人?
【发布时间】:2021-10-30 12:34:32
【问题描述】:

您好,我是初学者,我的代码有问题。当我第一次使用该命令时,机器人进入语音通道并且它运行良好,但是当再次使用该命令时它不再起作用。每次使用该命令时,我都尝试断开机器人的连接并且它可以工作,但这不是我真正想要的,如果机器人已经连接到频道,我需要它像 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()

【问题讨论】:

    标签: python discord.py text-to-speech


    【解决方案1】:

    当您的机器人位于 VoiceChannel 中时,它已经有一个您可以获得的 VoiceClient

    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
    

    【讨论】:

      猜你喜欢
      • 2022-01-16
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 2021-04-28
      • 2020-12-21
      • 2018-04-15
      • 1970-01-01
      相关资源
      最近更新 更多