liltecko
📎 1 file 13,885 chars
📄
pasted-code-1793236158731.txt
txt 1 lines
▶
 D99 PD — 1012 Ride-Along Management Discord Bot  Build a fully functional Discord bot for the D99 Police Department (D99 PD) to manage, track, and log all 1012 ride-along sessions automatically.  The goal is to eliminate manual ride-along logging and hour calculations. The bot must have a clean, professional interface using Discord embeds, buttons, slash commands, and dropdown menus where appropriate.  1. Officer Identification  Automatically identify officers using their Discord server nickname.  The mandatory nickname format is:  Rank | Name | ID  Example: Captain | John Smith | 1042  Parse the nickname as follows:  * Rank: Text before the first |. * Name: Text between the first and second |. * ID: Text after the second |.  Implementation requirements:  1. Automatically extract the rank, full name, and PD ID from the member’s current server-specific Discord nickname. 2. Remove unnecessary spaces around each field. 3. Treat the PD ID as a string, not an integer, to preserve leading zeros. 4. Validate that all three fields are present and non-empty. 5. If the nickname does not follow the expected format, notify the user and prevent the ride-along from starting until their details are corrected or an authorized administrator registers them. 6. Use the member’s unique Discord user ID internally to identify their Discord account. 7. Retrieve the supervisor’s information and every participating officer’s information automatically. Users should not need to enter their names, IDs, or ranks manually. 8. Save a snapshot of each officer’s name, rank, and PD ID when the session starts. Later nickname or rank changes must not modify historical records. 9. Use the same parsing and validation logic for supervisors and participants. 10. Never guess an officer’s identity or extract their rank, name, or PD ID from their Discord username if their server nickname is invalid.  If an officer changes their nickname or rank, the bot should use their latest valid details for new sessions while preserving the original details in previous records.  2. Starting a 1012 Ride-Along  Create a /1012 start slash command.  When a supervisor uses it:  1. Automatically identify the supervising officer, including their name, PD ID, and rank, using the Rank | Name | ID nickname format. 2. Allow them to select or mention multiple officers participating in the ride-along. 3. Retrieve each participant’s name, ID, and rank automatically from their Discord server nickname. 4. Validate the nickname of every participant before proceeding. 5. Display a confirmation embed listing the supervisor and all participating officers. 6. Provide a Start button to confirm and begin the session. 7. Record the exact start date and time using a consistent timezone configured by the server. 8. Start an individual timer for every participating officer only when the Start button is pressed.  A single supervisor must be able to manage multiple participating officers in the same session.  Only authorized officers should be permitted to start ride-alongs, based on configurable Discord roles or PD ranks.  Prevent a session from starting if any selected participant has an invalid nickname, is already participating in an active session, or otherwise fails the configured validation rules.  3. Individual Officer Timer Controls  This is one of the most important features.  Every participant must have an independent timer, even when several officers are part of the same ride-along session.  For each participant, provide these controls:  * Pause: Temporarily stop counting time for that officer. * Resume: Continue counting time for that officer. * Stop Officer: Permanently end that officer’s participation and finalize their logged time. * View Time: Display the officer’s accumulated time in the current session.  Pausing, resuming, or stopping one officer must NEVER affect the timers of other participants.  For example, if three officers are participating and one needs to leave, the supervisor must be able to stop that officer while the other two continue their ride-along.  A paused officer must not accumulate any additional time until resumed.  The bot must retain all time accumulated before a pause. Resuming must continue from the existing total rather than resetting the timer.  When an officer is stopped, their participation must be marked as completed, and their final duration must be saved. Their timer must not restart accidentally.  4. End the Entire Ride-Along  Provide an End Session button that ends the overall session.  When pressed:  1. Stop all remaining active participant timers. 2. Finalize the time for every participant who has not already been stopped. 3. Preserve the time accumulated by participants who were paused or stopped earlier. 4. Record the session end timestamp. 5. Save all finalized records to the database. 6. Display a summary embed containing the supervisor’s details, session timestamps, each participant’s details, and their individual total active time.  Officers who were individually stopped earlier must retain their finalized records and must not receive duplicate time when the overall session ends.  For officers who are paused when the session ends, finalize their existing accumulated active time without counting the paused period.  Once a session has ended, its timers and records must be locked against ordinary changes. Any authorized correction must be handled through an administrative process and recorded in the audit log.  5. Total Ride-Along Hours  Create a /1012 lookup command that allows authorized users to search for an officer by PD ID.  The result must display:  * Officer’s name, ID, and current rank. * Total accumulated ride-along time across all completed and ongoing sessions. * Total number of ride-along sessions. * Total hours and minutes in an easy-to-read format. * A breakdown of completed sessions, including supervisor, date, start time, end time, and duration.  Example output:  Officer: John Smith PD ID: 2051 Rank: Officer Total Ride-Along Time: 27 hours, 45 minutes Completed Sessions: 8  The numbers above are illustrative only.  Time from an ongoing session should reflect the officer’s current active time, excluding any paused periods.  If the officer’s rank or nickname has changed, display their current registered details while retaining the historical details in the individual session records.  Handle officers with no previous ride-alongs by displaying a clear message and a total of zero hours.  6. Additional Commands  Implement the following commands:  * /1012 start — Start a new ride-along session. * /1012 status — View active sessions and each participant’s current status. * /1012 lookup [ID] — Search for an officer’s total ride-along hours. * /1012 history [ID] — View an officer’s previous ride-along records. * /1012 leaderboard — Display a leaderboard of officers ranked by total accumulated ride-along time. * /1012 register — Allow authorized administrators to register or correct officer details. * /1012 help — Display instructions for using the bot.  Use autocomplete or a dropdown for officer selection whenever practical.  The /1012 history command should display previous sessions with dates, supervisors, durations, and session status. Support pagination when there are too many records to display in one Discord message.  The leaderboard must calculate totals from the database rather than relying on manually maintained values.  7. Database and Recordkeeping  Use a persistent database, preferably SQLite for a small deployment or PostgreSQL for an online production deployment.  Store the following information.  For each officer  * Discord user ID. * Full name. * PD ID. * Rank. * Registration details. * Current registered information. * Registration or update timestamps.  For each ride-along session  * Unique session ID. * Supervisor’s Discord ID, name, PD ID, and rank at the time of the session. * Start and end timestamps. * Session status. * Date of creation.  For each participating officer  * Discord user ID, name, PD ID, and rank at the time of the session. * Individual start timestamp. * Individual stop timestamp, if applicable. * All pause and resume timestamps. * Total accumulated active duration. * Final status: Active, Paused, or Completed.  Keep historical snapshots of officer names, IDs, and ranks so that future nickname changes do not alter previous records.  Never delete historical ride-along records when an officer changes rank or nickname.  Ensure that each session and each participant’s record has a unique identifier to prevent duplicate entries.  8. Accurate Time Calculations and Reliability  Do not rely on an in-memory countdown timer as the source of truth.  Calculate durations using stored timestamps and pause intervals. Store timestamps consistently, preferably in UTC, and display them in the server’s configured timezone.  The bot must:  * Preserve active sessions through bot restarts. * Restore the correct status and timers after reconnecting. * Prevent duplicate active sessions for the same officer unless an authorized administrator explicitly permits an exception. * Prevent accidental double-clicks from creating duplicate actions or records. * Ensure that pausing, resuming, and stopping are handled transactionally. * Calculate total time accurately across multiple sessions. * Never count paused time. * Avoid double-counting overlapping periods. * Maintain accurate time when the bot goes offline and returns. * Prevent a participant from accumulating time from overlapping sessions. * Ensure that a completed session cannot accidentally be reopened by pressing an old button.  If the bot goes offline during an active session, calculate elapsed time correctly when it returns using the recorded timestamps. Do not automatically treat downtime as paused time unless an explicit, documented recovery policy requires it.  Use persistent timestamps and pause intervals to calculate actual active duration.  9. Discord Interface and Permissions  Create a professional D99 PD-themed interface using Discord embeds, buttons, dropdowns, and ephemeral responses where appropriate.  The active session panel should display:  * Session ID. * Supervisor information. * Session start time. * Participating officers. * Each officer’s current status. * Each officer’s accumulated time. * Individual control buttons. * An End Session button.  Display clear status indicators for:  * Active. * Paused. * Completed.  Only the session’s authorized supervisor and designated administrators should be able to control that session. Configure permission overrides for exceptional cases.  Use Discord role-based permissions for administrative commands, officer registration, manual corrections, and record access.  Prevent unauthorized users from changing timers, editing records, or viewing restricted information.  Log administrative changes, manual adjustments, session cancellations, and exceptional actions in a designated audit channel.  Ensure that interaction buttons verify permissions on the server side. Hiding a button from unauthorized users is not sufficient security.  The bot should respond appropriately when a button is pressed by someone who does not have permission.  10. Error Handling and Validation  Handle the following situations gracefully:  * Invalid or unregistered officer IDs. * Incorrect nickname formats. * Missing rank, name, or PD ID fields. * Unauthorized command usage. * Attempting to pause an already paused officer. * Attempting to resume an active officer. * Attempting to stop an officer who has already completed their session. * Attempting to end an already completed session. * Attempting to start a second active session for an officer. * Bot restarts during an active session. * Discord API errors and missing permissions. * Database errors or failed record updates. * Expired or outdated Discord interaction buttons.  Display clear, useful error messages rather than failing silently.  If an operation fails, do not partially update the session or lose previously recorded time.  11. Implementation Requirements  Build the actual working bot, not just a mockup or a design demonstration.  Use a stable Discord bot framework, such as Python with discord.py, or an equivalent reliable framework supported by the generator.  Include:  * Complete source code. * Database schema and initialization. * Environment-variable configuration for the Discord bot token. * Setup instructions. * Deployment instructions. * Required Discord intents and permissions. * Instructions for configuring roles, nickname format, timezone, and audit channel. * A README explaining every command. * Tests for individual timers, pause/resume calculations, session finalization, persistence, nickname parsing, permissions, and duplicate prevention.  Never hardcode the Discord bot token into source code.  Prioritize accurate timekeeping, individual officer controls, persistent records, and permission security over unnecessary features.  The final result must be a deployable, fully functional D99 PD 1012 ride-along management bot.  12. Development Priority  Implement the project in this order:  1. Nickname parsing and officer identification using Rank | Name | ID. 2. Persistent database and officer registration. 3. Session creation and individual timer logic. 4. Pause, resume, individual stop, and end-session controls. 5. Automatic total-hour calculations, lookup, history, and leaderboard. 6. Discord interface, role permissions, and audit logging. 7. Restart recovery, error handling, and automated tests.  Do not mark the project as complete until the actual commands, database operations, and individual timer controls work end to end.  If any configuration values are required, provide clear setup instructions and sensible defaults rather than leaving core functionality as a placeholder.
Kodari AI
KodariOct 29 at 1:15 am 3
  1. Inspect the existing bot scaffold and dependencies.

  2. Implement persistent ride-along tracking, identity validation, commands, controls, and recovery.

  3. Add setup documentation and tests for core timekeeping and validation.

Implemented the D99 PD ride-along bot with /1012 commands, nickname validation and admin registration, SQLite-backed individual timers, pause/resume/stop/end controls, record lookup and history, role checks, audit logging, and restart recovery.

Setup and permissions are documented in README.md; configure .env from .env.example before running python main.py. The bot uses no privileged Gateway intents. Tests are included in tests/test_core.py, but were not run here.

liltecko

Can we get a preview here

Kodari AI
KodariOct 29 at 1:17 am 1

Here’s a text mockup of how it would look in Discord:

Before the timer starts

Plain Text
┌ Confirm D99 PD 1012 Ride-Along
│ Supervisor: Captain | Jane Doe | 01001
│ Participants:
│ • Officer | Alex Smith | 01042
│ • Officer | Sam Lee | 01087
│
│ No timers begin until the supervisor presses Start Ride-Along.
└ [ Start Ride-Along ]

Active session panel

Plain Text
┌ D99 PD 1012 • ACTIVE
│ Session: 8a3f…
│ Supervisor: Captain | Jane Doe | 01001
│ Started: 2026-11-16 14:30:00 UTC
│
│ ACTIVE  Officer | Alex Smith | 01042 — 0h 12m 08s
│ ACTIVE  Officer | Sam Lee | 01087 — 0h 12m 08s
│
│ Select an officer, then choose an individual timer control.
└ [Choose an officer to control ▾]
  [Pause] [Resume] [Stop Officer] [View Time]
  [End Session]

The bot also provides /1012 status, /1012 lookup, /1012 history, /1012 leaderboard, /1012 register, and /1012 help.

Kodari can make mistakes. Review important code before using.
Files
tests
database.py
identity.py
main.py
pasted-code-1793236140530.txt
permissions.py
README.md
requirements.txt
Code
8 1,155
main.py
import logging
import os
import re
import uuid
from datetime import datetime, timezone
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError

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

from database import RideAlongDB, participant_seconds
from identity import OfficerIdentity, parse_nickname
from permissions import can_supervise, can_view_records, is_admin


load_dotenv()
logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"))
logger = logging.getLogger("d99_ridealong")


def env_ids(key: str) -> set[int]:
    values = set()
    for part in os.getenv(key, "").split(","):
        part = part.strip()
        if part:
            try:
                values.add(int(part))
            except ValueError:
                logger.warning("Ignoring invalid ID in %s: %s", key, part)
    return values


ADMIN_ROLE_IDS = env_ids("ADMIN_ROLE_IDS")
SUPERVISOR_ROLE_IDS = env_ids("SUPERVISOR_ROLE_IDS")
ADMIN_USER_IDS = env_ids("ADMIN_USER_IDS")
AUDIT_CHANNEL_ID = int(os.getenv("AUDIT_CHANNEL_ID", "0") or "0")
DATABASE_PATH = os.getenv("DATABASE_PATH", "ridealong.sqlite3")
try:
    DISPLAY_TIMEZONE = ZoneInfo(os.getenv("TIMEZONE", "UTC"))
