fpt_mafia

i need a bot that can do everything the other bots from discord do and it is named Vlad's BOT

Kodari AI
KodariAug 22 at 11:13 am 1

Created Vlad’s BOT, a Discord bot with:

  • Slash and prefix commands

  • Moderation: kick, ban, timeout, warnings, clear, slowmode, lock/unlock

  • Role management

  • Polls and announcements

  • Reminders with JSON persistence

  • Server, user, and avatar information

  • Fun commands: 8ball and choose

  • Cooldowns, permission checks, error handling, logging, and embeds

  • Secure .env token configuration

Run it with:

Shell
pip install -r requirements.txt
cp .env.example .env

Set DISCORD_TOKEN in .env, then start it:

Shell
python bot.py

The bot account itself should be named Vlad’s BOT through the Discord Developer Portal.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
requirements.txt
Code
3 539
bot.py
import asyncio
import json
import logging
import os
import random
import secrets
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Optional

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


load_dotenv()

TOKEN = os.getenv("DISCORD_TOKEN")
PREFIX = os.getenv("BOT_PREFIX", "!")
OWNER_IDS = {
    int(value.strip())
    for value in os.getenv("OWNER_IDS", "").split(",")
    if value.strip().isdigit()
}

if not TOKEN:
    raise RuntimeError("DISCORD_TOKEN is missing from the environment")

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("vlads_bot")

DATA_DIR = Path("data")
DATA_DIR.mkdir(exist_ok=True)
WARNINGS_FILE = DATA_DIR / "warnings.json"
REMINDERS_FILE = DATA_DIR / "reminders.json"


def read_json(path: Path, fallback):
    if not path.exists():
        return fallback
    try:
        with path.open("r", encoding="utf-8") as file:
            return json.load(file)
    except (OSError, json.JSONDecodeError):
        logger.exception("Could not read %s", path)
        return fallback


def write_json(path: Path, value) -> None:
    temporary = path.with_suffix(".tmp")
    with temporary.open("w", encoding="utf-8") as file:
        json.dump(value, file, indent=2)
    temporary.replace(path)


warnings_data = read_json(WARNINGS_FILE, {})
if not isinstance(warnings_data, dict):
    warnings_data = {}


def utc_now() -> datetime:
    return datetime.now(timezone.utc)


def format_duration(seconds: int) -> str:
    parts = []
    for amount, label in ((86400, "d"), (3600, "h"), (60, "m"), (1, "s")):
        if seconds >= amount:
            count, seconds = divmod(seconds, amount)
            parts.append(f"{count}{label}")
    return " ".join(parts) or "0s"


def embed(title: str, description: str, color: discord.Color = discord.Color.blurple()) -> discord.Embed:
    return discord.Embed(title=title, description=description, color=color, timestamp=utc_now())


