zeusbuilds

One resource that runs the Discord side of the server. A voice channel with the live player count like Ingame: 24/64, updated every 30 seconds. /link so players connect their Discord to their in-game account, and anyone without the whitelist role is dropped on connect. Staff commands for /kick, /ban, /msg and /online that act on the running server, restricted to a staff role. Every staff action and every whitelist change posted to a log channel as an embed. Put all role and channel ids in the config so nothing is hard coded. while also giving me access to upload vehicles into my fivem server. with never having to touch the desktop for my server. i also need it to work with my trust system so that i can set peoples ownership with the /setOwner command.

Kodari AI
KodariAug 29 at 9:08 pm 2
DiscordServerManager
A Discord bot for FiveM server administration. Features live player count voice channel updates every 30 seconds, /link command to connect Discord accounts to in-game profiles, automatic whitelist enforcement dropping unlinked users, staff-only commands (/kick, /ban, /msg, /online) targeting the live server, vehicle upload capability via Discord, and a trust system with /setOwner for ownership management. All role and channel IDs configured externally, with every action logged as embeds to a designated channel.
  1. Build the Discord bot with configurable roles/channels, linking, staff controls, logging, live player-count status, vehicle uploads, and ownership persistence.

  2. Add the FiveM bridge resource for whitelist enforcement, command polling, persistent bans, player heartbeats, and trust-system ownership events.

  3. Add configuration, environment/dependency files, and setup documentation.

The initial files are created. I’m applying one correctness fix before handing it over: the kick command had an invalid placeholder role check that would block every use, and the whitelist-linking flow needs to document its bootstrap behavior.1. Created the Discord/FiveM integration project from scratch. 2. Added Discord features:

  • /link

  • /kick

  • /ban

  • /msg

  • /online

  • /setowner

  • /uploadvehicle

  1. Added configurable guild, role, channel, API, storage, and security settings.

  2. Added FiveM bridge functionality:

    • Whitelist checks on connection

    • Account linking

    • Player heartbeat tracking

    • Staff command polling

    • Persistent bans

    • Trust-system ownership events and optional exports

  3. Added secure ZIP vehicle uploads with path traversal and symlink protection.

  4. Added embed logging for staff actions, account links, vehicle uploads, and whitelist role changes.

  5. Added setup documentation, dependency declarations, environment template, and ignore rules.

Use /setowner rather than /setOwner because Discord application command names must be lowercase.

zeusbuilds

can you make it where it will pack all the vehicles in the same folder to eliminate resource.lua's

Kodari AI
KodariAug 29 at 9:16 pm 1
  1. Change vehicle uploads to accept a bundle of vehicle resource folders.

  2. Strip each nested fxmanifest.lua/__resource.lua, preserve vehicle files in one combined resource, and generate the only manifest automatically.

  3. Update the upload command and documentation so the bundle format is clear.

Updated /uploadvehicle to support combined vehicle packs:

  • Accepts a ZIP containing multiple vehicle folders.

  • Removes all fxmanifest.lua, __resource.lua, and resource.lua files.

  • Combines streamed vehicle assets into one stream folder.

  • Combines supported metadata into one data folder.

  • Generates a single fxmanifest.lua automatically.

  • Rejects duplicate streamed filenames to prevent vehicle conflicts.

  • Preserves secure ZIP path and symlink protections.

  • Updated the README with the new bundle format.

FiveM still requires one manifest for the combined resource, so the individual vehicle manifests are eliminated and replaced with one generated fxmanifest.lua.

zeusbuilds

how do i run this bot

Kodari AI
KodariAug 29 at 9:17 pm 1

Run it from the project folder that contains bot.py.

1. Install Python

Use Python 3.10 or newer.

Linux

Shell
cd /path/to/DiscordServerManager

python3 -m venv .venv
source .venv/bin/activate

pip install -r requirements.txt

Windows

Powershell
cd C:\path\to\DiscordServerManager

py -m venv .venv
.venv\Scripts\activate

pip install -r requirements.txt

