Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 1,308
bot.py
import logging
import os
import sqlite3
from datetime import datetime, timezone
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()
logging.basicConfig(
level=os.getenv("LOG_LEVEL", "INFO").upper(),
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("leo_police_reports")
def get_int_env(name: str, default: int = 0) -> int:
try:
return int(os.getenv(name, str(default)) or default)
except ValueError:
logger.warning("Invalid integer value for %s; using %s", name, default)
return default
TOKEN = (os.getenv("DISCORD_TOKEN") or "").strip()
LEO_ROLE_NAME = os.getenv("LEO_ROLE_NAME", "LEO")
SERVER_NAME = os.getenv("SERVER_NAME", "PS5 GTA V RP")
REPORT_CHANNEL_ID = get_int_env("REPORT_CHANNEL_ID")
GUILD_ID = get_int_env("DISCORD_GUILD_ID")
DATABASE_PATH = os.getenv("DATABASE_PATH", "data/reports.db")
if not TOKEN:
raise RuntimeError(
"DISCORD_TOKEN is required. Copy .env.example to .env and paste your "
"Discord bot token into DISCORD_TOKEN."
)
class NotLeoOfficer(app_commands.CheckFailure):
pass
class WrongReportChannel(app_commands.CheckFailure):
pass
async def leo_only(interaction: discord.Interaction) -> bool:
if interaction.guild is None or not isinstance(interaction.user, discord.Member):
raise NotLeoOfficer()
if REPORT_CHANNEL_ID and interaction.channel_id != REPORT_CHANNEL_ID:
raise WrongReportChannel()
if interaction.user.guild_permissions.administrator:
return True
if any(
role.name.casefold() == LEO_ROLE_NAME.casefold()
for role in interaction.user.roles
):
return True
raise NotLeoOfficer()
class ReportStore:
def __init__(self, database_path: str):
self.database_path = Path(database_path)
self.database_path.parent.mkdir(parents=True, exist_ok=True)
self._initialize()
def _connect(self) -> sqlite3.Connection:
connection = sqlite3.connect(self.database_path)
connection.row_factory = sqlite3.Row
return connection
def _initialize(self) -> None:
with self._connect() as connection:
connection.execute(
"""
CREATE TABLE IF NOT EXISTS reports (
id INTEGER PRIMARY KEY AUTOINCREMENT,
report_type TEXT NOT NULL,
incident_date TEXT NOT NULL,
location TEXT NOT NULL,
subjects TEXT NOT NULL,
summary TEXT NOT NULL,
evidence TEXT NOT NULL,
officers TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'OPEN',
created_by_id INTEGER NOT NULL,
created_by_name TEXT NOT NULL,
created_at TEXT NOT NULL,
closed_by_id INTEGER,
closed_by_name TEXT,
closed_at TEXT
)
"""
)
def create_report(
self,
report_type: str,
incident_date: str,
location: str,
subjects: str,
summary: str,
evidence: str,
officers: str,
created_by_id: int,
created_by_name: str,
) -> dict[str, Any]:
created_at = datetime.now(timezone.utc).isoformat()
with self._connect() as connection:
cursor = connection.execute(
"""
INSERT INTO reports (
report_type,
incident_date,
location,
subjects,
summary,
evidence,
officers,
status,
created_by_id,
created_by_name,
created_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, 'OPEN', ?, ?, ?)
""",
(
report_type,
incident_date,
location,
subjects,
summary,
evidence,
officers,
created_by_id,
created_by_name,
created_at,
),
)
report_id = cursor.lastrowid
return self.get_report(report_id)
def get_report(self, report_id: int) -> dict[str, Any] | None:
with self._connect() as connection:
row = connection.execute(
"SELECT * FROM reports WHERE id = ?",
(report_id,),
).fetchone()
return dict(row) if row else None
def search_reports(self, query: str, limit: int = 10) -> list[dict[str, Any]]:
search_value = f"%{query}%"
with self._connect() as connection:
rows = connection.execute(
"""
SELECT * FROM reports
WHERE report_type LIKE ?
OR incident_date LIKE ?
OR location LIKE ?
OR subjects LIKE ?
OR summary LIKE ?
OR evidence LIKE ?
OR officers LIKE ?
OR created_by_name LIKE ?
ORDER BY id DESC
LIMIT ?
""",
(
search_value,
search_value,
search_value,
search_value,
search_value,
search_value,
search_value,
search_value,
limit,
),
).fetchall()
return [dict(row) for row in rows]
def list_reports(
self,
status: str | None = None,