haski225831

You are an expert Discord bot developer. Generate the logic, command structure, and response templates for a Discord military faction ranking and point management bot.

The bot must support the following core capabilities:

  1. PREFIX & NAME MANAGEMENT

- Support a configurable command prefix (default: !). - Command: !setprefix [New Prefix] -> Updates the server's bot prefix. - Command: !nick @User [Prefix/Tag] -> Updates a member's server nickname with their rank abbreviation or clan tag (e.g., "[PVT] John").

  1. RANK ROLE CREATION

- Command: !createrank [Rank Name] [Color Hex] -> Creates a new Discord role automatically with standard member permissions and places it in the server role hierarchy.

  1. POINT TRACKING SYSTEM

- Command: !addpoints @User [Amount] [Reason] -> Adds merit/operation points to a member's database profile and logs the action. - Command: !deductpoints @User [Amount] [Reason] -> Removes points from a member's profile for disciplinary reasons or strikes. - Command: !points @User -> Displays the current point balance and rank status of the target member.

  1. PROMOTION & DEMOTION SYSTEM

- Command: !promote @User [New Rank Role] -> Removes the previous rank role, assigns the new rank role, updates their server nickname prefix, and posts a formatted promotion embed in the designated logging channel. - Command: !demote @User [New Rank Role] [Reason] -> Removes the current rank role, assigns the lower rank role, updates their server nickname prefix, and logs the demotion with an official notice.

REQUIREMENTS & SECURITY:

  • Only users with Administrator or designated Officer roles can execute !addpoints, !deductpoints, !createrank, !promote, and !demote.
  • All promotion, demotion, and point actions must output structured, professional embeds featuring the target user, acting officer, reason, and updated status.
  • Provide step-by-step setup instructions for hosting or configuring this bot logic. And also add a command that registers a role as a rank
Kodari AI
KodariOct 8 at 12:26 am 1
MilitaryRankBot
Discord bot managing military faction ranks and points. Supports configurable command prefix, nickname tagging with rank abbreviations, automatic rank role creation via !createrank, point tracking with !addpoints/!deductpoints/!points, and promotion/demotion workflows via !promote/!demote. Enforces officer-only permissions, logs all actions as structured embeds, and includes !registerrank to designate roles as ranks. Provides setup instructions for hosting and configuration.
  1. Build the prefix-command bot with persistent SQLite settings, point profiles, rank registration, and audit logs.

  2. Add permission checks, rank/nickname management, embeds, and command error handling.

  3. Add dependencies, an environment template, and step-by-step setup instructions.

Created the Discord.py faction bot with persistent per-server prefixes, rank registration and creation, nickname tags, point balances, promotions/demotions, and structured audit embeds. Point deductions are guarded against concurrent commands taking a balance below zero.

Configure DISCORD_TOKEN in .env (or as a Kodari project secret), then use !setofficer @Role and !setlogchannel #channel to set up officer access and action logs. See README.md for setup and command usage.

Enable Message Content Intent on the app’s Bot page in the Discord Developer Portal; prefix commands require it.

haski225831

How to set up bot

Kodari AI
KodariOct 8 at 1:01 am 1

Set up the bot

  1. Create the Discord bot

    • In the Discord Developer Portal, create an application, open its Bot page, and create the bot.

    • Copy its token. Keep it secret.

    • Under Privileged Gateway Intents, enable Message Content Intent. Prefix commands won’t work without it.

  2. Invite it to your server

    • In OAuth2 → URL Generator, select the bot scope and grant View Channels, Send Messages, Embed Links, Manage Roles, and Manage Nicknames.

    • Use the generated URL to invite the bot.

    • In your server’s Server Settings → Roles, move the bot’s role above the rank roles it needs to assign and above members whose nicknames it needs to change.

  3. Deploy on Kodari

    • Add DISCORD_TOKEN as a project secret with the token you copied.

    • Deploy the bot project. Its database (bot.db) stores server settings, registered roles, points, and action records.

  4. Configure it in your server
    As an administrator, run:

    Plain Text
    !setofficer @OfficerRole
    !setlogchannel #action-logs
    

    Repeat !setofficer for each officer role. To track existing rank roles, register each one:

    Plain Text
    !registerrank @RankRole
    
  5. Start using it

    Plain Text
    !createrank Private #5263A4
    !addpoints @Member 10 Completed operation
    !points @Member
    !promote @Member @RankRole Promotion reason
    !demote @Member @LowerRankRole Demotion reason
    !nick @Member PVT
    !setprefix ?
    

    !createrank expects the color as the final argument. After changing the prefix, use the new prefix for commands.

haski225831

Can u make it slash commands too

