Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 626
bot.py
import logging
import os
import re
import sqlite3
import time
from datetime import datetime
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("vehicle-registration-bot")
class VehicleDatabase:
def __init__(self, path: str):
self.connection = sqlite3.connect(path, check_same_thread=False)
self.connection.row_factory = sqlite3.Row
self.connection.execute("PRAGMA foreign_keys = ON")
self.connection.execute(
"""
CREATE TABLE IF NOT EXISTS vehicles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
owner_id INTEGER NOT NULL,
discord_username TEXT NOT NULL,
username TEXT NOT NULL,
brand TEXT NOT NULL,
model TEXT NOT NULL,
year INTEGER NOT NULL,
color TEXT NOT NULL,
vehicle_type TEXT NOT NULL,
state TEXT NOT NULL,
plate_text TEXT NOT NULL,
registered_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE(guild_id, state, plate_text)
)
"""
)
self.connection.execute(
"""
CREATE TABLE IF NOT EXISTS violations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
vehicle_id INTEGER NOT NULL,
guild_id INTEGER NOT NULL,
officer_id INTEGER NOT NULL,
officer_username TEXT NOT NULL,
description TEXT NOT NULL,
fine INTEGER NOT NULL DEFAULT 0,
issued_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(vehicle_id) REFERENCES vehicles(id) ON DELETE CASCADE
)
"""
)
self.connection.execute(
"CREATE INDEX IF NOT EXISTS idx_vehicles_owner ON vehicles(guild_id, owner_id)"
)
self.connection.execute(
"CREATE INDEX IF NOT EXISTS idx_violations_vehicle ON violations(vehicle_id)"
)
self.connection.commit()
def add_vehicle(
self,
guild_id: int,
owner_id: int,
discord_username: str,
username: str,
brand: str,
model: str,
year: int,
color: str,
vehicle_type: str,
state: str,
plate_text: str,
) -> Optional[int]:
try:
cursor = self.connection.execute(
"""
INSERT INTO vehicles (
guild_id, owner_id, discord_username, username, brand, model,
year, color, vehicle_type, state, plate_text
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
guild_id,
owner_id,
discord_username,
username,
brand,
model,
year,
color,
vehicle_type,
state,
plate_text,
),
)
self.connection.commit()
return cursor.lastrowid
except sqlite3.IntegrityError:
self.connection.rollback()
return None
def list_for_owner(self, guild_id: int, owner_id: int) -> list[sqlite3.Row]:
cursor = self.connection.execute(
"""
SELECT * FROM vehicles
WHERE guild_id = ? AND owner_id = ?
ORDER BY registered_at DESC, id DESC
LIMIT 25
""",
(guild_id, owner_id),
)
return cursor.fetchall()
def find_by_plate(
self, guild_id: int, state: str, plate_text: str
) -> Optional[sqlite3.Row]:
cursor = self.connection.execute(
"""
SELECT * FROM vehicles
WHERE guild_id = ? AND state = ? AND plate_text = ?
""",
(guild_id, state, plate_text),
)
return cursor.fetchone()
def delete_vehicle(self, guild_id: int, vehicle_id: int) -> None:
self.connection.execute(
"DELETE FROM vehicles WHERE guild_id = ? AND id = ?",
(guild_id, vehicle_id),
)
self.connection.commit()
def add_violation(
self,
vehicle_id: int,
guild_id: int,
officer_id: int,
officer_username: str,
description: str,
fine: int,
) -> int:
cursor = self.connection.execute(
"""
INSERT INTO violations (
vehicle_id, guild_id, officer_id, officer_username, description, fine
) VALUES (?, ?, ?, ?, ?, ?)
""",
(vehicle_id, guild_id, officer_id, officer_username, description, fine),
)
self.connection.commit()
return cursor.lastrowid
def list_violations(self, guild_id: int, vehicle_id: int) -> list[sqlite3.Row]:
cursor = self.connection.execute(
"""
SELECT * FROM violations
WHERE guild_id = ? AND vehicle_id = ?
ORDER BY issued_at DESC, id DESC
LIMIT 25
""",
(guild_id, vehicle_id),
)
return cursor.fetchall()
def close(self) -> None:
self.connection.close()
def clean_text(value: str, field_name: str, maximum: int) -> tuple[Optional[str], Optional[str]]:
value = value.strip()
if not value:
return None, f"{field_name} cannot be empty."
if len(value) > maximum:
return None, f"{field_name} must be {maximum} characters or fewer."
return value, None
def normalize_registration(
username: str,
brand: str,
model: str,
year: int,
color: str,
vehicle_type: str,
state: str,
plate_text: str,
) -> tuple[Optional[dict], Optional[str]]:
values = {}