import datetime import os import json 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"], default="vc") ): await ctx.defer() tts = gTTS(text=text, lang='pl') tts.save('tts.mp3') if os.path.exists('settings.json'): with open('settings.json') as f: data = json.load(f) volume = data['volume'] else: logger.error("settings.json not found") if output == "file": await ctx.respond(file=discord.File('tts.mp3')) logger.info(f"sent {text}") os.remove('tts.mp3') elif output == "vc": await ctx.respond(content="\u200b", ephemeral=True) await ctx.interaction.delete_original_response() # Check if the user is in a voice channel if not (ctx.author.voice and ctx.author.voice.channel): 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=f'-filter:a "volume={volume}"') logger.info(f"playing {text}") voice_client.play(audio_source) 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))