Xiaolung

make my discord bot a advance level up bot like whenever you level it's will send dm saying a new congratulations message and send what level you reach and you can also check your progress by the slash command and add a leaderboard in slash command too make it everything working and make it that whenever you level up required will be going up

here's the token of the bot

<redacted>

Kodari AI
KodariSep 10 at 5:39 pm 1
LevelUpProgressionBot
An advanced Discord leveling bot that tracks user experience points and levels. Users gain XP through activity, and upon leveling up, the bot sends a personalized direct message with a unique congratulations message and the new level achieved. The XP requirement to reach the next level increases progressively with each level. Users can check their current level, XP, and progress toward the next level using the /progress slash command. A /leaderboard slash command displays the top users ranked by level and XP, fostering friendly competition. The bot uses persistent JSON storage to maintain user data across sessions, ensuring progress is saved. It handles command errors gracefully and provides clear feedback for all interactions.
  1. Create a secure, SQLite-backed Discord leveling bot with message XP, increasing level requirements, and level-up DMs.

  2. Add /progress and /leaderboard slash commands plus environment/configuration files.

  3. Keep the supplied token out of the project; it should be regenerated because it was exposed.

Created the advanced Discord leveling bot with:

  • Persistent SQLite XP and level storage

  • Increasing XP requirements per level

  • Random XP rewards with cooldown protection

  • Automatic congratulations DMs on level-up

  • /progress [user] slash command with progress bar

  • /leaderboard slash command

  • Configurable environment variables

  • Error handling and logging

  • .gitignore protection for tokens and database files

  • Setup instructions in README.md

Files created:

  • bot.py

  • requirements.txt

  • .env.example

  • .gitignore

  • README.md

The token you shared was not added to any file. Regenerate it immediately in the Discord Developer Portal because it has been exposed. Then place the new token in .env as:

Env
DISCORD_TOKEN=your_new_token_here
Xiaolung

I can't type I the box

Kodari AI
KodariSep 10 at 5:42 pm 1

If you mean the Discord chat/message box, don’t paste the bot token there. The bot cannot safely receive its token through Discord.

Add it to a .env file in your project folder:

Env
DISCORD_TOKEN=your_new_token_here

Then restart the bot. Since the previous token was exposed, regenerate it first in Discord Developer Portal → Bot → Reset Token.

If you mean a different box—such as the code editor or terminal—tell me which app or screen you’re using.

Xiaolung

Done keep making now

Kodari AI
KodariSep 10 at 5:44 pm 1

The leveling bot is ready. Start it with:

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

Then test these slash commands in your server:

  • /progress — view your level, XP, messages, and progress bar

  • /progress @user — view another member’s progress

  • /leaderboard — view the server’s top members

Make sure Message Content Intent is enabled in the Discord Developer Portal. The bot will award XP from messages, increase the XP requirement each level, and DM users when they level up.

For instant slash-command updates during testing, add your server ID to .env:

Env
DEV_GUILD_ID=your_server_id

If the bot is hosted on a platform with a Run or Start button, use that instead of the terminal command.

Xiaolung

How to get the dev guild id

Kodari AI
KodariSep 10 at 5:45 pm 1

To get your Discord server (guild) ID:

Desktop

  1. Open Discord.

  2. Click User Settings ⚙️.

  3. Go to Advanced.

  4. Turn on Developer Mode.

  5. Right-click your server icon/name.

  6. Click Copy Server ID.

Mobile

  1. Tap your profile picture.

  2. Open Settings → Advanced.

  3. Enable Developer Mode.

  4. Long-press your server icon/name.

  5. Tap Copy Server ID.

Add it to your .env file:

Env
DEV_GUILD_ID=123456789012345678

Replace the number with your copied server ID, then restart the bot. Slash commands should appear in that server almost immediately.

Xiaolung

Continue and make

Kodari AI
KodariSep 10 at 5:47 pm 1

The bot code is already complete. Finish setup like this:

  1. Create a file named .env in the same folder as bot.py.

  2. Add:

Env
DISCORD_TOKEN=your_new_regenerated_token
DATABASE_PATH=levels.db
XP_COOLDOWN_SECONDS=60
DEV_GUILD_ID=your_server_id
  1. Install dependencies:

