How can I make a TTS bot similar to KDBot with discord.py?

Hi I am a begginer and i have a problem with my code. when I use the command for the first time the bot enters the voice channel and it works perfect, but when using the command again it no longer works. I have tried disconnecting the bot every time I use the command and it works, but it is not what I really want, if the bot is already connected to the channel I need it to play the audio as kdbot does. Can somebody help me?

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

1 Answer

When your bot is in a VoiceChannel, it already has a VoiceClient that you can get:

from discord.utils import get [...] voice = get(self.bot.voice_clients, guild=ctx.guild) 

Here's how you'd use it:

@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 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like