xurk

I want to run the bot, where do I put the token and how do I turn it up?

Kodari AI
KodariNov 6 at 10:03 pm 1

Create a .env file in the same folder as bot.py and add:

Env
DISCORD_TOKEN=your_bot_token_here

Get the token from the Discord Developer Portal → your application → Bot. Keep it secret.

To start the bot locally, run:

Shell
pip install -r requirements.txt
python bot.py

To run it on Kodari, add the token to .env in the project and start the bot from the hosting controls.

Kodari can make mistakes. Review important code before using.
Files
bot.py
README.md
requirements.txt
Code
3 466
bot.py
from __future__ import annotations

import asyncio
import json
import logging
import os
from dataclasses import dataclass
from datetime import timedelta
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


load_dotenv()


@dataclass(frozen=True)
class Settings:
    token: str
    log_level: str
    warnings_file: Path

    @classmethod
    def from_environment(cls) -> "Settings":
        token = os.getenv("DISCORD_TOKEN", "").strip()
        if not token:
            raise RuntimeError("DISCORD_TOKEN is missing from the environment")

        return cls(
            token=token,
            log_level=os.getenv("LOG_LEVEL", "INFO").upper(),
            warnings_file=Path(os.getenv("WARNINGS_FILE", "data/warnings.json")),
        )


class WarningStore:
    def __init__(self, path: Path) -> None:
        self.path = path
        self._lock = asyncio.Lock()
        self._warnings: dict[str, list[dict[str, Any]]] = {}

    async def load(self) -> None:
        async with self._lock:
            self.path.parent.mkdir(parents=True, exist_ok=True)
            if not self.path.exists():
                self._warnings = {}
                await self._save_locked()
                return

            try:
                data = json.loads(self.path.read_text(encoding="utf-8"))
            except (OSError, json.JSONDecodeError) as error:
                raise RuntimeError(f"Unable to read warnings file: {self.path}") from error

            self._warnings = data if isinstance(data, dict) else {}

    async def add(
        self,
        guild_id: int,
        user_id: int,
        moderator_id: int,
        reason: str,
    ) -> dict[str, Any]:
        async with self._lock:
            key = self._key(guild_id, user_id)
            entries = self._warnings.setdefault(key, [])
            warning = {
                "id": len(entries) + 1,
                "moderator_id": moderator_id,
                "reason": reason,
                "created_at": discord.utils.utcnow().isoformat(),
            }
            entries.append(warning)
            await self._save_locked()
            return warning

    async def get(self, guild_id: int, user_id: int) -> list[dict[str, Any]]:
        async with self._lock:
            return list(self._warnings.get(self._key(guild_id, user_id), []))

    async def clear(self, guild_id: int, user_id: int) -> int:
        async with self._lock:
            key = self._key(guild_id, user_id)
            removed = len(self._warnings.pop(key, []))
            await self._save_locked()
            return removed

    @staticmethod
    def _key(guild_id: int, user_id: int) -> str:
        return f"{guild_id}:{user_id}"

    async def _save_locked(self) -> None:
        self.path.parent.mkdir(parents=True, exist_ok=True)
        temporary_path = self.path.with_suffix(f"{self.path.suffix}.tmp")
        temporary_path.write_text(
            json.dumps(self._warnings, indent=2, ensure_ascii=False),
            encoding="utf-8",
        )
        temporary_path.replace(self.path)


def display_name(user: discord.abc.User) -> str:
    return f"{user} ({user.id})"


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


def guild_only(interaction: discord.Interaction) -> bool:
    return interaction.guild is not None


def has_permission(interaction: discord.Interaction, permission: str) -> bool:
    return bool(
        interaction.guild
        and isinstance(interaction.user, discord.Member)
        and getattr(interaction.user.guild_permissions, permission, False)
    )


def bot_can_moderate(interaction: discord.Interaction, member: discord.Member) -> bool:
    guild = interaction.guild
    bot_member = guild.me if guild else None
    if bot_member is None:
        return False
    return member != guild.owner and member.top_role < bot_member.top_role


class Moderation(commands.Cog):
    def __init__(self, bot: "BleedBot") -> None:
        self.bot = bot

    @app_commands.command(name="clear", description="Delete recent messages from this channel.")
    @app_commands.describe(amount="Number of messages to delete, from 1 to 100")
    @app_commands.checks.cooldown(1, 5.0)
    async def clear(self, interaction: discord.Interaction, amount: app_commands.Range[int, 1, 100]) -> None:
        if not guild_only(interaction) or not has_permission(interaction, "manage_messages"):
            await reply(interaction, "You need the Manage Messages permission.")
            return
        if not isinstance(interaction.channel, discord.TextChannel):
            await reply(interaction, "This command can only be used in a text channel.")
            return

        await interaction.response.defer(ephemeral=True)
        deleted = await interaction.channel.purge(limit=amount)
        await interaction.edit_original_response(content=f"Deleted {len(deleted)} message(s).")

    @app_commands.command(name="kick", description="Kick a member from the server.")
    @app_commands.describe(member="Member to kick", reason="Reason for the kick")
    async def kick(self, interaction: discord.Interaction, member: discord.Member, reason: str = "No reason provided") -> None:
        if not guild_only(interaction) or not has_permission(interaction, "kick_members"):
            await reply(interaction, "You need the Kick Members permission.")
            return
        if not bot_can_moderate(interaction, member):
            await reply(interaction, "I cannot moderate that member because of role hierarchy.")
            return

        try:
            await member.kick(reason=f"{reason} — by {display_name(interaction.user)}")
        except discord.Forbidden:
            await reply(interaction, "Discord refused the kick. Check my role hierarchy and permissions.")
            return
        await reply(interaction, f"Kicked **{member}**. Reason: {reason}", ephemeral=False)

    @app_commands.command(name="ban", description="Ban a member from the server.")
    @app_commands.describe(
        member="Member to ban",
        reason="Reason for the ban",
        delete_days="Delete up to 7 days of the member's messages",
    )
    async def ban(
        self,
        interaction: discord.Interaction,
        member: discord.Member,
        reason: str = "No reason provided",
        delete_days: app_commands.Range[int, 0, 7] = 0,
    ) -> None:
        if not guild_only(interaction) or not has_permission(interaction, "ban_members"):
            await reply(interaction, "You need the Ban Members permission.")
            return
        if not bot_can_moderate(interaction, member):
            await reply(interaction, "I cannot moderate that member because of role hierarchy.")
            return

        try:
            await interaction.guild.ban(