aboutsummaryrefslogtreecommitdiffstats
path: root/cogs/tts.py
blob: 8076a2dd268ec89ba62591d04e4e101d4b99c1ef (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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))