2. Configure the bot token

Copy the environment template:

Shell
cp .env.example .env

Edit .env:

Env
DISCORD_TOKEN=your_actual_discord_bot_token
CONFIG_PATH=config.json

Create the bot in the Discord Developer Portal, enable Server Members Intent, and invite it using:

  • bot

  • applications.commands

3. Edit config.json

Replace all 0 values with your Discord IDs:

JSON
{
  "discord": {
    "guild_id": 123456789012345678,
    "staff_role_id": 123456789012345678,
    "admin_role_id": 123456789012345678,
    "whitelist_role_id": 123456789012345678,
    "log_channel_id": 123456789012345678,
    "status_voice_channel_id": 123456789012345678
  },
  "bridge": {
    "bind_host": "127.0.0.1",
    "bind_port": 8080,
    "shared_secret": "create-a-long-random-secret"
  },
  "storage": {
    "database_path": "kodari.sqlite3",
    "resource_upload_dir": "/path/to/your/fivem/resources",
    "max_upload_mb": 500
  },
  "security": {
    "link_code_ttl_seconds": 600
  }
}

Enable Developer Mode in Discord, then right-click the server, roles, and channels to copy their IDs.

Set resource_upload_dir to the actual resources directory used by your FiveM server. For example:

JSON
"resource_upload_dir": "/home/fivem/server-data/resources"

This allows /uploadvehicle to place vehicle resources directly into the FiveM server.

4. Install the FiveM bridge

Copy the fivem folder into your FiveM resources directory as:

Plain Text
resources/[kodari]/kodari_bridge/

Add this to server.cfg:

Cfg
set kodari_bot_api "http://127.0.0.1:8080"
set kodari_bot_secret "create-a-long-random-secret"
set kodari_trust_event "trust:setOwner"

ensure kodari_bridge

The value of kodari_bot_secret must exactly match bridge.shared_secret in config.json.

If the bot and FiveM are on different servers, replace 127.0.0.1 with the bot server’s private IP and firewall port 8080 so only the FiveM server can access it.

5. Start the bot

Shell
source .venv/bin/activate
python bot.py

On Windows:

Powershell
.venv\Scripts\activate
py bot.py

You should see the bot connect to Discord. Start or restart FiveM after adding the bridge resource.

6. Keep it running without a desktop

On Linux, run it with systemd or tmux. For example:

Shell
tmux new -s discordbot
cd /path/to/DiscordServerManager
source .venv/bin/activate
python bot.py

Detach with:

Plain Text
Ctrl+B, then D

Reattach later with:

Shell
tmux attach -t discordbot

Once running, the main commands are:

Plain Text
/link
/kick
/ban
/msg
/online
/setowner
/uploadvehicle

/kick, /ban, /msg, and /online require the configured staff role. /uploadvehicle requires the configured admin role. Discord command names are lowercase, so ownership uses /setowner.

zeusbuilds

will the bot appear online

Kodari AI
KodariAug 30 at 6:24 pm 1

Yes. The bot will appear online in Discord while bot.py is running successfully and connected with a valid token.

You should see a console message similar to:

Plain Text
Logged in as YourBot#0000

It may appear offline if:

  • bot.py is not running

  • the process crashes or the server reboots

  • DISCORD_TOKEN is incorrect

  • the bot cannot connect to Discord

  • the hosting server loses internet access

The FiveM bridge does not control the Discord presence; the Python bot must remain running. To keep it online continuously, run it with systemd, Docker, or a process manager such as pm2 rather than closing the terminal.

zeusbuilds
📎 1 file 1,684 chars
📄
pasted-code-1788114432089.txt
txt 34 lines
▶
 .venv\Scripts\activate
