Files
fivem
.gitignore
bot.py
config.json
README.md
requirements.txt
Code
10 918
bot.py
import asyncio
import hashlib
import hmac
import json
import logging
import os
import re
import secrets
import shutil
import sqlite3
import tempfile
import time
import zipfile
from pathlib import Path, PurePosixPath
import aiohttp
from aiohttp import web
import discord
from discord import app_commands
from discord.ext import commands, tasks
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("kodari")
class Database:
def __init__(self, path: str):
self.connection = sqlite3.connect(path, check_same_thread=False)
self.connection.row_factory = sqlite3.Row
self.connection.executescript(
"""
CREATE TABLE IF NOT EXISTS link_codes (
code TEXT PRIMARY KEY,
discord_id TEXT NOT NULL,
expires_at INTEGER NOT NULL,
used_at INTEGER
);
CREATE TABLE IF NOT EXISTS linked_accounts (
license_id TEXT PRIMARY KEY,
discord_id TEXT NOT NULL,
identifiers TEXT NOT NULL,
player_name TEXT NOT NULL,
linked_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS commands (
id INTEGER PRIMARY KEY AUTOINCREMENT,
action TEXT NOT NULL,
payload TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
created_at INTEGER NOT NULL,
result TEXT
);
CREATE TABLE IF NOT EXISTS server_state (
id INTEGER PRIMARY KEY CHECK (id = 1),
players TEXT NOT NULL,
max_players INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS vehicle_owners (
vehicle TEXT PRIMARY KEY,
discord_id TEXT NOT NULL,
display_name TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
"""
)
self.connection.commit()
def create_link_code(self, discord_id: int, ttl_seconds: int) -> tuple[str, int]:
now = int(time.time())
expires_at = now + ttl_seconds
code = secrets.token_hex(4).upper()
self.connection.execute(
"INSERT INTO link_codes(code, discord_id, expires_at) VALUES (?, ?, ?)",
(code, str(discord_id), expires_at),
)
self.connection.commit()
return code, expires_at
def consume_link_code(self, code: str, license_id: str, identifiers: list[str], player_name: str) -> str | None:
now = int(time.time())
row = self.connection.execute(
"SELECT discord_id FROM link_codes WHERE code = ? AND used_at IS NULL AND expires_at >= ?",
(code.upper(), now),
).fetchone()
if row is None:
return None
self.connection.execute("UPDATE link_codes SET used_at = ? WHERE code = ?", (now, code.upper()))
self.connection.execute(
"INSERT INTO linked_accounts(license_id, discord_id, identifiers, player_name, linked_at) "
"VALUES (?, ?, ?, ?, ?) ON CONFLICT(license_id) DO UPDATE SET discord_id=excluded.discord_id, "
"identifiers=excluded.identifiers, player_name=excluded.player_name, linked_at=excluded.linked_at",
(license_id, row["discord_id"], json.dumps(identifiers), player_name, now),
)
self.connection.commit()
return row["discord_id"]
def linked_discord_id(self, license_id: str) -> str | None:
row = self.connection.execute(
"SELECT discord_id FROM linked_accounts WHERE license_id = ?", (license_id,)
).fetchone()
return row["discord_id"] if row else None
def enqueue(self, action: str, payload: dict) -> int:
cursor = self.connection.execute(
"INSERT INTO commands(action, payload, created_at) VALUES (?, ?, ?)",
(action, json.dumps(payload), int(time.time())),
)
self.connection.commit()
return int(cursor.lastrowid)
def claim_pending(self) -> list[dict]:
rows = self.connection.execute(
"SELECT id, action, payload FROM commands WHERE status = 'pending' ORDER BY id LIMIT 50"
).fetchall()
if rows:
self.connection.executemany(
"UPDATE commands SET status = 'delivered' WHERE id = ?", [(row["id"],) for row in rows]
)
self.connection.commit()
return [
{"id": row["id"], "action": row["action"], "payload": json.loads(row["payload"])}
for row in rows
]
def complete_command(self, command_id: int, success: bool, message: str) -> None:
self.connection.execute(
"UPDATE commands SET status = ?, result = ? WHERE id = ?",
("complete" if success else "failed", message[:1000], command_id),
)
self.connection.commit()
def record_players(self, players: list[dict], max_players: int) -> None:
self.connection.execute(
"INSERT INTO server_state(id, players, max_players, updated_at) VALUES (1, ?, ?, ?) "
"ON CONFLICT(id) DO UPDATE SET players=excluded.players, max_players=excluded.max_players, "
"updated_at=excluded.updated_at",
(json.dumps(players), max_players, int(time.time())),
)
self.connection.commit()
def server_snapshot(self) -> tuple[list[dict], int, int] | None:
row = self.connection.execute("SELECT players, max_players, updated_at FROM server_state WHERE id = 1").fetchone()
if row is None:
return None
return json.loads(row["players"]), row["max_players"], row["updated_at"]
def set_owner(self, vehicle: str, discord_id: int, display_name: str) -> None:
self.connection.execute(
"INSERT INTO vehicle_owners(vehicle, discord_id, display_name, updated_at) VALUES (?, ?, ?, ?) "
"ON CONFLICT(vehicle) DO UPDATE SET discord_id=excluded.discord_id, display_name=excluded.display_name, "
"updated_at=excluded.updated_at",
(vehicle, str(discord_id), display_name, int(time.time())),
)
self.connection.commit()
class KodariBot(commands.Bot):
def __init__(self, config: dict, database: Database):
intents = discord.Intents.default()
intents.members = True
super().__init__(command_prefix="!", intents=intents)
self.config = config
self.database = database
self.http_runner: web.AppRunner | None = None
self.http_site: web.TCPSite | None = None
async def setup_hook(self) -> None:
guild_id = int(self.config["discord"]["guild_id"])
guild = discord.Object(id=guild_id)
self.tree.copy_global_to(guild=guild)
await self.tree.sync(guild=guild)
self.status_loop.start()
async def start_http(self) -> None:
app = web.Application()
app.add_routes(
[
web.get("/health", self.handle_health),
web.post("/api/server/heartbeat", self.handle_heartbeat),
web.get("/api/server/commands", self.handle_commands),
web.post("/api/server/commands/{command_id}/result", self.handle_command_result),
web.post("/api/link/consume", self.handle_link_consume),
web.get("/api/whitelist/check", self.handle_whitelist_check),
]
)
self.http_runner = web.AppRunner(app)
await self.http_runner.setup()
bridge = self.config["bridge"]
self.http_site = web.TCPSite(self.http_runner, bridge["bind_host"], int(bridge["bind_port"]))
await self.http_site.start()
logger.info("Bridge API listening on %s:%s", bridge["bind_host"], bridge["bind_port"])
async def close(self) -> None:
if self.status_loop.is_running():
self.status_loop.cancel()
if self.http_runner: