Files
main.py
requirements.txt
Code
2 277
main.py
import logging
import os
from datetime import datetime, timezone
from decimal import Decimal, InvalidOperation
import aiosqlite
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("gestione_server")
DATABASE_PATH = "gestione_server.db"
async def initialize_database():
async with aiosqlite.connect(DATABASE_PATH) as db:
await db.execute("""
CREATE TABLE IF NOT EXISTS arrests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
person TEXT NOT NULL,
duration TEXT NOT NULL,
reason TEXT NOT NULL,
created_at TEXT NOT NULL,
staff_id INTEGER NOT NULL
)
""")
await db.execute("""
CREATE TABLE IF NOT EXISTS fines (
id INTEGER PRIMARY KEY AUTOINCREMENT,
person TEXT NOT NULL,
amount REAL NOT NULL,
reason TEXT NOT NULL,
created_at TEXT NOT NULL,
staff_id INTEGER NOT NULL
)
""")
await db.execute("""
CREATE TABLE IF NOT EXISTS vehicles (
plate TEXT PRIMARY KEY COLLATE NOCASE,
model TEXT NOT NULL,
owner TEXT NOT NULL,
created_at TEXT NOT NULL,
staff_id INTEGER NOT NULL
)
""")
await db.commit()
def timestamp():
return datetime.now(timezone.utc).strftime("%d/%m/%Y %H:%M UTC")
async def add_arrest(person, duration, reason, staff_id):
async with aiosqlite.connect(DATABASE_PATH) as db:
await db.execute(
"INSERT INTO arrests (person, duration, reason, created_at, staff_id) VALUES (?, ?, ?, ?, ?)",
(person, duration, reason, timestamp(), staff_id),
)
await db.commit()
async def add_fine(person, amount, reason, staff_id):
async with aiosqlite.connect(DATABASE_PATH) as db:
await db.execute(
"INSERT INTO fines (person, amount, reason, created_at, staff_id) VALUES (?, ?, ?, ?, ?)",
(person, amount, reason, timestamp(), staff_id),
)
await db.commit()
async def save_vehicle(plate, model, owner, staff_id):
async with aiosqlite.connect(DATABASE_PATH) as db:
await db.execute(
"""INSERT INTO vehicles (plate, model, owner, created_at, staff_id)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(plate) DO UPDATE SET model = excluded.model, owner = excluded.owner,
created_at = excluded.created_at, staff_id = excluded.staff_id""",
(plate.upper(), model, owner, timestamp(), staff_id),
)
await db.commit()
async def search_records(query):
pattern = f"%{query.strip()}%"
async with aiosqlite.connect(DATABASE_PATH) as db:
db.row_factory = aiosqlite.Row
arrests = await (await db.execute(
"SELECT person, duration, reason, created_at FROM arrests WHERE person LIKE ? ORDER BY id DESC LIMIT 5",
(pattern,),
)).fetchall()
fines = await (await db.execute(
"SELECT person, amount, reason, created_at FROM fines WHERE person LIKE ? ORDER BY id DESC LIMIT 5",
(pattern,),
)).fetchall()
vehicles = await (await db.execute(
"SELECT plate, model, owner FROM vehicles WHERE plate LIKE ? OR model LIKE ? OR owner LIKE ? ORDER BY plate LIMIT 5",
(pattern, pattern, pattern),
)).fetchall()
return arrests, fines, vehicles
def staff_only(interaction):
return isinstance(interaction.user, discord.Member) and interaction.user.guild_permissions.manage_guild
class ArrestModal(discord.ui.Modal, title="Registra un arresto"):
person = discord.ui.TextInput(label="Nome della persona", max_length=100)
duration = discord.ui.TextInput(label="Durata", placeholder="Es. 20 minuti", max_length=80)
reason = discord.ui.TextInput(label="Motivo", style=discord.TextStyle.paragraph, max_length=500)
async def on_submit(self, interaction: discord.Interaction):
await add_arrest(self.person.value.strip(), self.duration.value.strip(), self.reason.value.strip(), interaction.user.id)
await interaction.response.send_message(
f"Arresto registrato per **{self.person.value.strip()}**.", ephemeral=True
)
class FineModal(discord.ui.Modal, title="Registra una multa"):
person = discord.ui.TextInput(label="Nome della persona", max_length=100)
amount = discord.ui.TextInput(label="Importo", placeholder="Es. 250 oppure 250,50", max_length=20)
reason = discord.ui.TextInput(label="Motivo", style=discord.TextStyle.paragraph, max_length=500)
async def on_submit(self, interaction: discord.Interaction):
try:
amount = Decimal(self.amount.value.strip().replace(",", "."))
if not amount.is_finite() or amount <= 0:
raise InvalidOperation
except InvalidOperation:
await interaction.response.send_message("Inserisci un importo valido maggiore di zero.", ephemeral=True)
return
await add_fine(self.person.value.strip(), float(amount), self.reason.value.strip(), interaction.user.id)
await interaction.response.send_message(
f"Multa di **{amount:.2f}** registrata per **{self.person.value.strip()}**.", ephemeral=True
)
class VehicleModal(discord.ui.Modal, title="Registra o aggiorna un veicolo"):
plate = discord.ui.TextInput(label="Targa", max_length=16)
model = discord.ui.TextInput(label="Modello", max_length=100)
owner = discord.ui.TextInput(label="Proprietario", max_length=100)
async def on_submit(self, interaction: discord.Interaction):
await save_vehicle(self.plate.value.strip(), self.model.value.strip(), self.owner.value.strip(), interaction.user.id)
await interaction.response.send_message(
f"Veicolo **{self.plate.value.strip().upper()}** salvato.", ephemeral=True
)
class SearchModal(discord.ui.Modal, title="Cerca persone e veicoli"):
query = discord.ui.TextInput(label="Nome, targa, modello o proprietario", max_length=100)
async def on_submit(self, interaction: discord.Interaction):
await send_search_results(interaction, self.query.value.strip())
async def send_search_results(interaction, query):
if not query:
await interaction.response.send_message("Inserisci un termine da cercare.", ephemeral=True)
return
arrests, fines, vehicles = await search_records(query)
embed = discord.Embed(title=f"Risultati ricerca: {query[:100]}", color=discord.Color.blurple())
if arrests:
embed.add_field(
name="Arresti",
value="\n".join(f"**{row['person']}** · {row['duration']} — {row['reason']} ({row['created_at']})" for row in arrests)[:1024],
inline=False,
)
if fines:
embed.add_field(
name="Multe",
value="\n".join(f"**{row['person']}** · {row['amount']:.2f} — {row['reason']} ({row['created_at']})" for row in fines)[:1024],
inline=False,
)
if vehicles:
embed.add_field(
name="Veicoli",
value="\n".join(f"**{row['plate']}** · {row['model']} — proprietario: {row['owner']}" for row in vehicles)[:1024],
inline=False,
)
if not arrests and not fines and not vehicles:
embed.description = "Nessun risultato trovato."
embed.set_footer(text="Mostrati al massimo 5 risultati per categoria")
await interaction.response.send_message(embed=embed, ephemeral=True)
class StaffPanelView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
async def open_modal(self, interaction, modal):
if not staff_only(interaction):
await interaction.response.send_message("Serve il permesso **Gestisci server** per usare il pannello.", ephemeral=True)
return
await interaction.response.send_modal(modal)