Shell
pip install -r requirements.txt
  1. Enable Message Content Intent in the Discord Developer Portal:

    • Developer Portal → Your Application → Bot

    • Enable Message Content Intent

    • Save changes

  2. Invite the bot with these permissions:

    • View Channels

    • Send Messages

    • Embed Links

    • Read Message History

  3. Start it:

Shell
python bot.py

Test these commands in your server:

Plain Text
/progress
/progress @member
/leaderboard

The bot will award XP from messages, increase the XP needed for every level, save progress in levels.db, and DM users when they level up.

Do not reuse the token you posted earlier—regenerate it first, then place the new token only in .env.

Xiaolung

Btw you will get xp by messing

Kodari AI
KodariSep 10 at 5:47 pm 1

Yes. The bot awards XP when users send messages in the server.

  • XP is given only after the configured cooldown, so users can’t spam for unlimited XP.

  • Bot messages are ignored.

  • Once enough XP is earned, the user levels up.

  • The required XP increases with every level.

  • The bot sends a congratulations DM showing the new level.

  • Use /progress to check XP and /leaderboard to view rankings.

Xiaolung

Make both active

Kodari AI
KodariSep 10 at 5:48 pm 1
  1. Keep message XP and slash commands active together.

  2. Ensure the message handler also processes any bot commands instead of stopping after XP handling.

  3. Preserve the existing cooldown, level-up DM, /progress, and /leaderboard behavior.

Both are active:

  • Message XP leveling continues working.

  • Prefix commands are now processed too.

  • /progress remains active.

  • /leaderboard remains active.

  • Level-up DMs and increasing XP requirements remain active.

Restart the bot after saving the change. Also regenerate the token you previously shared, since it is exposed.

Xiaolung

Bot is active now?

Kodari AI
KodariSep 10 at 5:49 pm 1

I can’t see whether your bot process is currently running from here. Check the terminal or hosting console:

Plain Text
Logged in as YourBotName
Bot is ready!

If it shows that, the bot is active. In Discord, test:

Plain Text
/progress
/leaderboard

Then send a normal message to earn XP. If slash commands do not appear, restart the bot and confirm DEV_GUILD_ID is set correctly in .env.

Also, regenerate the token you posted earlier before running the bot.

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

import logging
import math
import os
import random
import sqlite3
import time
from typing import Optional

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


load_dotenv()

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


class LevelDatabase:
    """Small SQLite persistence layer for per-server level profiles."""

    def __init__(self, path: str) -> None:
        self.connection = sqlite3.connect(path)
        self.connection.row_factory = sqlite3.Row
        self.connection.execute("PRAGMA journal_mode=WAL")
        self.connection.execute(
            """
            CREATE TABLE IF NOT EXISTS profiles (
                guild_id INTEGER NOT NULL,
                user_id INTEGER NOT NULL,
                xp INTEGER NOT NULL DEFAULT 0,
                level INTEGER NOT NULL DEFAULT 0,
                messages INTEGER NOT NULL DEFAULT 0,
                PRIMARY KEY (guild_id, user_id)
            )
            """
        )
        self.connection.execute(
            """
            CREATE INDEX IF NOT EXISTS profiles_leaderboard
            ON profiles (guild_id, level DESC, xp DESC)
            """
        )
        self.connection.commit()

    @staticmethod
    def required_xp_for_level(level: int) -> int:
        """Return total XP required to reach a level.

        The square progression makes each level require more XP than the
        previous one: level 1 requires 100 total XP, level 2 requires 400,
        level 3 requires 900, and so on.
        """
        return 100 * level * level

    @classmethod
    def level_for_xp(cls, xp: int) -> int:
        level = max(0, int(math.sqrt(xp / 100)))
        while cls.required_xp_for_level(level + 1) <= xp:
            level += 1
        while level > 0 and cls.required_xp_for_level(level) > xp:
            level -= 1
        return level

    def get_profile(self, guild_id: int, user_id: int) -> sqlite3.Row:
        self.connection.execute(
            "INSERT OR IGNORE INTO profiles (guild_id, user_id) VALUES (?, ?)",
            (guild_id, user_id),
        )
        self.connection.commit()
        profile = self.connection.execute(
            "SELECT guild_id, user_id, xp, level, messages FROM profiles "
            "WHERE guild_id = ? AND user_id = ?",
            (guild_id, user_id),
        ).fetchone()
        if profile is None:
            raise RuntimeError("Could not load the user's level profile")
        return profile

    def add_xp(self, guild_id: int, user_id: int, amount: int) -> tuple[sqlite3.Row, int]:
        profile = self.get_profile(guild_id, user_id)
        old_level = profile["level"]
        new_xp = profile["xp"] + amount
        new_level = self.level_for_xp(new_xp)
        self.connection.execute(
            "UPDATE profiles SET xp = ?, level = ?, messages = messages + 1 "
            "WHERE guild_id = ? AND user_id = ?",
            (new_xp, new_level, guild_id, user_id),
        )
        self.connection.commit()
        return self.get_profile(guild_id, user_id), old_level

    def get_leaderboard(self, guild_id: int, limit: int = 10) -> list[sqlite3.Row]:
        return list(
            self.connection.execute(
                "SELECT user_id, xp, level, messages FROM profiles "
                "WHERE guild_id = ? AND xp > 0 "
                "ORDER BY level DESC, xp DESC LIMIT ?",
                (guild_id, limit),
            ).fetchall()
        )

    def close(self) -> None:
        self.connection.close()


class LevelBot(commands.Bot):
    XP_MESSAGES = (
        "Your consistency is paying off!",
        "Another milestone unlocked! Keep going!",
        "The server noticed your dedication!",
        "You are climbing the ranks beautifully!",
        "That level-up was well earned!",
    )

    def __init__(self) -> None:
        intents = discord.Intents.default()
        intents.guild_messages = True
        intents.message_content = True
        super().__init__(command_prefix="!", intents=intents)
        self.database = LevelDatabase(os.getenv("DATABASE_PATH", "levels.db"))
        self.message_cooldowns: dict[tuple[int, int], float] = {}

    async def setup_hook(self) -> None:
        development_guild = os.getenv("DEV_GUILD_ID")
        if development_guild:
            guild = discord.Object(id=int(development_guild))
            self.tree.copy_global_to(guild=guild)
            await self.tree.sync(guild=guild)
            logger.info("Slash commands synced to development guild %s", development_guild)
        else:
            await self.tree.sync()
            logger.info("Global slash commands synced")

    async def on_ready(self) -> None:
        if self.user is not None:
            logger.info("Logged in as %s (%s)", self.user, self.user.id)

    async def on_message(self, message: discord.Message) -> None:
        await self.process_commands(message)

        if message.author.bot or message.guild is None:
            return

        cooldown_seconds = int(os.getenv("XP_COOLDOWN_SECONDS", "60"))
        cooldown_key = (message.guild.id, message.author.id)
        now = time.monotonic()
        last_award = self.message_cooldowns.get(cooldown_key, 0.0)

        if now - last_award < cooldown_seconds:
            return

        self.message_cooldowns[cooldown_key] = now
        xp_amount = random.randint(15, 25)
        profile, old_level = self.database.add_xp(
            message.guild.id,
            message.author.id,
            xp_amount,
        )

        if profile["level"] > old_level:
            await self.send_level_up_dm(message.author, profile)

    async def send_level_up_dm(self, user: discord.User, profile: sqlite3.Row) -> None:
        level = profile["level"]
        next_level_xp = self.database.required_xp_for_level(level + 1)
        embed = discord.Embed(
            title="Congratulations on your level up!",
            description=(
                f"{random.choice(self.XP_MESSAGES)}\n\n"
                f"You reached **Level {level}**!"
            ),
            color=discord.Color.blurple(),
        )
        embed.add_field(name="Total XP", value=f"{profile['xp']:,}")
        embed.add_field(name="XP for next level", value=f"{next_level_xp:,}")
        embed.set_footer(text="Keep chatting to reach the next milestone.")

        try:
            await user.send(embed=embed)
        except discord.Forbidden:
            logger.info("Could not DM level-up notification to %s", user.id)
        except discord.HTTPException:
            logger.exception("Discord rejected the level-up DM for %s", user.id)

    async def close(self) -> None:
        self.database.close()
        await super().close()


bot = LevelBot()