From 791e75cb2beeca45a6edf52b65f7e299e03b5eaf Mon Sep 17 00:00:00 2001 From: SamlonDev Date: Sat, 14 Jun 2025 18:54:02 +0200 Subject: code-style issues --- .idea/.gitignore | 8 +++ cogs/ai.py | 20 ++++--- cogs/compression.py | 25 ++++---- cogs/downloader.py | 32 ++++++----- cogs/math.py | 16 +++--- cogs/music/join.py | 5 +- cogs/music/leave.py | 5 +- cogs/music/loop.py | 4 +- cogs/music/play.py | 55 +++++++++--------- cogs/music/play_compressed.py | 15 +++-- cogs/music/queue.py | 6 +- cogs/music/skip.py | 29 +++++----- cogs/ping_commands.py | 60 ------------------- cogs/tts.py | 19 +++--- cogs/vc_logs.py | 110 ----------------------------------- cogs/vclogs.py | 130 ++++++++++++++++++++++++++++++++++++++++++ main.py | 8 ++- 17 files changed, 273 insertions(+), 274 deletions(-) create mode 100644 .idea/.gitignore delete mode 100644 cogs/ping_commands.py delete mode 100644 cogs/vc_logs.py create mode 100644 cogs/vclogs.py diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/cogs/ai.py b/cogs/ai.py index ded74d9..d2af796 100644 --- a/cogs/ai.py +++ b/cogs/ai.py @@ -1,7 +1,9 @@ +import os + import discord -from discord.ext import commands import google.generativeai as genai -import os +from discord.ext import commands + class AI(commands.Cog): def __init__(self, bot): @@ -12,22 +14,22 @@ class AI(commands.Cog): description="SEENATOR", ) async def senator( - self, - ctx: discord.ApplicationContext, - text = discord.Option(str, "message", required=True) + self, + ctx: discord.ApplicationContext, + text=discord.Option(str, "message", required=True) ): - ''' + """ OOWA this so impressive gwachan >w< I can't believe you made this you are so good gwachan :3 - ''' + """ await ctx.defer() genai.configure(api_key=os.getenv("GOOGLE_API_KEY")) model = genai.GenerativeModel("gemini-1.5-flash") response = model.generate_content( - "You are Senator Steaven Sperma Armstrong from Metal Gear Rising Vengeance. Respond in plain text, no ** or "". If the message is in Polish, respond in Polish. Respond in 100 words. Respond accordingly to this message: "+text, + "You are Senator Steaven Sperma Armstrong from Metal Gear Rising Vengeance. Respond in plain text, no ** or "". If the message is in Polish, respond in Polish. Respond in 100 words. Respond accordingly to this message: " + text, ) await ctx.respond(response.text) + def setup(bot): bot.add_cog(AI(bot)) - \ No newline at end of file diff --git a/cogs/compression.py b/cogs/compression.py index dfd96ae..ddfa545 100644 --- a/cogs/compression.py +++ b/cogs/compression.py @@ -1,10 +1,10 @@ -import discord -from discord.ext import commands -import asyncio import mimetypes -import os +import os import subprocess -import tempfile + +import discord +from discord.ext import commands + def filetype(filename): mime_type, _ = mimetypes.guess_type(filename) @@ -17,10 +17,11 @@ def filetype(filename): return "Image" return "Unknown" + class Compression(commands.Cog): def __init__(self, bot): self.bot = bot - + @commands.slash_command( name="kompresja", description="skompresuj wideło albo dźwienk :)", @@ -33,14 +34,14 @@ class Compression(commands.Cog): ) async def compression(self, ctx, plik): await ctx.defer() - # Save files to temp directory inside the bot's root directory + # Save files to the temp directory inside the bot's root directory bot_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) temp_dir = os.path.join(bot_dir, "temp") if not os.path.exists(temp_dir): os.makedirs(temp_dir) file_path = os.path.join(temp_dir, plik.filename) await plik.save(file_path) - + input_path = file_path output_path = os.path.join(temp_dir, f"better_{plik.filename}") file_type = filetype(file_path) @@ -51,7 +52,7 @@ class Compression(commands.Cog): ffmpeg_command = f"ffmpeg -i {input_path} -ar 8000 -ac 1 -b:a 16k -acodec libmp3lame -q:a 9 {output_path}" elif file_type == "Image": # Use ImageMagick's magick to heavily compress image (JPEG/PNG/GIF) - # For JPEG: quality 5, strip metadata, resize to 30% of original size + # For JPEG: quality 5, strip metadata, resize to 30% of the original size # For PNG: magick to JPEG, then compress # For GIF: optimize and reduce colors ext = os.path.splitext(input_path)[1].lower() @@ -68,10 +69,10 @@ class Compression(commands.Cog): else: await ctx.respond("Plik jest nieobsługiwany", ephemeral=True) return - + try: subprocess.run(ffmpeg_command, check=True, shell=True) - # Upload compressed file + # Upload the compressed file await ctx.respond(file=discord.File(output_path)) # Delete compressed file os.remove(input_path) @@ -85,4 +86,4 @@ class Compression(commands.Cog): def setup(bot): - bot.add_cog(Compression(bot)) \ No newline at end of file + bot.add_cog(Compression(bot)) diff --git a/cogs/downloader.py b/cogs/downloader.py index 7f48e57..c35373f 100644 --- a/cogs/downloader.py +++ b/cogs/downloader.py @@ -1,12 +1,13 @@ import base64 import os +import os.path +import tempfile + import discord -from discord.ext import commands import requests import yt_dlp +from discord.ext import commands from dotenv import load_dotenv -import tempfile -import os.path # Load environment variables load_dotenv() @@ -34,9 +35,9 @@ class Downloader(commands.Cog): description="download video from internet", ) async def download( - self, - ctx: discord.ApplicationContext, - url: discord.Option(str, "url", required=True) + self, + ctx: discord.ApplicationContext, + url: discord.Option(str, "url", required=True) ): await ctx.defer() try: @@ -52,7 +53,7 @@ class Downloader(commands.Cog): with yt_dlp.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(url, download=True) actual_filename = ydl.prepare_filename(info) - + await ctx.followup.send("Video downloaded successfully, Uploading to pixeldrain...") # upload to pixeldrain try: @@ -61,37 +62,40 @@ class Downloader(commands.Cog): response = requests.post( self.pixeldrain_url, files=files, - headers={"Authorization": f"Basic {base64.b64encode((':' + PIXELDRAIN_API_KEY).encode()).decode()}"} + headers={ + "Authorization": f"Basic {base64.b64encode((':' + PIXELDRAIN_API_KEY).encode()).decode()}"} ) - + try: response_data = response.json() print("Pixeldrain response:", response_data) # Debug log - + if response.status_code == 201: # 201 means successful upload file_id = response_data.get('id') if file_id: file_link = f"https://pixeldrain.com/u/{file_id}" await ctx.followup.send(f"oto twoje videło\n {file_link}") else: - await ctx.followup.send(f"⚠️ Upload successful but no file ID returned. Response: {response_data}") + await ctx.followup.send( + f"⚠️ Upload successful but no file ID returned. Response: {response_data}") else: error_msg = response_data.get('error', 'Unknown error') if response.status_code == 401: error_msg = "Invalid API key. Please check your PIXELDRAIN_API_KEY in .env file." await ctx.followup.send(f"❌ Upload failed (Status {response.status_code}): {error_msg}") except ValueError as e: - # If response is not JSON + # If the response is not JSON error_msg = f"Failed to parse server response: {str(e)}" if response.text: error_msg += f"\nResponse: {response.text[:200]}" await ctx.followup.send(f"❌ {error_msg}") except Exception as e: await ctx.followup.send(f"Error: {str(e)}") - # No need for explicit cleanup as tempfile.TemporaryDirectory handles it automatically + # No need for explicit cleanup as a tempfile.TemporaryDirectory handles it automatically except Exception as e: await ctx.followup.send(f"Error: {str(e)}") + def setup(bot): - bot.add_cog(Downloader(bot)) \ No newline at end of file + bot.add_cog(Downloader(bot)) diff --git a/cogs/math.py b/cogs/math.py index df2be4a..53340f2 100644 --- a/cogs/math.py +++ b/cogs/math.py @@ -1,23 +1,25 @@ -from discord.ext import commands -import discord -from discord import (ApplicationContext) import subprocess +from discord import (ApplicationContext) +from discord.ext import commands + + class Math(commands.Cog): def __init__(self, bot): self.bot = bot - + @commands.slash_command( name="math", description="wrug szyskih matfisuf" ) - async def math(self, ctx:ApplicationContext, equation:str): + async def math(self, ctx: ApplicationContext, equation: str): try: - math=subprocess.check_output(f"qalc -e {equation}", shell=True) + math = subprocess.check_output(f"qalc -e {equation}", shell=True) await ctx.respond(f"{equation} = {math.decode('utf-8').strip()}") except Exception as e: await ctx.respond(e, ephemeral=True) print(e) + def setup(bot): - bot.add_cog(Math(bot)) \ No newline at end of file + bot.add_cog(Math(bot)) diff --git a/cogs/music/join.py b/cogs/music/join.py index 91a0b18..a613e81 100644 --- a/cogs/music/join.py +++ b/cogs/music/join.py @@ -1,6 +1,6 @@ -import discord from discord.ext import commands + class Join(commands.Cog): def __init__(self, bot): self.bot = bot @@ -9,5 +9,6 @@ class Join(commands.Cog): async def join(self, ctx): await ctx.voice_client.connect() + def setup(bot): - bot.add_cog(Join(bot)) \ No newline at end of file + bot.add_cog(Join(bot)) diff --git a/cogs/music/leave.py b/cogs/music/leave.py index 0be2068..7be3b60 100644 --- a/cogs/music/leave.py +++ b/cogs/music/leave.py @@ -1,6 +1,6 @@ -import discord from discord.ext import commands + class Leave(commands.Cog): def __init__(self, bot): self.bot = bot @@ -9,5 +9,6 @@ class Leave(commands.Cog): async def kick(self, ctx): await ctx.voice_client.disconnect() + def setup(bot): - bot.add_cog(Leave(bot)) \ No newline at end of file + bot.add_cog(Leave(bot)) diff --git a/cogs/music/loop.py b/cogs/music/loop.py index 5f51c7e..2331840 100644 --- a/cogs/music/loop.py +++ b/cogs/music/loop.py @@ -1,5 +1,6 @@ from discord.ext import commands + class Loop(commands.Cog): def __init__(self, bot): self.bot = bot @@ -18,5 +19,6 @@ class Loop(commands.Cog): self.set_looping(guild_id, looping) await ctx.respond(f"looping jest teraz {'włączony' if looping else 'wyłączony'}.") + def setup(bot): - bot.add_cog(Loop(bot)) \ No newline at end of file + bot.add_cog(Loop(bot)) diff --git a/cogs/music/play.py b/cogs/music/play.py index bf9d081..b47de03 100644 --- a/cogs/music/play.py +++ b/cogs/music/play.py @@ -1,12 +1,14 @@ -import discord -from discord.ext import commands import asyncio + +import discord import yt_dlp +from discord.ext import commands from youtubesearchpython import VideosSearch # Suppress noise about console usage from yt-dlp yt_dlp.utils.bug_reports_message = lambda: '' + class Play(commands.Cog): def __init__(self, bot): self.bot = bot @@ -32,15 +34,15 @@ class Play(commands.Cog): queue = self.get_queue(guild_id) if queue: title, url = queue[0] - - def after_playing(error): + + def after_playing(): if queue: queue.pop(0) if queue: next_title, next_url = queue[0] if not vc.is_playing() and not vc.is_paused(): asyncio.run_coroutine_threadsafe( - self.play_audio(ctx, vc, next_url, next_title, guild_id), + self.play_audio(ctx, vc, next_url, next_title), self.bot.loop ) else: @@ -48,11 +50,11 @@ class Play(commands.Cog): vc.disconnect(), self.bot.loop ) - + if not vc.is_playing() and not vc.is_paused(): - await self.play_audio(ctx, vc, url, title, guild_id, after=after_playing) + await self.play_audio(ctx, vc, url, title, after=after_playing) - async def play_audio(self, ctx, vc, url, title, guild_id, after=None): + async def play_audio(self, ctx, vc, url, title, after=None): try: with yt_dlp.YoutubeDL(self.ydl_opts) as ydl: info = await self.bot.loop.run_in_executor( @@ -61,59 +63,59 @@ class Play(commands.Cog): ) if 'entries' in info: info = info['entries'][0] - + url2 = info['url'] - - FFMPEG_OPTIONS = { + + ffmpeg_options = { 'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn' } - - source = discord.FFmpegPCMAudio(url2, **FFMPEG_OPTIONS) + + source = discord.FFmpegPCMAudio(url2, **ffmpeg_options) vc.play(source, after=after) await ctx.followup.send(f"gra: {title}") except Exception as e: await ctx.followup.send(f"Wystąpił błąd podczas odtwarzania: {str(e)}") - # Try to play next in queue if there's an error + # Try to play next in the queue if there's an error if after: after(None) @commands.slash_command(name="grajcuj", description="grajcuj melodyje") async def play(self, ctx, *, search: str): await ctx.defer() - + if not (ctx.author.voice and ctx.author.voice.channel): await ctx.followup.send("nie jesteś w kanale głosowym") return - + channel = ctx.author.voice.channel vc = ctx.voice_client or await channel.connect() - + if vc.channel != channel: await vc.move_to(channel) - + # Search for the video videos_search = VideosSearch(search, limit=1) result = videos_search.result() - + if not result['result']: await ctx.followup.send("nie znaleziono wideo dla twojego wyszukiwania.", ephemeral=True) return - + video = result['result'][0] title = video['title'] url = video['link'] - + # Add to queue queue = self.get_queue(ctx.guild.id) queue.append((title, url)) - + # If nothing is playing, start playing if not vc.is_playing() and not vc.is_paused(): await self.play_next(ctx, vc, ctx.guild.id) else: await ctx.followup.send(f"dodano do kolejki: {title}") - + @commands.slash_command(name="stop", description="zatrzymaj odtwarzanie i wyczyść kolejkę") async def stop(self, ctx): if ctx.voice_client: @@ -123,7 +125,7 @@ class Play(commands.Cog): await ctx.respond("Zatrzymano odtwarzanie i wyczyszczono kolejkę") else: await ctx.respond("Nie jestem połączony z kanałem głosowym") - + @commands.slash_command(name="pauza", description="wstrzymaj odtwarzanie") async def pause(self, ctx): if ctx.voice_client and ctx.voice_client.is_playing(): @@ -131,7 +133,7 @@ class Play(commands.Cog): await ctx.respond("Wstrzymano odtwarzanie") else: await ctx.respond("Nic nie jest teraz odtwarzane") - + @commands.slash_command(name="wznow", description="wznów odtwarzanie") async def resume(self, ctx): if ctx.voice_client and ctx.voice_client.is_paused(): @@ -140,5 +142,6 @@ class Play(commands.Cog): else: await ctx.respond("Nic nie jest teraz wstrzymane") + def setup(bot): - bot.add_cog(Play(bot)) \ No newline at end of file + bot.add_cog(Play(bot)) diff --git a/cogs/music/play_compressed.py b/cogs/music/play_compressed.py index 3297110..f14d75b 100644 --- a/cogs/music/play_compressed.py +++ b/cogs/music/play_compressed.py @@ -1,15 +1,18 @@ -import discord -from discord.ext import commands import asyncio import os import subprocess + +import discord +from discord.ext import commands from youtubesearchpython import VideosSearch + class GrajcujZkompresowane(commands.Cog): def __init__(self, bot): self.bot = bot - def prepend_title_to_file(self, file_path, title): + @staticmethod + def prepend_title_to_file(file_path, title): try: with open(file_path, 'rb') as original: data = original.read() @@ -19,7 +22,8 @@ class GrajcujZkompresowane(commands.Cog): except Exception as e: print(f"Failed to prepend title: {e}") - def compress_audio(self, input_path): + @staticmethod + def compress_audio(input_path): base, ext = os.path.splitext(input_path) output_path = f"{base}_compressed{ext}" ffmpeg_command = f"ffmpeg -i {input_path} -ar 8000 -ac 1 -b:a 500 -acodec libmp3lame -q:a 9 {output_path}" @@ -84,5 +88,6 @@ class GrajcujZkompresowane(commands.Cog): else: await ctx.followup.send(f"dodano do koleyjki (zkompresowane): {title}") + def setup(bot): - bot.add_cog(GrajcujZkompresowane(bot)) \ No newline at end of file + bot.add_cog(GrajcujZkompresowane(bot)) diff --git a/cogs/music/queue.py b/cogs/music/queue.py index 29f0c36..d932838 100644 --- a/cogs/music/queue.py +++ b/cogs/music/queue.py @@ -1,5 +1,6 @@ from discord.ext import commands + class Queue(commands.Cog): def __init__(self, bot): self.bot = bot @@ -13,10 +14,11 @@ class Queue(commands.Cog): guild_id = ctx.guild.id queue = self.get_queue(guild_id) if queue: - queue_str = "\n".join(f"{i+1}. {title}" for i, (_, title, _) in enumerate(queue)) + queue_str = "\n".join(f"{i + 1}. {title}" for i, (_, title, _) in enumerate(queue)) await ctx.respond(f"koleyjka:\n{queue_str}") else: await ctx.respond("koleyjka jest pustawa") + def setup(bot): - bot.add_cog(Queue(bot)) \ No newline at end of file + bot.add_cog(Queue(bot)) diff --git a/cogs/music/skip.py b/cogs/music/skip.py index 67c391e..b0023fe 100644 --- a/cogs/music/skip.py +++ b/cogs/music/skip.py @@ -1,5 +1,5 @@ from discord.ext import commands -import discord + class Skip(commands.Cog): def __init__(self, bot): @@ -9,31 +9,31 @@ class Skip(commands.Cog): async def pomin(self, ctx): """Skip the current song and play the next one in the queue.""" vc = ctx.voice_client - + if not vc or not vc.is_connected(): await ctx.respond("Nie jestem połączony z kanałem głosowym.") return - + if not vc.is_playing() and not vc.is_paused(): await ctx.respond("Nic nie jest teraz odtwarzane.") return - + # Get the play cog play_cog = self.bot.get_cog('Play') if not play_cog: await ctx.respond("Błąd: Nie można znaleźć modułu odtwarzania.") return - + queue = play_cog.get_queue(ctx.guild.id) - + if not queue: await ctx.respond("Kolejka jest pusta.") return - + # Stop the current song (this will trigger play_next in the after callback) vc.stop() await ctx.respond("Pominięto aktualną piosenkę.") - + @commands.slash_command(name="kolejka", description="pokaż aktualną kolejkę") async def queue_list(self, ctx): """Show the current queue.""" @@ -41,21 +41,22 @@ class Skip(commands.Cog): if not play_cog: await ctx.respond("Błąd: Nie można znaleźć modułu odtwarzania.") return - + queue = play_cog.get_queue(ctx.guild.id) - + if not queue: await ctx.respond("Kolejka jest pusta.") return - + queue_list = [] for i, (title, _) in enumerate(queue[:10], 1): # Show up to 10 songs queue_list.append(f"{i}. {title}") - + if len(queue) > 10: queue_list.append(f"...i {len(queue) - 10} więcej") - + await ctx.respond("\n".join(["**Kolejka:**"] + queue_list)) + def setup(bot): - bot.add_cog(Skip(bot)) \ No newline at end of file + bot.add_cog(Skip(bot)) diff --git a/cogs/ping_commands.py b/cogs/ping_commands.py deleted file mode 100644 index beb9685..0000000 --- a/cogs/ping_commands.py +++ /dev/null @@ -1,60 +0,0 @@ -import discord -from discord.ext import commands -import asyncio -from yt_dlp import VideosSearch - -class PingCommands(commands.Cog): - def __init__(self, bot): - self.bot = bot - - @commands.Cog.command() - async def vc(self, ctx): - # join voice channel - pass - - @commands.slash_command(name="grajcuj", description="grajcuj melodyje") - async def play(self, ctx, *, search: str): - await ctx.defer() - if not (ctx.author.voice and ctx.author.voice.channel): - await ctx.followup.send("nie jesteś w kanale głosowym") - return - channel = ctx.author.voice.channel - if ctx.voice_client is not None: - vc = ctx.voice_client - await vc.move_to(channel) - else: - vc = await channel.connect() - videos_search = VideosSearch(search, limit=1) - result = videos_search.result() - if not result['result']: - await ctx.followup.send("nie znaleziono wideo dla twojego wyszukiwania.", ephemeral=True) - return - video = result['result'][0] - title = video['title'] - url = video['link'] - - # Get direct audio stream URL - proc = await asyncio.create_subprocess_exec( - "yt-dlp", "-f", "bestaudio", "-g", url, - stdout=asyncio.subprocess.PIPE - ) - stdout, _ = await proc.communicate() - stream_url = stdout.decode().strip() - - ffmpeg_options = { - "before_options": "-probesize 32k -analyzeduration 0 -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5", - "options": "-vn" - } - audio = discord.FFmpegPCMAudio( - stream_url, - before_options=ffmpeg_options["before_options"], - options=ffmpeg_options["options"] - ) - if not vc.is_playing(): - vc.play(audio) - await ctx.followup.send(f"gra: {title}") - else: - await ctx.followup.send(f"dodano do koleyjki: {title}") - - - diff --git a/cogs/tts.py b/cogs/tts.py index 41dc366..2481ab3 100644 --- a/cogs/tts.py +++ b/cogs/tts.py @@ -1,8 +1,10 @@ +import datetime +import os + import discord from discord.ext import commands from gtts import gTTS -import os -import datetime + class TTS(commands.Cog): def __init__(self, bot): @@ -10,22 +12,22 @@ class TTS(commands.Cog): @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) - ): + 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')) os.remove('tts.mp3') elif output == "vc": - # Check if user is in a voice channel + # 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) os.remove('tts.mp3') return channel = ctx.author.voice.channel - # Connect to voice channel if not already connected + # 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() @@ -43,5 +45,6 @@ class TTS(commands.Cog): await ctx.respond("Nieznany sposób odtwarzania.", ephemeral=True) os.remove('tts.mp3') + def setup(bot): - bot.add_cog(TTS(bot)) \ No newline at end of file + bot.add_cog(TTS(bot)) diff --git a/cogs/vc_logs.py b/cogs/vc_logs.py deleted file mode 100644 index e4a8454..0000000 --- a/cogs/vc_logs.py +++ /dev/null @@ -1,110 +0,0 @@ - -import discord -from discord.ext import commands -import datetime -from gtts import gTTS -import os -import json - -class vc_logs(commands.Cog): - def __init__(self, bot): - self.bot = bot - - async def play_tts(self, channel, text): - # Generate TTS audio - tts = gTTS(text=text, lang='pl') - tts.save('temp_tts.mp3') - - # Connect to 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(): - if os.path.exists('settings.json'): - with open('settings.json') as f: - data = json.load(f) - volume = data['volume'] - else: - with open('settings.json', 'w') as f: - json.dump({'volume': '5'}, f, indent=4) - - audio_source = discord.FFmpegPCMAudio('temp_tts.mp3', options=f'-filter:a "volume={volume}"') - voice_client.play(audio_source) - while voice_client.is_playing(): - await discord.utils.sleep_until(datetime.datetime.now() + datetime.timedelta(seconds=1)) - os.remove('temp_tts.mp3') - - @commands.slash_command( - name="log_volume" - ) - async def volume(self, ctx: discord.ApplicationContext, volume: int): - try: - if not os.path.exists('settings.json'): - with open('settings.json', 'w') as f: - json.dump({'volume': '5'}, f, indent=4) - with open('settings.json', 'w') as f: - json.dump({"volume": volume}, f, indent=4) - await ctx.send(f"Volume has been set to: {volume}") - except Exception as e: - await ctx.respond(e, ephemeral=True) - print(e) - - - - @commands.Cog.listener() - async def on_voice_state_update(self, member, before, after): - log_channel = self.bot.get_channel(1213843195457183885) - current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") - tts_text = None - tts_channel = None - # Ignore if user is a bot - if member.bot: - return - if before.channel is None and after.channel is not None: - message = f"[{current_time}] {member.name} dołączył na {after.channel.name}" - tts_text = f"{member.display_name} sie zespawnił" - tts_channel = after.channel - await log_channel.send(message) - print(message) - elif before.channel is not None and after.channel is None: - message = f"[{current_time}] {member.name} rozłączył się z {before.channel.name}" - tts_text = f"{member.display_name} jest chujem" - tts_channel = before.channel - await log_channel.send(message) - print(message) - - if before.self_deaf != after.self_deaf: - if after.self_deaf: - message = f"[{current_time}] {member.name} ogłuchnął się na {after.channel.name}" - tts_text = f"{member.display_name} jest bity przez ojca" - else: - message = f"[{current_time}] {member.name} odgłuchął się na {after.channel.name}" - tts_text = f"{member.display_name} uciek od ojca" - tts_channel = after.channel - await log_channel.send(message) - print(message) - if tts_text and tts_channel: - await self.play_tts(tts_channel, tts_text) - return - - if before.self_mute != after.self_mute: - if after.self_mute: - message = f"[{current_time}] {member.name} wyciszył się na {after.channel.name}" - tts_text = f"{member.display_name} idzie robić jajecznice" - else: - message = f"[{current_time}] {member.name} odciszył się na {after.channel.name}" - tts_text = f"{member.display_name} zrobił jajecznice" - tts_channel = after.channel - await log_channel.send(message) - print(message) - - if tts_text and tts_channel: - await self.play_tts(tts_channel, tts_text) - - -def setup(bot): - bot.add_cog(vc_logs(bot)) \ No newline at end of file diff --git a/cogs/vclogs.py b/cogs/vclogs.py new file mode 100644 index 0000000..4bc7104 --- /dev/null +++ b/cogs/vclogs.py @@ -0,0 +1,130 @@ +import datetime +import json +import os + +import discord +from discord.ext import commands +from gtts import gTTS + + +class VcLogs(commands.Cog): + def __init__(self, bot): + self.bot = bot + + @staticmethod + async def handle_state_change(member, channel, state_type, is_enabled, current_time, log_channel): + """Helper method to handle voice state changes""" + state_messages = { + 'deaf': { + True: ( + f"[{current_time}] {member.name} ogłuchnął się na {channel.name}", + f"{member.display_name} jest bity przez ojca" + ), + False: ( + f"[{current_time}] {member.name} odgłuchał się na {channel.name}", + f"{member.display_name} uciek od ojca" + ) + }, + 'mute': { + True: ( + f"[{current_time}] {member.name} wyciszył się na {channel.name}", + f"{member.display_name} idzie robić jajecznice" + ), + False: ( + f"[{current_time}] {member.name} odciszył się na {channel.name}", + f"{member.display_name} zrobił jajecznice" + ) + } + } + + message, tts_text = state_messages[state_type][is_enabled] + await log_channel.send(message) + print(message) + return tts_text, channel + + async def play_tts(self, channel, text): + # Generate TTS audio + tts = gTTS(text=text, lang='pl') + tts.save('temp_tts.mp3') + + # 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(): + if os.path.exists('settings.json'): + with open('settings.json') as f: + data = json.load(f) + volume = data['volume'] + else: + with open('settings.json', 'w') as f: + json.dump({'volume': '5'}, f, indent=4) + + audio_source = discord.FFmpegPCMAudio('temp_tts.mp3', options=f'-filter:a "volume={volume}"') + voice_client.play(audio_source) + while voice_client.is_playing(): + await discord.utils.sleep_until(datetime.datetime.now() + datetime.timedelta(seconds=1)) + os.remove('temp_tts.mp3') + + @commands.slash_command( + name="log_volume" + ) + async def volume(self, ctx: discord.ApplicationContext, volume: int): + try: + if not os.path.exists('settings.json'): + with open('settings.json', 'w') as f: + json.dump({'volume': '5'}, f, indent=4) + with open('settings.json', 'w') as f: + json.dump({"volume": volume}, f, indent=4) + await ctx.send(f"Volume has been set to: {volume}") + except Exception as e: + await ctx.respond(e, ephemeral=True) + print(e) + + @commands.Cog.listener() + async def on_voice_state_update(self, member, before, after): + log_channel = self.bot.get_channel(1213843195457183885) + current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + tts_text = None + tts_channel = None + + # Ignore if the user is a bot + if member.bot: + return + + if before.channel is None and after.channel is not None: + message = f"[{current_time}] {member.name} dołączył na {after.channel.name}" + tts_text = f"{member.display_name} sie zespawnił" + tts_channel = after.channel + await log_channel.send(message) + print(message) + elif before.channel is not None and after.channel is None: + message = f"[{current_time}] {member.name} rozłączył się z {before.channel.name}" + tts_text = f"{member.display_name} jest chujem" + tts_channel = before.channel + await log_channel.send(message) + print(message) + + if before.self_deaf != after.self_deaf: + tts_text, tts_channel = await self.handle_state_change( + member, after.channel, 'deaf', after.self_deaf, current_time, log_channel + ) + if tts_text and tts_channel: + await self.play_tts(tts_channel, tts_text) + return + + if before.self_mute != after.self_mute: + tts_text, tts_channel = await self.handle_state_change( + member, after.channel, 'mute', after.self_mute, current_time, log_channel + ) + + if tts_text and tts_channel: + await self.play_tts(tts_channel, tts_text) + + +def setup(bot): + bot.add_cog(VcLogs(bot)) \ No newline at end of file diff --git a/main.py b/main.py index e21ec66..5993734 100644 --- a/main.py +++ b/main.py @@ -1,18 +1,22 @@ import datetime import os -from dotenv import load_dotenv + # create a pycord bot template import discord from discord.ext import commands +from dotenv import load_dotenv bot = commands.Bot(intents=discord.Intents.all()) + + @bot.event async def on_ready(): print(f"ŁUKASZ SPERMA AKTYWACJA" + datetime.datetime.now().strftime("(%Y-%m-%d %H:%M:%S)")) - # send message to channel ID + # send the message to channel ID channel = bot.get_channel(1081667823799111804) await channel.send("ŁUKASZ SPERMA AKTYWACJA") + if __name__ == "__main__": load_dotenv() extensions = [ -- cgit v1.2.3