import discord from discord.ext import commands, tasks import aiosqlite import asyncio…
- User
import discord from discord.ext import commands, tasks import aiosqlite import asyncio from collections import defaultdict from datetime import datetime, timedelta import re
ID des Kanals, in den Verstöße gesendet werden
VIOLATION_CHANNEL_ID = 1268575457398362208 # Ersetze dies durch deine tatsächliche Kanal-ID
class Spam(commands.Cog): def init(self, bot: commands.Bot): self.bot = bot self.bot.loop.create_task(self.initialize_database()) # Nachrichtenprotokoll: Benutzer-ID -> Liste der Timestamps self.message_log = defaultdict(list) # Verstoßzähler: Benutzer-ID -> Anzahl der Verstöße self.violations = defaultdict(int) # Standard Spam-Schwellenwerte self.threshold = {'messages': 5, 'seconds': 10} # Standard Verstoß-Einstellungen self.violation_settings = {'count': 3, 'timeout_duration': 3600} # in Sekunden # Aufgabe zur Reinigung des Nachrichtenprotokolls self.clean_logs.start()
def cog_unload(self): self.clean_logs.cancel() @tasks.loop(minutes=1) async def clean_logs(self): """Reinigt alte Nachrichtenprotokolle, um Speicher zu sparen.""" current_time = datetime.utcnow().timestamp() for user_id, timestamps in self.message_log.items(): self.message_log[user_id] = [ts for ts in timestamps if current_time - ts < self.threshold['seconds']] async def initialize_database(self): """Initialisiert die SQLite-Datenbank und Tabellen.""" async with aiosqlite.connect("spam_protection.db") as db: await db.execute(""" CREATE TABLE IF NOT EXISTS whitelist ( type TEXT NOT NULL, id INTEGER NOT NULL, PRIMARY KEY (type, id) ) """) await db.execute(""" CREATE TABLE IF NOT EXISTS blacklist ( type TEXT NOT NULL, id INTEGER NOT NULL, PRIMARY KEY (type, id) ) """) await db.execute(""" CREATE TABLE IF NOT EXISTS settings ( key TEXT PRIMARY KEY, value TEXT NOT NULL ) """) await db.commit() # Lade Einstellungen aus der Datenbank async with db.execute("SELECT key, value FROM settings") as cursor: async for key, value in cursor: if key == 'threshold_messages': self.threshold['messages'] = int(value) elif key == 'threshold_seconds': self.threshold['seconds'] = int(value) elif key == 'violation_count': self.violation_settings['count'] = int(value) elif key == 'violation_timeout_duration': self.violation_settings['timeout_duration'] = int(value) # Hilfsfunktionen für Datenbankoperationen async def add_to_list(self, list_type: str, item_type: str, item_id: int): async with aiosqlite.connect("spam_protection.db") as db: try: await db.execute(f"INSERT INTO {list_type} (type, id) VALUES (?, ?)", (item_type, item_id)) await db.commit() return True except aiosqlite.IntegrityError: return False async def remove_from_list(self, list_type: str, item_type: str, item_id: int): async with aiosqlite.connect("spam_protection.db") as db: await db.execute(f"DELETE FROM {list_type} WHERE type = ? AND id = ?", (item_type, item_id)) await db.commit() async def is_whitelisted(self, user: discord.Member, channel: discord.TextChannel): async with aiosqlite.connect("spam_protection.db") as db: # Prüfe auf Benutzer-Whitelist async with db.execute("SELECT 1 FROM whitelist WHERE type = 'user' AND id = ?", (user.id,)) as cursor: if await cursor.fetchone(): return True # Prüfe auf Kanal-Whitelist async with db.execute("SELECT 1 FROM whitelist WHERE type = 'channel' AND id = ?", (channel.id,)) as cursor: if await cursor.fetchone(): return True # Prüfe auf Rollen-Whitelist for role in user.roles: if role.is_default(): continue async with db.execute("SELECT 1 FROM whitelist WHERE type = 'role' AND id = ?", (role.id,)) as cursor: if await cursor.fetchone(): return True return False async def is_blacklisted(self, user: discord.Member, channel: discord.TextChannel): async with aiosqlite.connect("spam_protection.db") as db: # Prüfe auf Benutzer-Blacklist async with db.execute("SELECT 1 FROM blacklist WHERE type = 'user' AND id = ?", (user.id,)) as cursor: if await cursor.fetchone(): return True # Prüfe auf Kanal-Blacklist async with db.execute("SELECT 1 FROM blacklist WHERE type = 'channel' AND id = ?", (channel.id,)) as cursor: if await cursor.fetchone(): return True # Prüfe auf Rollen-Blacklist for role in user.roles: if role.is_default(): continue async with db.execute("SELECT 1 FROM blacklist WHERE type = 'role' AND id = ?", (role.id,)) as cursor: if await cursor.fetchone(): return True return False # Ereignislistener für Nachrichten @commands.Cog.listener() async def on_message(self, message: discord.Message): if message.author.bot: return # Überprüfe, ob der Benutzer oder der Kanal ausgeschlossen ist if await self.is_whitelisted(message.author, message.channel): return if await self.is_blacklisted(message.author, message.channel): # Optional: Handhabung für schwarze Listen return current_time = datetime.utcnow().timestamp() self.message_log[message.author.id].append(current_time) # Bereinige alte Nachrichten self.message_log[message.author.id] = [ ts for ts in self.message_log[message.author.id] if current_time - ts < self.threshold['seconds'] ] if len(self.message_log[message.author.id]) > self.threshold['messages']: # Überschreitung erkannt try: await message.delete() except discord.Forbidden: pass # Keine Berechtigung, Nachricht zu löschen # Informiere den Benutzer (optional) try: await message.author.send("Bitte unterlasse das Spamming auf Blair Deutschland.") except discord.Forbidden: pass # Benutzer hat keine DM geöffnet # Sende die Verletzung an den spezifischen Kanal violation_channel = self.bot.get_channel(VIOLATION_CHANNEL_ID) if violation_channel: embed = discord.Embed( title="Spam-Verstoß", description=f"**Benutzer:** {message.author.mention} (`{message.author.id}`)\n" f"**Kanal:** {message.channel.mention}\n" f"**Nachricht:** {message.content}", color=discord.Color.red(), timestamp=datetime.utcnow() ) await violation_channel.send(embed=embed) # Erhöhe den Verstoßzähler self.violations[message.author.id] += 1 # Prüfe, ob die Verstoßanzahl das Limit erreicht hat if self.violations[message.author.id] >= self.violation_settings['count']: try: # Timeout anwenden timeout_duration = self.violation_settings['timeout_duration'] until = datetime.utcnow() + timedelta(seconds=timeout_duration) await message.author.timeout(until, reason="Spam-Verstöße") await violation_channel.send( f"{message.author.mention} wurde für {self.format_duration(timeout_duration)} wegen Spam verwarnt." ) except discord.Forbidden: await violation_channel.send( f"Ich habe keine Berechtigung, {message.author.mention} zu stummschalten." ) # Zurücksetzen des Verstoßzählers self.violations[message.author.id] = 0 # Hilfsfunktion zur Formatierung der Dauer def format_duration(self, seconds: int) -> str: parts = [] intervals = ( ('h', 3600), ('m', 60), ('s', 1), ) for suffix, length in intervals: value = seconds // length if value: parts.append(f"{value}{suffix}") seconds %= length return ' '.join(parts) if parts else '0s' # Definiere die Slash Command Gruppe und deren Befehle spam_group = discord.SlashCommandGroup(name="spam", description="Commands, die eine Relation mit Spamming zu tun haben.") # Whitelist Befehle @spam_group.command(name="whitelist_user", description="Füge einen Benutzer zur Whitelist hinzu.") @discord.option(name="user", description="Der Benutzer, der hinzugefügt werden soll.", type=discord.Member, required=True) @commands.has_permissions(administrator=True) async def whitelist_user(self, ctx: discord.ApplicationContext, user: discord.Member): success = await self.add_to_list('whitelist', 'user', user.id) if success: await ctx.respond(f"{user.mention} wurde zur Whitelist hinzugefügt.", ephemeral=True) else: await ctx.respond(f"{user.mention} ist bereits in der Whitelist.", ephemeral=True) @spam_group.command(name="whitelist_channel", description="Füge einen Kanal zur Whitelist hinzu.") @discord.option(name="channel", description="Der Kanal, der hinzugefügt werden soll.", type=discord.TextChannel, required=True) @commands.has_permissions(administrator=True) async def whitelist_channel(self, ctx: discord.ApplicationContext, channel: discord.TextChannel): success = await self.add_to_list('whitelist', 'channel', channel.id) if success: await ctx.respond(f"{channel.mention} wurde zur Whitelist hinzugefügt.", ephemeral=True) else: await ctx.respond(f"{channel.mention} ist bereits in der Whitelist.", ephemeral=True) @spam_group.command(name="whitelist_role", description="Füge eine Rolle zur Whitelist hinzu.") @discord.option(name="role", description="Die Rolle, die hinzugefügt werden soll.", type=discord.Role, required=True) @commands.has_permissions(administrator=True) async def whitelist_role(self, ctx: discord.ApplicationContext, role: discord.Role): success = await self.add_to_list('whitelist', 'role', role.id) if success: await ctx.respond(f"Die Rolle {role.name} wurde zur Whitelist hinzugefügt.", ephemeral=True) else: await ctx.respond(f"Die Rolle {role.name} ist bereits in der Whitelist.", ephemeral=True) # Blacklist Befehle @spam_group.command(name="blacklist_user", description="Füge einen Benutzer zur Blacklist hinzu.") @discord.option(name="user", description="Der Benutzer, der hinzugefügt werden soll.", type=discord.Member, required=True) @commands.has_permissions(administrator=True) async def blacklist_user(self, ctx: discord.ApplicationContext, user: discord.Member): success = await self.add_to_list('blacklist', 'user', user.id) if success: await ctx.respond(f"{user.mention} wurde zur Blacklist hinzugefügt.", ephemeral=True) else: await ctx.respond(f"{user.mention} ist bereits in der Blacklist.", ephemeral=True) @spam_group.command(name="blacklist_channel", description="Füge einen Kanal zur Blacklist hinzu.") @discord.option(name="channel", description="Der Kanal, der hinzugefügt werden soll.", type=discord.TextChannel, required=True) @commands.has_permissions(administrator=True) async def blacklist_channel(self, ctx: discord.ApplicationContext, channel: discord.TextChannel): success = await self.add_to_list('blacklist', 'channel', channel.id) if success: await ctx.respond(f"{channel.mention} wurde zur Blacklist hinzugefügt.", ephemeral=True) else: await ctx.respond(f"{channel.mention} ist bereits in der Blacklist.", ephemeral=True) @spam_group.command(name="blacklist_role", description="Füge eine Rolle zur Blacklist hinzu.") @discord.option(name="role", description="Die Rolle, die hinzugefügt werden soll.", type=discord.Role, required=True) @commands.has_permissions(administrator=True) async def blacklist_role(self, ctx: discord.ApplicationContext, role: discord.Role): success = await self.add_to_list('blacklist', 'role', role.id) if success: await ctx.respond(f"Die Rolle {role.name} wurde zur Blacklist hinzugefügt.", ephemeral=True) else: await ctx.respond(f"Die Rolle {role.name} ist bereits in der Blacklist.", ephemeral=True) # View Blacklist und Whitelist @spam_group.command(name="view_blacklist", description="Zeigt die aktuelle Blacklist an.") @commands.has_permissions(administrator=True) async def view_blacklist(self, ctx: discord.ApplicationContext): async with aiosqlite.connect("spam_protection.db") as db: cursor = await db.execute("SELECT type, id FROM blacklist") entries = await cursor.fetchall() if not entries: await ctx.respond("Die Blacklist ist leer.", ephemeral=True) return embed = discord.Embed(title="Blacklist", color=discord.Color.orange()) for entry in entries: entry_type, entry_id = entry if entry_type == 'user': user = self.bot.get_user(entry_id) name = user.mention if user else f"Unbekannter Benutzer ({entry_id})" elif entry_type == 'channel': channel = self.bot.get_channel(entry_id) name = channel.mention if channel else f"Unbekannter Kanal ({entry_id})" elif entry_type == 'role': role = ctx.guild.get_role(entry_id) name = role.mention if role else f"Unbekannte Rolle ({entry_id})" embed.add_field(name=entry_type.capitalize(), value=name, inline=False) await ctx.respond(embed=embed, ephemeral=True) @spam_group.command(name="view_whitelist", description="Zeigt die aktuelle Whitelist an.") @commands.has_permissions(administrator=True) async def view_whitelist(self, ctx: discord.ApplicationContext): async with aiosqlite.connect("spam_protection.db") as db: cursor = await db.execute("SELECT type, id FROM whitelist") entries = await cursor.fetchall() if not entries: await ctx.respond("Die Whitelist ist leer.", ephemeral=True) return embed = discord.Embed(title="Whitelist", color=discord.Color.green()) for entry in entries: entry_type, entry_id = entry if entry_type == 'user': user = self.bot.get_user(entry_id) name = user.mention if user else f"Unbekannter Benutzer ({entry_id})" elif entry_type == 'channel': channel = self.bot.get_channel(entry_id) name = channel.mention if channel else f"Unbekannter Kanal ({entry_id})" elif entry_type == 'role': role = ctx.guild.get_role(entry_id) name = role.mention if role else f"Unbekannte Rolle ({entry_id})" embed.add_field(name=entry_type.capitalize(), value=name, inline=False) await ctx.respond(embed=embed, ephemeral=True) # Schwellenwert setzen @spam_group.command(name="set_spam_threshold", description="Setzt das Spam-Limit.") @discord.option(name="messages", description="Anzahl der Nachrichten", type=int, required=True) @discord.option(name="seconds", description="Zeitraum in Sekunden", type=int, required=True) @commands.has_permissions(administrator=True) async def set_spam_threshold(self, ctx: discord.ApplicationContext, messages: int, seconds: int): if messages < 1 or seconds < 1: await ctx.respond("Die Werte müssen größer als 0 sein.", ephemeral=True) return self.threshold['messages'] = messages self.threshold['seconds'] = seconds # Speichern in der Datenbank async with aiosqlite.connect("spam_protection.db") as db: await db.execute("REPLACE INTO settings (key, value) VALUES ('threshold_messages', ?)", (str(messages),)) await db.execute("REPLACE INTO settings (key, value) VALUES ('threshold_seconds', ?)", (str(seconds),)) await db.commit() await ctx.respond(f"Spam-Schwellenwert auf {messages} Nachrichten pro {seconds} Sekunden gesetzt.", ephemeral=True) # Verstoß-Einstellungen setzen @spam_group.command(name="set_spam_violation", description="Setzt die Verstoß-Einstellungen.") @discord.option(name="violation_count", description="Anzahl der Verstöße bevor eine Strafe erfolgt", type=int, required=True) @discord.option(name="timeout_duration", description="Dauer des Timeouts (z.B. 1h, 30m, 45s)", type=str, required=True) @commands.has_permissions(administrator=True) async def set_spam_violation(self, ctx: discord.ApplicationContext, violation_count: int, timeout_duration: str): if violation_count < 1: await ctx.respond("Die Anzahl der Verstöße muss größer als 0 sein.", ephemeral=True) return # Konvertiere timeout_duration zu Sekunden try: timeout_seconds = self.parse_duration(timeout_duration) except ValueError: await ctx.respond("Ungültiges Zeitformat. Verwende z.B. 1h für eine Stunde, 30m für 30 Minuten oder 45s für 45 Sekunden.", ephemeral=True) return self.violation_settings['count'] = violation_count self.violation_settings['timeout_duration'] = timeout_seconds # Speichern in der Datenbank async with aiosqlite.connect("spam_protection.db") as db: await db.execute("REPLACE INTO settings (key, value) VALUES ('violation_count', ?)", (str(violation_count),)) await db.execute("REPLACE INTO settings (key, value) VALUES ('violation_timeout_duration', ?)", (str(timeout_seconds),)) await db.commit() await ctx.respond(f"Verstoß-Einstellungen aktualisiert: {violation_count} Verstöße führen zu einem Timeout von {self.format_duration(timeout_seconds)}.", ephemeral=True) def parse_duration(self, duration_str: str) -> int: """Parst eine Dauer-String wie '1h', '30m', '45s' in Sekunden.""" pattern = re.compile(r'^(\d+)([hms])$') match = pattern.match(duration_str.lower()) if not match: raise ValueError("Ungültiges Format") amount, unit = match.groups() amount = int(amount) if unit == 'h': return amount * 3600 elif unit == 'm': return amount * 60 elif unit == 's': return amount else: raise ValueError("Ungültiges Einheitenzeichen.") # Error Handling für Commands async def cog_command_error(self, ctx: discord.ApplicationContext, error): if isinstance(error, commands.MissingPermissions): await ctx.respond("Du hast nicht die erforderlichen Berechtigungen, um diesen Befehl zu verwenden.", ephemeral=True) elif isinstance(error, commands.MissingRequiredArgument): await ctx.respond("Ein erforderliches Argument fehlt.", ephemeral=True) else: await ctx.respond("Ein Fehler ist aufgetreten. Bitte versuche es später erneut.", ephemeral=True) print(f"Fehler bei Spam-Command: {error}") - Assistant