except ZoneInfoNotFoundError:
    logger.warning("Invalid TIMEZONE; using UTC")
    DISPLAY_TIMEZONE = ZoneInfo("UTC")

db = RideAlongDB(DATABASE_PATH)
intents = discord.Intents.default()


def fmt_duration(seconds: int) -> str:
    hours, remainder = divmod(max(0, int(seconds)), 3600)
    minutes, seconds = divmod(remainder, 60)
    return f"{hours}h {minutes}m {seconds}s"


def fmt_datetime(value: str | None) -> str:
    if not value:
        return "—"
    parsed = datetime.fromisoformat(value)
    return parsed.astimezone(DISPLAY_TIMEZONE).strftime("%Y-%m-%d %H:%M:%S %Z")


def identity_label(identity: OfficerIdentity) -> str:
    return f"{identity.rank} | {identity.name} | {identity.pd_id}"


def is_admin_member(member) -> bool:
    return is_admin(member, ADMIN_ROLE_IDS, ADMIN_USER_IDS)


def can_control_session(member, details: dict) -> bool:
    return member.id == int(details["session"]["supervisor_discord_id"]) or is_admin_member(member)


def panel_embed(details: dict) -> discord.Embed:
    session = details["session"]
    active = session["status"] == "ACTIVE"
    embed = discord.Embed(
        title=f"D99 PD 1012 • {session['status']}",
        color=discord.Color.dark_blue() if active else discord.Color.gold(),
        description=(
            f"**Session:** `{session['id']}`\n"
            f"**Supervisor:** {session['supervisor_rank']} | {session['supervisor_name']} | {session['supervisor_pd_id']}\n"
            f"**Started:** {fmt_datetime(session['start_at'])}\n\n"
        ),
    )
    lines = []
    for participant in details["participants"]:
        duration = fmt_duration(participant_seconds(participant))
        line = (
            f"`{participant['status']}` **{participant['rank']} | {participant['name']} | "
            f"{participant['pd_id']}** — {duration}"
        )
        lines.append(line[:170])
    embed.description += "\n".join(lines) if lines else "No participants."
    if session["status"] == "COMPLETED":
        embed.add_field(name="Ended", value=fmt_datetime(session["end_at"]), inline=False)
    embed.set_footer(text="Select an officer, then choose an individual timer control.")
    return embed


def summary_embed(details: dict) -> discord.Embed:
    embed = panel_embed(details)
    embed.title = f"D99 PD 1012 • Session {details['session']['id']} finalized"
    embed.color = discord.Color.dark_green()
    embed.description += f"\n\n**Ended:** {fmt_datetime(details['session']['end_at'])}"
    return embed


async def audit(guild: discord.Guild | None, title: str, description: str) -> None:
    if not guild or not AUDIT_CHANNEL_ID:
        return
    channel = guild.get_channel(AUDIT_CHANNEL_ID)
    if channel is None:
        logger.warning("Audit channel %s is unavailable in guild %s", AUDIT_CHANNEL_ID, guild.id)
        return
    try:
        await channel.send(embed=discord.Embed(title=title, description=description, color=discord.Color.orange()))
    except discord.HTTPException:
        logger.exception("Failed to write audit event")


async def identify_member(member: discord.Member) -> OfficerIdentity:
    try:
        identity = parse_nickname(member.nick)
    except ValueError as nickname_error:
        registered = await db.get_officer_by_user_id(member.id)
        if registered and registered["is_admin_registered"]:
            return OfficerIdentity(registered["rank"], registered["full_name"], registered["pd_id"])
        raise ValueError(
            f"{member.mention} has an invalid server nickname. Set it to `Rank | Name | ID` "
            "or ask an administrator to use `/1012 register`."
        ) from nickname_error
    await db.upsert_officer(member.id, identity)
    return identity


def parse_participant_ids(raw: str) -> list[int]:
    tokens = re.findall(r"<@!?([0-9]+)>|(?:^|[\s,])([0-9]+)(?=$|[\s,])", raw)
    ids = [int(mention or numeric) for mention, numeric in tokens]
    if not ids:
        raise ValueError("Mention one or more participating officers, separated by spaces or commas.")
    unique_ids = list(dict.fromkeys(ids))
    if len(unique_ids) > 25:
        raise ValueError("A session can have at most 25 participating officers.")
    return unique_ids


async def fetch_member(guild: discord.Guild, member_id: int) -> discord.Member:
    member = guild.get_member(member_id)
    if member is not None:
        return member
    try:
        return await guild.fetch_member(member_id)
    except discord.NotFound as exc:
        raise ValueError(f"Discord account `{member_id}` is not a member of this server.") from exc


async def report_error(interaction: discord.Interaction, message: str) -> None:
    if interaction.response.is_done():
        await interaction.followup.send(message, ephemeral=True)
    else:
        await interaction.response.send_message(message, ephemeral=True)


class StartConfirmationView(discord.ui.View):
    def __init__(self, session_id: str):
        super().__init__(timeout=None)
        self.session_id = session_id

    @discord.ui.button(label="Start Ride-Along", style=discord.ButtonStyle.success, custom_id="ra:confirm")
    async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
        details = await db.get_session(self.session_id)
        if not details:
            await report_error(interaction, "This session no longer exists.")
            return
        if not can_control_session(interaction.user, details):
            await report_error(interaction, "Only this session’s supervisor or a designated administrator can start it.")
            return
        try:
            details = await db.start_pending_session(self.session_id)
        except ValueError as exc:
            await report_error(interaction, str(exc))
            return
        await audit(
            interaction.guild,
            "Ride-along started",
            f"Session `{self.session_id}` started by <@{interaction.user.id}>.",
        )
        view = SessionView(details)
        await interaction.response.edit_message(embed=panel_embed(details), view=view)
        bot.add_view(view, message_id=interaction.message.id)


class OfficerSelect(discord.ui.Select):
    def __init__(self, session_id: str, participants: list[dict]):
        options = [
            discord.SelectOption(
                label=f"{p['rank']} | {p['name']} | {p['pd_id']}"[:100],
                value=p["discord_user_id"],