max21321312.

Discord-Bot – Funktionsplan Version 1.0 (Grundfunktionen) Begrüßungsnachrichten /help /ping Server- und Benutzerinfos Embed-Nachrichten

Version 2.0 (Moderation) Kick Ban Timeout Warnsystem AutoMod Log-System

Version 3.0 (Community) Ticketsystem Levelsystem Reaktionsrollen Willkommensrollen Umfragen

Version 4.0 (Erweiterungen) Musik KI-Befehle Erinnerungen Giveaway-System Wirtschaftssystem Minispiele

Version 5.0 (Premium) Web-Dashboard Mehrsprachigkeit Backups Statistiken Individuelle Einstellungen pro Server

Kodari AI
KodariAug 5 at 11:28 pm 5
DiscordModerationSuite
A comprehensive Discord moderation bot built with discord.py. Features slash commands for kicking, banning, and timing out users, a warning system with configurable thresholds, automatic message filtering for spam and inappropriate content, and detailed logging of all moderation actions to a designated channel. Includes server and user info commands, embed-based responses, and a help command. Designed for easy setup with a token configuration file and modular cog structure for maintainable expansion.
  1. Implement the Version 1 Discord bot: welcome messages, slash help, ping, server/user information, and embed posting.

  2. Add secure token/dependency setup so it runs without hardcoded credentials.

  1. Created the Version 1 Discord bot in bot.py with welcome embeds, /help, /ping, /serverinfo, /userinfo, and permission-protected /embed.

  2. Added configurable welcome settings and embed color in config.json.

  3. Added secure environment-token setup in .env, dependencies in requirements.txt, and .gitignore protection for tokens.

max21321312.

.env <redacted>

Kodari AI
KodariAug 5 at 11:28 pm 1

Der Discord-Token wurde öffentlich geteilt und muss als kompromittiert gelten.

  1. Wähle deine Anwendung → Bot → Reset Token.

  2. Kopiere den neuen Token und speichere ihn ausschließlich lokal in .env:

Env
DISCORD_TOKEN=DEIN_NEUER_TOKEN
  1. Stelle sicher, dass .env in .gitignore steht und niemals in GitHub hochgeladen wird.

  2. Starte den Bot danach neu.

Der gepostete Token sollte nicht weiter verwendet werden.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
config.json
requirements.txt
Code
4 272
bot.py
import json
import logging
import os
import time
from pathlib import Path
from typing import Any

import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv


BASE_DIR = Path(__file__).parent
CONFIG_PATH = BASE_DIR / "config.json"
DEFAULT_CONFIG: dict[str, Any] = {
    "welcome_channel_name": "willkommen",
    "welcome_message": "Willkommen {member_mention} auf **{guild_name}**!",
    "embed_color": "0x5865F2",
    "command_cooldown_seconds": 3,
}


def load_config() -> dict[str, Any]:
    try:
        with CONFIG_PATH.open("r", encoding="utf-8") as config_file:
            configured_values = json.load(config_file)
    except (OSError, json.JSONDecodeError) as error:
        logging.warning("Could not load config.json; using defaults: %s", error)
        return DEFAULT_CONFIG.copy()

    if not isinstance(configured_values, dict):
        logging.warning("config.json must contain an object; using defaults.")
        return DEFAULT_CONFIG.copy()

    config = DEFAULT_CONFIG.copy()
    config.update(configured_values)
    return config


def config_color(config: dict[str, Any]) -> discord.Color:
    try:
        value = config["embed_color"]
        return discord.Color(int(value, 0) if isinstance(value, str) else int(value))
    except (KeyError, TypeError, ValueError):
        return discord.Color.blurple()


class CommandRateLimiter:
    def __init__(self, cooldown_seconds: float) -> None:
        self.cooldown_seconds = max(0.0, cooldown_seconds)
        self.last_used: dict[tuple[int, str], float] = {}

    def remaining(self, user_id: int, command_name: str) -> float:
        key = (user_id, command_name)
        now = time.monotonic()
        previous_use = self.last_used.get(key)

        if previous_use is not None:
            elapsed = now - previous_use
            if elapsed < self.cooldown_seconds:
                return self.cooldown_seconds - elapsed

        self.last_used[key] = now
        return 0.0


class CommunityBot(commands.Bot):
    def __init__(self, config: dict[str, Any]) -> None:
        intents = discord.Intents.default()
        intents.members = True
        super().__init__(command_prefix="!", intents=intents, help_command=None)
        self.config = config
        self.embed_color = config_color(config)
        self.rate_limiter = CommandRateLimiter(float(config["command_cooldown_seconds"]))

    async def setup_hook(self) -> None:
        synced_commands = await self.tree.sync()
        logging.info("Synced %s application command(s).", len(synced_commands))

    async def interaction_check(self, interaction: discord.Interaction[discord.Client]) -> bool:
        if interaction.command is None or interaction.user is None:
            return True

        remaining = self.rate_limiter.remaining(interaction.user.id, interaction.command.name)
        if remaining <= 0:
            return True

        await interaction.response.send_message(
            f"Bitte warte noch {remaining:.1f} Sekunden, bevor du diesen Befehl erneut nutzt.",
            ephemeral=True,
        )
        return False

    async def on_ready(self) -> None:
        logging.info("Bot is ready as %s in %s server(s).", self.user, len(self.guilds))