>> py bot.py
>>
Traceback (most recent call last):
  File "C:\RedDirt\txData\Qbox_6FC022.base\resources\DiscordServerManager\bot.py", line 586, in 
    asyncio.run(main())
    ~~~~~~~~~~~^^^^^^^^
  File "C:\Python314\Lib\asyncio\runners.py", line 204, in run
    return runner.run(main)
           ~~~~~~~~~~^^^^^^
  File "C:\Python314\Lib\asyncio\runners.py", line 127, in run
    return self._loop.run_until_complete(task)
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
  File "C:\Python314\Lib\asyncio\base_events.py", line 719, in run_until_complete
    return future.result()
           ~~~~~~~~~~~~~^^
  File "C:\RedDirt\txData\Qbox_6FC022.base\resources\DiscordServerManager\bot.py", line 561, in main
    config = json.load(config_file)
  File "C:\Python314\Lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
        cls=cls, object_hook=object_hook,
        parse_float=parse_float, parse_int=parse_int,
        parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "C:\Python314\Lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
           ~~~~~~~~~~~~~~~~~~~~~~~^^^
  File "C:\Python314\Lib\json\decoder.py", line 345, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python314\Lib\json\decoder.py", line 361, in raw_decode
    obj, end = self.scan_once(s, idx)
               ~~~~~~~~~~~~~~^^^^^^^^
json.decoder.JSONDecodeError: Invalid \escape: line 17 column 31 (char 442)
(.venv) PS C:\RedDirt\txData\Qbox_6FC022.base\resources\DiscordServerManager>
Kodari AI
KodariAug 30 at 6:25 pm 1

The error is caused by the Windows path in config.json. JSON treats single backslashes as escape characters.

Change line 17 from something like:

JSON
"resource_upload_dir": "C:\RedDirt\txData\Qbox_6FC022.base\resources"

to either:

JSON
"resource_upload_dir": "C:/RedDirt/txData/Qbox_6FC022.base/resources"

or:

JSON
"resource_upload_dir": "C:\\RedDirt\\txData\\Qbox_6FC022.base\\resources"

Your storage section should look like:

JSON
"storage": {
  "database_path": "kodari.sqlite3",
  "resource_upload_dir": "C:/RedDirt/txData/Qbox_6FC022.base/resources",
  "max_upload_mb": 500
}

Save the file, then run:

Powershell
py bot.py

The upload directory should be the main FiveM resources folder—not the bot’s DiscordServerManager folder.

zeusbuilds

>> Traceback (most recent call last):

File "C:\RedDirt\txData\Qbox_6FC022.base\resources\DiscordServerManager\bot.py", line 586, in <module> asyncio.run(main()) ~~~~~~~~~~~^^^^^^^^ File "C:\Python314\Lib\asyncio\runners.py", line 204, in run return runner.run(main) ~~~~~~~~~~^^^^^^ File "C:\Python314\Lib\asyncio\runners.py", line 127, in run return self._loop.run_until_complete(task) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^ File "C:\Python314\Lib\asyncio\base_events.py", line 719, in run_until_complete return future.result() ~~~~~~~~~~~~~^^ File "C:\RedDirt\txData\Qbox_6FC022.base\resources\DiscordServerManager\bot.py", line 564, in main raise RuntimeError("DISCORD_TOKEN is not set") RuntimeError: DISCORD_TOKEN is not set (.venv) PS C:\RedDirt\txData\Qbox_6FC022.base\resources\DiscordServerManager>

Kodari AI
KodariAug 30 at 6:27 pm 1

DISCORD_TOKEN is missing from the environment. Create a file named .env in:

Plain Text
C:\RedDirt\txData\Qbox_6FC022.base\resources\DiscordServerManager\

Its contents should be:

Env
DISCORD_TOKEN=your_actual_discord_bot_token
CONFIG_PATH=config.json

Replace your_actual_discord_bot_token with the bot token from Discord Developer Portal → Bot → Reset Token.

Make sure the file is named exactly:

Plain Text
.env

not:

Plain Text
.env.example
.env.txt

In PowerShell, verify it exists:

Powershell
Get-ChildItem -Force

You should see .env. Then restart the bot:

Powershell
.venv\Scripts\activate
py bot.py

For a temporary test, you can set the token directly in PowerShell:

Powershell
$env:DISCORD_TOKEN="your_actual_discord_bot_token"
py bot.py

Never post or share the token. If it has been exposed, reset it immediately in the Discord Developer Portal.

zeusbuilds

>> 2026-08-30 20:28:03,464 WARNING discord.client: PyNaCl is not installed, voice will NOT be supported 2026-08-30 20:28:03,464 WARNING discord.client: davey is not installed, voice will NOT be supported 2026-08-30 20:28:03,467 INFO kodari: Bridge API listening on 127.0.0.1:8080 2026-08-30 20:28:03,467 INFO discord.client: logging in using static token 2026-08-30 20:28:03,468 WARNING discord.ext.commands.bot: Privileged message content intent is missing, commands may not work as expected. 2026-08-30 20:28:04,372 INFO discord.gateway: Shard ID None has connected to Gateway (Session ID: 9a9787350da3c9e0068298a89ba4e240).

Kodari AI
KodariAug 30 at 6:28 pm 1

Yes—the bot is running and successfully connected to Discord:

Plain Text
Shard ID None has connected to Gateway

It should now appear online in Discord.

The warnings are not startup failures:

  • PyNaCl/davey not installed: only affects connecting to or playing audio in voice channels. The bot can still rename a voice channel with the player count.

  • Message content intent missing: affects traditional prefix commands such as !command. Your slash commands should still work. Enable Message Content Intent in the Discord Developer Portal if you plan to use prefix commands.

Verify the following in Discord:

  1. Slash commands appear after typing /.

  2. The bot has Manage Channels permission for the player-count voice channel.

  3. The bot has Send Messages and Embed Links permission in the log channel.

  4. FiveM can reach 127.0.0.1:8080 if FiveM and the bot are running on the same Windows machine.

Keep the PowerShell window open; closing it stops the bot.

zeusbuilds

[DTF], Dev Diddy APP — 2:39 PM The FiveM server heartbeat is unavailable.

Only you can see this • Dismiss message

Kodari AI
KodariAug 30 at 6:40 pm 1

The Discord bot is online, but the FiveM bridge is not successfully sending heartbeats to it. The warning appears when /online has not received a heartbeat within 90 seconds.

1. Confirm the bridge is installed correctly

Your FiveM resource should look like this:

Plain Text
resources/[kodari]/kodari_bridge/
├── fxmanifest.lua
├── config.lua
├── server.lua
└── bans.json

Do not leave it as:

Plain Text
resources/[kodari]/fivem/server.lua

2. Add the bridge settings to server.cfg

Cfg
set kodari_bot_api "http://127.0.0.1:8080"
set kodari_bot_secret "the-exact-same-secret-from-config.json"

ensure kodari_bridge

The secret must match this value in the bot’s config.json:

JSON
"bridge": {
  "bind_host": "127.0.0.1",
  "bind_port": 8080,
  "shared_secret": "the-exact-same-secret-from-config.json"
}

Make sure there are no extra spaces or quotation differences in the secret.

3. Restart both programs

Stop and restart the Python bot:

Powershell
py bot.py

Then restart the FiveM server, or run this in the FiveM console:

Plain Text
restart kodari_bridge

You should see the bridge resource start in the FiveM console. The bot should continue showing:

Plain Text
Bridge API listening on 127.0.0.1:8080

4. Test the bot API from PowerShell

With the Python bot running, execute:

Powershell
Invoke-WebRequest http://127.0.0.1:8080/health

A successful result should return:

JSON
{"ok": true}

If that works but the heartbeat is still unavailable, the issue is on the FiveM bridge side—usually kodari_bridge is not started or the secret does not match.

If FiveM and the bot are on different computers, 127.0.0.1 is incorrect. Set kodari_bot_api to the bot computer’s LAN IP instead:

Cfg
set kodari_bot_api "http://192.168.1.25:8080"

Then configure the bot’s bind_host as:

JSON
"bind_host": "0.0.0.0"

and allow TCP port 8080 through the Windows firewall.

Kodari can make mistakes. Review important code before using.
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: