Kallum Harlow

create a bot for this roblox roleplay game named ERLC its a department bot the departments name is Natinal Highways the commands I want are listed below: ban kick timeout infraction issue infraction revoke promotion issue and promotion revoke the bot token is <redacted>

Kodari AI
KodariSep 7 at 5:27 pm 1
NationalHighwaysModBot
A Discord moderation bot for the ERLC Roblox roleplay game, serving the National Highways department. Features slash commands for banning, kicking, timing out users, issuing and revoking infractions, and managing promotions. Includes role-based permissions, logging of all moderation actions to a designated channel, and a simple database for tracking infraction history and promotion records.
  1. Create a secure discord.py slash-command bot with department moderation and promotion workflows.

  2. Add SQLite persistence for infractions and promotion audit records.

  3. Add environment-based configuration, dependency setup, and deployment instructions without storing the exposed token.

  1. Created the National Highways Discord bot with slash commands:

    • /ban

    • /kick

    • /timeout

    • /infraction issue

    • /infraction revoke

    • /promotion issue

    • /promotion revoke

  2. Added SQLite persistence for infraction and promotion records.

  3. Added permission checks, cooldowns, role hierarchy protection, ephemeral responses, logging, and error handling.

  4. Added .env configuration through .env.example, dependency setup, .gitignore, and deployment instructions.

  5. The token provided was exposed in chat. Revoke it immediately in the Discord Developer Portal and generate a new token before running the bot.

Kallum Harlow

it keeps on stopping

Kodari AI
KodariSep 7 at 5:33 pm 1
  1. Make startup failures explicit instead of letting the process exit with little context.

  2. Log gateway disconnects/reconnects so temporary Discord connection drops are distinguishable from crashes.

  3. Add a troubleshooting section for the common causes: missing .env, revoked token, permissions, and hosting process shutdown.

  1. Added clearer startup error messages for missing or invalid tokens.

  2. Added disconnect/reconnect logging so temporary Discord outages are visible.

  3. Added exception handling for token errors, privileged intents, unexpected crashes, and manual shutdowns.

  4. Added troubleshooting instructions to README.md.

Most likely cause: the token you originally provided was exposed and Discord may have invalidated it. Generate a new token in the Discord Developer Portal, then put it in .env:

Env
DISCORD_TOKEN=your_new_token_here

Start it from a terminal:

Shell
python main.py

Keep the terminal open and send me the exact error message it prints if it still stops.

Kallum Harlow

Bot failed: No Discord token found. Make sure your bot has a .env file with DISCORD_TOKEN

Kodari AI
KodariSep 7 at 5:36 pm 1

That message means the bot cannot find DISCORD_TOKEN.

  1. Reset the exposed token in the Discord Developer Portal.

  2. Create a file named exactly .env in the same folder as main.py.

  3. Add this line using the new token:

Env
DISCORD_TOKEN=your_new_discord_bot_token

Do not include backticks or use the old token.

Make sure the file is not accidentally named .env.txt. On Windows, enable View → File name extensions to check.

Install the required package if needed:

Shell
pip install -r requirements.txt

Then run the bot from the project folder:

Shell
python main.py

If you are hosting it on a platform such as Replit, Render, or Railway, add DISCORD_TOKEN in that platform’s Secrets/Environment Variables section instead of creating .env.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
database.py
main.py
README.md
requirements.txt
Code
5 683
main.py
from __future__ import annotations

import logging
import os
from datetime import datetime, timedelta, timezone

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

from database import Database


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


async def respond(
    interaction: discord.Interaction,
    content: str | None = None,
    embed: discord.Embed | None = None,
) -> None:
    payload: dict[str, object] = {"content": content, "embed": embed, "ephemeral": True}
    if interaction.response.is_done():
        await interaction.followup.send(**payload)
    else:
        await interaction.response.send_message(**payload)


def guild_from(interaction: discord.Interaction) -> discord.Guild | None:
    return interaction.guild


def can_act_on_member(interaction: discord.Interaction, member: discord.Member) -> str | None:
    guild = guild_from(interaction)
    actor = interaction.user
    if guild is None or not isinstance(actor, discord.Member):
        return "This command can only be used inside a server."
    if member == actor:
        return "You cannot use this action on yourself."
    if member == guild.owner:
        return "The server owner cannot be targeted by this bot."
    if actor.id != guild.owner_id and member.top_role >= actor.top_role:
        return "You can only target members below your highest role."
    if guild.me is None or member.top_role >= guild.me.top_role:
        return "That member is at or above the bot's highest role."
    return None


def can_manage_role(interaction: discord.Interaction, role: discord.Role) -> str | None:
    guild = guild_from(interaction)
    actor = interaction.user
    if guild is None or not isinstance(actor, discord.Member):
        return "This command can only be used inside a server."
    if role.is_default() or role.managed:
        return "That role cannot be assigned by the bot."
    if actor.id != guild.owner_id and role >= actor.top_role:
        return "You can only manage roles below your highest role."
    if guild.me is None or role >= guild.me.top_role:
        return "That role must be below the bot's highest role."
    return None


@app_commands.checks.has_permissions(ban_members=True)
@app_commands.checks.cooldown(1, 5.0, key=lambda interaction: (interaction.guild_id, interaction.user.id))
@app_commands.guild_only()
async def ban_member(
    interaction: discord.Interaction,
    member: discord.Member,
    reason: str = "No reason provided",
) -> None:
    problem = can_act_on_member(interaction, member)
    if problem:
        await respond(interaction, problem)
        return
    guild = interaction.guild
    assert guild is not None
    try:
        await guild.ban(member, reason=f"Ban by {interaction.user}: {reason}")
    except discord.HTTPException:
        logger.exception("Failed to ban member %s in guild %s", member.id, guild.id)
        await respond(interaction, "Discord rejected the ban. Check the bot's permissions and role hierarchy.")
        return
    await respond(interaction, f"Banned {member.mention}. Reason: {reason}")


@app_commands.checks.has_permissions(kick_members=True)
@app_commands.checks.cooldown(1, 5.0, key=lambda interaction: (interaction.guild_id, interaction.user.id))
@app_commands.guild_only()
async def kick_member(
    interaction: discord.Interaction,
    member: discord.Member,
    reason: str = "No reason provided",
) -> None:
    problem = can_act_on_member(interaction, member)
    if problem:
        await respond(interaction, problem)
        return
    guild = interaction.guild
    assert guild is not None
    try:
        await member.kick(reason=f"Kick by {interaction.user}: {reason}")
    except discord.HTTPException:
        logger.exception("Failed to kick member %s in guild %s", member.id, guild.id)
        await respond(interaction, "Discord rejected the kick. Check the bot's permissions and role hierarchy.")
        return
    await respond(interaction, f"Kicked {member.mention}. Reason: {reason}")


@app_commands.checks.has_permissions(moderate_members=True)
@app_commands.checks.cooldown(1, 5.0, key=lambda interaction: (interaction.guild_id, interaction.user.id))
@app_commands.guild_only()
@app_commands.describe(duration_minutes="Timeout length in minutes, from 1 to 40320")
async def timeout_member(
    interaction: discord.Interaction,
    member: discord.Member,
    duration_minutes: app_commands.Range[int, 1, 40320],
    reason: str = "No reason provided",
) -> None:
    problem = can_act_on_member(interaction, member)
    if problem:
        await respond(interaction, problem)
        return
    guild = interaction.guild
    assert guild is not None
    until = discord.utils.utcnow() + timedelta(minutes=duration_minutes)
    try:
        await member.timeout(until, reason=f"Timeout by {interaction.user}: {reason}")
    except discord.HTTPException:
        logger.exception("Failed to timeout member %s in guild %s", member.id, guild.id)
        await respond(interaction, "Discord rejected the timeout. Check the bot's permissions and role hierarchy.")
        return
    await respond(
        interaction,
        f"Timed out {member.mention} for {duration_minutes} minutes. Reason: {reason}",
    )


ban_command = app_commands.Command(name="ban", description="Ban a member from the server", callback=ban_member)
kick_command = app_commands.Command(name="kick", description="Kick a member from the server", callback=kick_member)
timeout_command = app_commands.Command(
    name="timeout",
    description="Timeout a member",
    callback=timeout_member,
)


def moderation_embed(title: str, color: discord.Color) -> discord.Embed:
    embed = discord.Embed(title=title, color=color, timestamp=datetime.now(timezone.utc))
    embed.set_footer(text="National Highways Department")
    return embed


class InfractionGroup(app_commands.Group):
    def __init__(self, database: Database) -> None:
        super().__init__(name="infraction", description="Manage department infractions")
        self.database = database

    @app_commands.command(name="issue", description="Issue an infraction to a member")
    @app_commands.guild_only()
    @app_commands.checks.has_permissions(manage_messages=True)
    @app_commands.checks.cooldown(1, 5.0, key=lambda interaction: (interaction.guild_id, interaction.user.id))
    @app_commands.describe(
        member="The member receiving the infraction",
        infraction_type="The type of infraction",
        severity="The severity of the infraction",
        reason="Why the infraction is being issued",
    )
    @app_commands.choices(
        infraction_type=[
            app_commands.Choice(name="Policy Violation", value="Policy Violation"),
            app_commands.Choice(name="Conduct", value="Conduct"),
            app_commands.Choice(name="Attendance", value="Attendance"),
            app_commands.Choice(name="Other", value="Other"),
        ],
        severity=[
            app_commands.Choice(name="Warning", value="Warning"),
            app_commands.Choice(name="Written Warning", value="Written Warning"),
            app_commands.Choice(name="Final Warning", value="Final Warning"),
        ],
    )
    async def issue(
        self,
        interaction: discord.Interaction,
        member: discord.Member,
        infraction_type: app_commands.Choice[str],
        severity: app_commands.Choice[str],
        reason: str,
    ) -> None:
        problem = can_act_on_member(interaction, member)
        if problem:
            await respond(interaction, problem)
            return
        guild = interaction.guild
        assert guild is not None
        infraction_id = self.database.create_infraction(