Kodari AI
KodariOct 8 at 1:19 am 1
  • Add slash-command equivalents for the existing prefix commands, including officer checks and rank/points workflows.

  • Sync the application commands at startup and return clear ephemeral errors for slash-command failures.

Added slash-command versions of the bot’s setup, nickname, rank, points, promotion, and demotion commands. They sync automatically when the bot starts; Discord may take a little while to show globally synced commands. Prefix commands still work too.

haski225831

How do I deploy my bot in kodari

Kodari AI
KodariOct 8 at 1:21 am 1

To deploy the bot on Kodari:

  1. In the Discord Developer Portal, open your application’s Bot page and enable Message Content Intent so prefix commands work. Copy the bot token—don’t share or post it.

  2. In your Kodari bot project, add DISCORD_TOKEN as a project secret and paste in the token.

  3. Make sure requirements.txt includes the bot’s dependencies, then deploy or start the project in Kodari. The bot should come online and print KODARI_READY.

  4. Invite the bot to your server with permissions to view channels, send messages, embed links, manage roles, and manage nicknames. Put its role above the rank roles it needs to assign.

  5. In your server, configure officers and the log channel using the bot’s setup commands. Slash commands sync when the bot starts; if they don’t appear right away, give Discord a little time.

Kodari keeps the bot running while it’s hosted.

haski225831

Simplify it

Kodari AI
KodariOct 8 at 1:27 am 1
  1. Add your Discord bot token as the DISCORD_TOKEN secret in Kodari.

  2. Deploy the project.

  3. Invite the bot to your server. Enable Message Content Intent in the Developer Portal if you want to use prefix commands.

haski225831

<redacted>

Kodari AI
KodariOct 8 at 1:29 am 1

That looks like a Discord bot token. Treat it as compromised and reset it now in Discord Developer Portal → your app → Bot → Reset Token. Then update Kodari’s DISCORD_TOKEN secret with the new token and redeploy. Don’t post the new token here.

haski225831

Wheres discord_token

Kodari AI
KodariOct 8 at 1:30 am 1

In your Kodari bot project, open Secrets/Environment Variables and add:

  • Name: DISCORD_TOKEN

  • Value: your newly reset Discord bot token

Save it, then redeploy the bot. Don’t reuse the token you posted—reset it in the Discord Developer Portal first.

haski225831

Wheres is that guide me

Kodari AI
KodariOct 8 at 1:37 am 1

Open your bot project in Kodari, then go to Files. Create a file named .env next to bot.py and add:

Env
DISCORD_TOKEN=your_new_token

Save it, then start or redeploy the bot. Reset the token you posted before using it—that one is exposed.

haski225831

How to deploy the bot

Kodari AI
KodariOct 8 at 1:51 am 1
  1. Open your bot project in Kodari.

  2. Add your new token as the DISCORD_TOKEN secret (or in .env beside bot.py).

  3. Click Deploy or Run to start the bot.

Keep the bot running in Kodari, and don’t share the token.

haski225831

Where is the deploy or run button

Kodari AI
KodariOct 8 at 1:59 am 1

I can’t see your Kodari screen, so I can’t point to the exact button. Open your bot project and look in the top toolbar for Run or Deploy. If you don’t see either, send a screenshot of the project page and I’ll guide you.

Kodari can make mistakes. Review important code before using.
Files
.
.gitignore
bot.py
README.md
requirements.txt
Code
5 853
bot.py
import logging
import os
import re
from datetime import datetime, timezone

import aiosqlite
import discord
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("faction_bot")

DATABASE_PATH = "bot.db"
DEFAULT_PREFIX = "!"
database: aiosqlite.Connection | None = None

intents = discord.Intents.default()
intents.message_content = True


async def initialize_database() -> None:
    global database
    database = await aiosqlite.connect(DATABASE_PATH)
    await database.executescript(
        """
        CREATE TABLE IF NOT EXISTS guild_config (
            guild_id INTEGER PRIMARY KEY,
            prefix TEXT NOT NULL DEFAULT '!',
            log_channel_id INTEGER
        );
        CREATE TABLE IF NOT EXISTS officer_roles (
            guild_id INTEGER NOT NULL,
            role_id INTEGER NOT NULL,
            PRIMARY KEY (guild_id, role_id)
        );
        CREATE TABLE IF NOT EXISTS rank_roles (
            guild_id INTEGER NOT NULL,
            role_id INTEGER NOT NULL,
            PRIMARY KEY (guild_id, role_id)
        );
        CREATE TABLE IF NOT EXISTS points (
            guild_id INTEGER NOT NULL,
            user_id INTEGER NOT NULL,
            balance INTEGER NOT NULL DEFAULT 0,
            PRIMARY KEY (guild_id, user_id)
        );
        CREATE TABLE IF NOT EXISTS action_log (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            guild_id INTEGER NOT NULL,
            action TEXT NOT NULL,
            target_id INTEGER NOT NULL,
            actor_id INTEGER NOT NULL,
            reason TEXT NOT NULL,
            status TEXT NOT NULL,
            created_at TEXT NOT NULL
        );
        """
    )
    await database.commit()


async def current_prefix(bot: commands.Bot, message: discord.Message) -> str:
    if message.guild is None or database is None:
        return DEFAULT_PREFIX
    cursor = await database.execute(
        "SELECT prefix FROM guild_config WHERE guild_id = ?", (message.guild.id,)
    )
    row = await cursor.fetchone()
    await cursor.close()
    return row[0] if row else DEFAULT_PREFIX


bot = commands.Bot(command_prefix=current_prefix, intents=intents)


@bot.event
async def setup_hook() -> None:
    await initialize_database()
    await bot.tree.sync()


@bot.event
async def on_ready() -> None:
    logger.info("Bot ready as %s", bot.user)
    print("KODARI_READY", flush=True)


async def fetch_prefix(guild_id: int) -> str:
    cursor = await database.execute(
        "SELECT prefix FROM guild_config WHERE guild_id = ?", (guild_id,)
    )
    row = await cursor.fetchone()
    await cursor.close()
    return row[0] if row else DEFAULT_PREFIX


async def require_officer(ctx: commands.Context) -> bool:
    if ctx.guild is None or not isinstance(ctx.author, discord.Member):
        return False
    if ctx.author.guild_permissions.administrator:
        return True
    cursor = await database.execute(
        "SELECT role_id FROM officer_roles WHERE guild_id = ?", (ctx.guild.id,)
    )
    rows = await cursor.fetchall()
    await cursor.close()
    officer_ids = {row[0] for row in rows}
    return any(role.id in officer_ids for role in ctx.author.roles)


def rank_name_from_role(role: discord.Role) -> str:
    return role.name


async def registered_rank_roles(guild: discord.Guild) -> list[discord.Role]:
    cursor = await database.execute(
        "SELECT role_id FROM rank_roles WHERE guild_id = ?", (guild.id,)
    )
    rows = await cursor.fetchall()
    await cursor.close()
    return [role for row in rows if (role := guild.get_role(row[0])) is not None]


async def member_rank_status(member: discord.Member) -> str:
    ranks = await registered_rank_roles(member.guild)
    current = [role.name for role in ranks if role in member.roles]
    return ", ".join(current) if current else "Unranked"


def formatted_nickname(member: discord.Member, tag: str) -> str:
    base_name = re.sub(r"^\[[^\]]+\]\s*", "", member.display_name).strip()
    if not base_name:
        base_name = member.name
    clean_tag = tag.strip()
    if not (clean_tag.startswith("[") and clean_tag.endswith("]")):
        clean_tag = f"[{clean_tag.strip('[] ')}]"
    return f"{clean_tag} {base_name}"[:32]


def action_embed(
    title: str,
    color: discord.Color,
    target: discord.Member,
    actor: discord.Member,
    reason: str,
    status_label: str,
    status: str,
) -> discord.Embed:
    embed = discord.Embed(title=title, color=color, timestamp=datetime.now(timezone.utc))
    embed.add_field(
        name="Target",
        value=f"{target.mention} ({target} · `{target.id}`)",
        inline=False,
    )
    embed.add_field(name="Acting Officer", value=f"{actor.mention} ({actor})", inline=True)
    embed.add_field(name=status_label, value=status, inline=True)
    embed.add_field(name="Reason", value=reason, inline=False)
    return embed


async def record_and_log(
    guild: discord.Guild,
    action: str,
    target: discord.Member,
    actor: discord.Member,
    reason: str,
    status: str,
    embed: discord.Embed,
) -> None:
    await database.execute(
        """INSERT INTO action_log
           (guild_id, action, target_id, actor_id, reason, status, created_at)
           VALUES (?, ?, ?, ?, ?, ?, ?)""",
        (
            guild.id,
            action,
            target.id,
            actor.id,
            reason,
            status,
            datetime.now(timezone.utc).isoformat(),
        ),
    )
    await database.commit()

    cursor = await database.execute(
        "SELECT log_channel_id FROM guild_config WHERE guild_id = ?", (guild.id,)
    )
    row = await cursor.fetchone()
    await cursor.close()
    if row and row[0]:
        channel = guild.get_channel(row[0])
        if channel is not None and hasattr(channel, "send"):
            try: