import datetime import os import discord from discord.ext import commands from gtts import gTTS import logging logger = logging.getLogger(__name__) class TTS(commands.Cog): def __init__(self, bot): self.bot = bot @commands.slash_command(name="tts", description="Generuje TTS dla danego tekstu") async def tts(self, ctx, text: str = discord.Option(str, "Tekst do przeczytania", required=True), output: str = discord.Option(str, "Wybierz sposób odtwarzania", choices=["file", "vc"], required=True) ): tts = gTTS(text=text, lang='pl') tts.save('tts.mp3') if output == "file": await ctx.respond(file=discord.File('tts.mp3')) logger.info("TTS file sent") os.remove('tts.mp3') elif output == "vc": # Check if the user is in a voice channel if not (ctx.author.voice and ctx.author.voice.channel): await ctx.respond("Musisz być na kanale głosowym, aby odtworzyć TTS!", ephemeral=True) logger.info("User is not in a voice channel") os.remove('tts.mp3') return channel = ctx.author.voice.channel # Connect to the voice channel if not already connected voice_client = discord.utils.get(self.bot.voice_clients, guild=channel.guild) if not voice_client or not voice_client.is_connected(): voice_client = await channel.connect() elif voice_client.channel != channel: await voice_client.move_to(channel) # Play the TTS audio if not voice_client.is_playing(): audio_source = discord.FFmpegPCMAudio('tts.mp3', options='-filter:a "volume=6"') logger.info("TTS audio played") voice_client.play(audio_source) # Wait for playback to finish while voice_client.is_playing(): await discord.utils.sleep_until(datetime.datetime.now() + datetime.timedelta(seconds=1)) os.remove('tts.mp3') else: await ctx.respond("Nieznany sposób odtwarzania.", ephemeral=True) logger.info("Unknown playback method") os.remove('tts.mp3') def setup(bot): bot.add_cog(TTS(bot))