async def respond(
    interaction: discord.Interaction[discord.Client],
    content: str | None = None,
    *,
    embed: discord.Embed | None = None,
    ephemeral: bool = False,
) -> None:
    if interaction.response.is_done():
        await interaction.followup.send(content, embed=embed, ephemeral=ephemeral)
    else:
        await interaction.response.send_message(content, embed=embed, ephemeral=ephemeral)


logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
load_dotenv()
bot = CommunityBot(load_config())


@bot.event
async def on_member_join(member: discord.Member) -> None:
    channel_name = str(bot.config["welcome_channel_name"])
    channel = discord.utils.get(member.guild.text_channels, name=channel_name)
    if channel is None:
        logging.warning("Welcome channel #%s was not found in %s.", channel_name, member.guild.name)
        return

    try:
        welcome_text = str(bot.config["welcome_message"]).format(
            member_mention=member.mention,
            guild_name=member.guild.name,
        )
    except (KeyError, ValueError):
        logging.warning("Invalid welcome_message placeholders in config.json.")
        welcome_text = f"Willkommen {member.mention} auf **{member.guild.name}**!"

    welcome_embed = discord.Embed(description=welcome_text, color=bot.embed_color)
    welcome_embed.set_author(name="Neues Mitglied", icon_url=member.display_avatar.url)
    await channel.send(
        embed=welcome_embed,
        allowed_mentions=discord.AllowedMentions(users=True, roles=False, everyone=False),
    )


@bot.tree.command(name="help", description="Zeigt die verfügbaren Befehle an.")
async def help_command(interaction: discord.Interaction[discord.Client]) -> None:
    embed = discord.Embed(title="Hilfe", color=bot.embed_color)
    embed.add_field(name="/help", value="Zeigt diese Übersicht an.", inline=False)
    embed.add_field(name="/ping", value="Zeigt die Bot-Latenz an.", inline=False)
    embed.add_field(name="/serverinfo", value="Zeigt Informationen über diesen Server an.", inline=False)
    embed.add_field(name="/userinfo [mitglied]", value="Zeigt Informationen über ein Mitglied an.", inline=False)
    embed.add_field(
        name="/embed <titel> <nachricht>",
        value="Sendet eine Embed-Nachricht (Benötigt: Nachrichten verwalten).",
        inline=False,
    )
    await respond(interaction, embed=embed, ephemeral=True)


@bot.tree.command(name="ping", description="Zeigt die Bot-Latenz an.")
async def ping_command(interaction: discord.Interaction[discord.Client]) -> None:
    await respond(interaction, f"🏓 Pong! `{round(bot.latency * 1000)} ms`")


@bot.tree.command(name="serverinfo", description="Zeigt Informationen über diesen Server an.")
@app_commands.guild_only()
async def server_info_command(interaction: discord.Interaction[discord.Client]) -> None:
    guild = interaction.guild
    if guild is None:
        await respond(interaction, "Dieser Befehl kann nur auf einem Server verwendet werden.", ephemeral=True)
        return

    owner = guild.owner.mention if guild.owner is not None else "Unbekannt"
    embed = discord.Embed(title=guild.name, color=bot.embed_color, timestamp=guild.created_at)
    if guild.icon is not None:
        embed.set_thumbnail(url=guild.icon.url)
    embed.add_field(name="Besitzer", value=owner)
    embed.add_field(name="Mitglieder", value=str(guild.member_count or 0))
    embed.add_field(name="Kanäle", value=str(len(guild.channels)))
    embed.add_field(name="Rollen", value=str(len(guild.roles)))
    embed.set_footer(text=f"Server-ID: {guild.id} • Erstellt am")
    await respond(interaction, embed=embed)


@bot.tree.command(name="userinfo", description="Zeigt Informationen über ein Mitglied an.")
@app_commands.guild_only()
@app_commands.describe(member="Das Mitglied, dessen Informationen angezeigt werden sollen.")
async def user_info_command(
    interaction: discord.Interaction[discord.Client],
    member: discord.Member | None = None,
) -> None:
    if not isinstance(interaction.user, discord.Member):
        await respond(interaction, "Mitgliedsinformationen sind hier nicht verfügbar.", ephemeral=True)
        return

    member = member or interaction.user
    roles = [role.mention for role in member.roles if not role.is_default()]
    role_text = ", ".join(roles) if roles else "Keine"
    if len(role_text) > 1024:
        role_text = role_text[:1021] + "..."