class VladsBot(commands.Bot):
    def __init__(self) -> None:
        intents = discord.Intents.all()
        super().__init__(
            command_prefix=commands.when_mentioned_or(PREFIX),
            intents=intents,
            help_command=None,
            allowed_mentions=discord.AllowedMentions(
                everyone=False,
                roles=False,
                users=True,
            ),
            owner_ids=OWNER_IDS or None,
        )
        self.reminder_tasks: dict[str, asyncio.Task] = {}
        self.reminders: list[dict] = read_json(REMINDERS_FILE, [])
        if not isinstance(self.reminders, list):
            self.reminders = []

    async def setup_hook(self) -> None:
        for reminder in self.reminders.copy():
            self.schedule_reminder(reminder)
        synced = await self.tree.sync()
        logger.info("Synced %d application commands", len(synced))

    async def on_ready(self) -> None:
        await self.change_presence(
            activity=discord.Game(name=f"{PREFIX}help | Vlad's BOT")
        )
        logger.info("Logged in as %s (%s)", self.user, self.user.id if self.user else "unknown")

    def schedule_reminder(self, reminder: dict) -> None:
        reminder_id = str(reminder.get("id", ""))
        if reminder_id and reminder_id not in self.reminder_tasks:
            self.reminder_tasks[reminder_id] = asyncio.create_task(
                self._deliver_reminder(reminder)
            )

    async def _deliver_reminder(self, reminder: dict) -> None:
        reminder_id = str(reminder["id"])
        try:
            wait_for = max(0, float(reminder["due"]) - utc_now().timestamp())
            await asyncio.sleep(wait_for)
            channel = self.get_channel(int(reminder["channel_id"]))
            if channel is None:
                try:
                    channel = await self.fetch_channel(int(reminder["channel_id"]))
                except (discord.HTTPException, discord.NotFound):
                    channel = None
            if channel is not None and hasattr(channel, "send"):
                await channel.send(
                    f"<@{reminder['user_id']}> ⏰ Reminder: {reminder['text']}"
                )
        except asyncio.CancelledError:
            raise
        except (discord.Forbidden, discord.HTTPException):
            logger.warning("Could not deliver reminder %s", reminder_id)
        finally:
            self.reminder_tasks.pop(reminder_id, None)
            self.reminders = [item for item in self.reminders if str(item.get("id")) != reminder_id]
            write_json(REMINDERS_FILE, self.reminders)


bot = VladsBot()


@bot.hybrid_command(description="Show Vlad's BOT commands.")
@app_commands.describe(command="A specific command to learn more about")
async def help(ctx: commands.Context, command: Optional[str] = None) -> None:
    if command:
        selected = bot.get_command(command.lower())
        if selected is None:
            await ctx.send(embed=embed("Help", f"No command named `{command}` exists.", discord.Color.red()))
            return
        signature = f"{PREFIX}{selected.qualified_name} {selected.signature}".rstrip()
        await ctx.send(embed=embed(selected.qualified_name, f"`{signature}`\n{selected.description or 'No description available.'}"))
        return

    categories = {
        "General": "`help`, `ping`, `serverinfo`, `userinfo`, `avatar`, `poll`, `remind`",
        "Moderation": "`clear`, `kick`, `ban`, `timeout`, `untimeout`, `warn`, `warnings`, `slowmode`, `lock`, `unlock`",
        "Roles": "`role-create`, `role-add`, `role-remove`",
        "Fun": "`8ball`, `choose`",
    }
    description = "\n".join(f"**{name}**\n{commands_text}" for name, commands_text in categories.items())
    description += f"\n\nUse `{PREFIX}help <command>` for details. Slash commands are also available."
    await ctx.send(embed=embed("Vlad's BOT", description))


@bot.hybrid_command(description="Check the bot's response time.")
@commands.cooldown(1, 5, commands.BucketType.user)
async def ping(ctx: commands.Context) -> None:
    latency = round(bot.latency * 1000)
    await ctx.send(embed=embed("🏓 Pong!", f"WebSocket latency: **{latency}ms**"))


@bot.hybrid_command(description="Display information about this server.")
@commands.guild_only()
async def serverinfo(ctx: commands.Context) -> None:
    guild = ctx.guild
    if guild is None:
        return
    owner = guild.owner.mention if guild.owner else f"<@{guild.owner_id}>"
    description = (
        f"**Owner:** {owner}\n"
        f"**Members:** {guild.member_count}\n"
        f"**Channels:** {len(guild.channels)}\n"
        f"**Roles:** {len(guild.roles)}\n"
        f"**Created:** <t:{int(guild.created_at.timestamp())}:F>"
    )
    card = embed(guild.name, description)
    if guild.icon:
        card.set_thumbnail(url=guild.icon.url)
    await ctx.send(embed=card)


@bot.hybrid_command(description="Display information about a member.")
@app_commands.describe(member="The member to inspect")
async def userinfo(ctx: commands.Context, member: Optional[discord.Member] = None) -> None: