All products

np_discord

Discord for your server scripts. One resource holds the bot token and every other resource asks it through exports: is this player a cop on Discord, give them a role, log this to a channel, ban that account, post a status message, answer a slash command. Plus the things every server ends up building on top: a whitelist, batched logs, a chat bridge and rich presence.

v1.0.0StandaloneAbout 150 exportsNo database
Price TBAStore link follows at release
InstallationDocumentation
Version
1.0.0
Frameworks
None needed. Job roles for es_extended, qb-core and qbx_core, detected by their events
Dependencies
None
Database
None
Discord
An application with a bot user on your server
Gateway
Optional, needs a server artifact with the Node 22 runtime
Optional
np_admin (live settings), chat (chat bridge), baseevents (death log)
Permissions
No in-game permissions. The bot's Discord permissions are the limit
Logs: one Log call per entry returns at once, and the bot posts the entries as batched embeds, ten per message, with the player's name, id and mention
Logs: one Log call per entry returns at once, and the bot posts the entries as batched embeds, ten per message, with the player's name, id and mention

np_discord has no in-game UI. These illustrations show what a script calls and what the bot posts, rendered in the browser at 1920×1080. Names are made up.

What's in it

Around 150 exports with the same conventions: a result on success, false for "no", and an error as the second value when Discord could not be asked. Rate limits, retries and caching are handled for you.

Players are Discord users

  • Every function takes a player source, a Discord id or discord:<id>.
  • Roles and channels by config name ('police'), id or their name on Discord.

Members and roles

  • HasRole, HasAnyRole, AddRole, RemoveRole, SetRoles, SetNickname.
  • Display name, avatar, account age, boosting and computed permissions, per channel too.

Moderation and voice

  • Timeout, kick, ban, unban, bulk ban, ban lookup and the audit log.
  • Move, disconnect, mute and deafen members, and see who sits in which voice channel.

Messages

  • Send, edit, delete, pin, react, reply. Embeds, buttons, text files, DMs, threads and forum posts.
  • Text is cut to Discord's limits, and nothing pings anyone unless you ask for it.

Logs and webhooks

  • Log('name', entry) returns at once. Entries go out ten embeds per message.
  • Webhook urls live in convars, not in files. Built-in join, leave, chat, death and resource logs.

Several guilds

  • Finds every guild the bot is in, with its roles and channels, without listing an id.
  • A main server plus LSPD, LSMD or FIB servers. A role knows which guild it lives in.

Slash commands and live updates

  • Slash commands, buttons, select menus and modals. Handlers get the in-game source.
  • A role given on Discord reaches the game within a second through the gateway.

Ready-made

  • A connection whitelist, in-game chat to a Discord channel and back, a self-updating status message and the bot activity.
  • Job to role sync and client rich presence with buttons.

A closer look

Logs

Log never makes a script wait. Entries are queued per channel and sent in batches, so a busy server doesn't run into Discord's rate limits.

A Log call and the admin log channel with four batched embeds: vehicle spawned, went on duty, player joined and player banned
  • Batched: ten embeds per message every Config.Logs.flushInterval ms (2000 by default), up to 200 waiting per channel.
  • player = source adds a field with the player's name, id and mention.
  • A channel is a webhook url from the convar discord_webhook_<name>, or a channel the bot posts in.
  • Built in: join, leave, chat, death (needs baseevents) and resource start and stop. Each one off until you name a channel.

Roles and job sync

Every online player is synced on join: Discord id, member status, name, avatar and roles in every configured guild. Role changes on Discord fire an event in game.

A player's roles in the main and LSPD guilds, HasRole checks, the job to role mapping and the role change event
PieceHow it works
ChecksHasRole(source, 'police') works on cached members, so most checks need no request. "Not a member" and "could not ask" both come back falsy, so if HasRole(…) then is safe
ChangesAddRole, RemoveRole and SetRoles with a reason for the audit log. Drag the bot's role above every role it hands out
Livenp_discord:playerRolesChanged with the added and removed roles. Within a second through the gateway, without it a poll checks one online player every 5 s
Job rolesConfig.JobRoles: a framework job, and a grade if you like, becomes a Discord role. The old job's role is taken away on a job change
ClientEach client gets its own profile (avatar, display name, roles) for UIs. Permissions are always decided on the server

Slash commands, buttons and modals

They need the gateway. A handler gets the interaction, the arguments and the in-game player that belongs to the Discord user, or false. A string it returns is sent as the reply.

RegisterCommand for /kick, the reply Kicked 23 in the staff channel and an application message with buttons
  • RegisterCommand in one guild, several or all of them, or globally. Commands are only re-sent to Discord when they changed.
  • OnComponent for buttons and select menus by custom_id prefix, OnModal for forms, OnAutocomplete for up to 25 choices.
  • Answer within three seconds, or call InteractionDefer first and edit the reply later.
  • permissions only sets who sees a command by default. Check the member yourself when a command is sensitive.

Whitelist

Config.Connect is checked while the player connects. Off by default.

OptionWhat it does
requireDiscordDiscord must be running and linked to FiveM
requireMembertrue for the main guild, or a list of guilds the player must be in
rolesAt least one of these, from any guild. Empty means no role needed
blockedRolesRefused with any of these, from any guild
bypassIdentifiers that always get in: license:…, discord:…, steam:…
failOpenLet players in when Discord itself is unreachable. Off by default
messagesThe text for checking, no Discord, not a member, missing role, blocked and error
Connecting: checking your Discord, welcome in, not whitelisted and Discord not found, next to the Config.Connect options

A role in roles or blockedRoles that can't be resolved refuses every connection and says so in the console, rather than letting everyone in.

Status message, chat bridge and presence

Each one is a switch in config.lua, off until you turn it on.

The status message with 32 of 64 players and the connect address, the bot activity, rich presence and the chat bridge in both directions
  • Status message: the bot keeps one message up to date with the player count, the connect address and up to 40 player names.
  • Bot activity: {players}/{max} players under the bot's name. Needs the gateway.
  • Chat bridge: in-game chat to a Discord channel, and back with the gateway and the Message Content intent. Commands starting with / are skipped.
  • Rich presence on the player's own Discord profile, with your art and up to two buttons. Scripts can override the text with SetPresence.

Several guilds

At start np_discord reads every guild the bot is in, with its roles and channels. With the gateway that data stays current without another request.

  • The guild from discord_guild_id is always main. More go into Config.Guilds, each with its own roles and channels.
  • A role knows its guild: HasRole(source, 'lspd-officer') asks the LSPD guild, AddRole gives the role there.
  • Discovered guilds are named after their Discord name. Their roles are reached as 'lsmd/Doctor'.
  • Bare names only search the guilds you configured, so a server the bot was merely invited to can never grant "Admin" on yours.
Config.Guilds = {
  staff = '123456789012345678',
  lspd = {
    id = '123456789012345678',
    roles = {
      ['lspd-officer'] = '123456789012345678',
      ['lspd-chief'] = '123456789012345678',
    },
    channels = { ['lspd-radio'] = '123456789012345678' },
  },
}

-- a list may mix guilds: each role is checked where it lives
Discord.HasAnyRole(source, { 'mod', 'lspd-officer' })

Security

The bot token stays on the server, and no player can make the bot do anything.

ConcernHow it's handled
Bot tokenRead from a convar on the server and never sent anywhere else. Use set, never setr
Client eventsThe only net event is a client asking for its own profile
WebhooksOnly urls on Discord's own hosts are accepted
MentionsOff by default. EscapeMarkdown makes player text inert: no formatting, mentions or links
Other resourcesEvery resource on your server can call the exports. Give the bot only the Discord permissions you actually use
  • Rate limits: one queue per route, waits when a bucket is empty, retries 429 and 5xx with backoff.
  • Few requests: guilds, roles, channels and emojis live in memory. Identical lookups at the same time share one request.
  • Tests run in plain Lua 5.4 and Node 22 against a fake Discord, no FiveM needed.

Set it up

Compatibility

No framework, no database, no other resource needed. A framework only adds job roles, detected by its events.

FrameworkWhat np_discord uses it for
es_extendedJob and grade to Discord role (Config.JobRoles)
qbx_coreJob and grade to Discord role
qb-coreJob and grade to Discord role
StandaloneEverything else: every export, logs, the whitelist, the chat bridge, the status message, slash commands and rich presence
NeedsFor
FiveM serverLua 5.4
Discord botAn application with a bot user that is on your Discord server
Node 22 runtimeOnly for the gateway: slash commands, live updates, Discord to game chat, the bot activity
np_adminOptional: 40 of the settings live in its settings panel
chatOptional: the chat bridge and the chat log
baseeventsOptional: the death log

Installation

On start the console shows ready as <bot> in "<server>", or what is missing.

  1. Create the bot in the Discord developer portal: New Application, Bot, Reset Token. Under Privileged Gateway Intents switch on Server Members Intent and, for the chat bridge, Message Content Intent.
  2. Invite it to every guild you configure with the scopes bot and applications.commands, and only the permissions you need: Manage Roles, Manage Nicknames, Kick, Ban and Moderate Members, Move Members, Manage Channels, Manage Webhooks, Send Messages. Drag the bot's role above every role it should hand out, or Discord refuses with 50013 Missing Permissions.
  3. Copy np_discord into your resources and add it to server.cfg:
    set discord_bot_token "YOUR-BOT-TOKEN"   # set, never setr
    set discord_guild_id "123456789012345678"
    
    # optional, one per log channel
    set discord_webhook_joins "https://discord.com/api/webhooks/…"
    
    ensure np_discord   # before the resources that use it
  4. Name your roles and channels in config.lua (Config.Roles, Config.Channels) and switch on what you need.

Configuration

config.lua stays on the server; only Config.Presence is sent to clients. Tokens and webhook urls go in server.cfg.

KeyDefaultWhat
Roles / ChannelsemptyNames for the ids you use all the time
GuildsemptyNames for more guilds, each with its own roles and channels
DiscoveryonRead every guild the bot is in, track up to 10
Cachemember 120 sHow long results are reused (1800 s while the gateway reports member changes)
Sync.interval5Without the gateway: re-check one online player every N seconds
Http15000 ms, 3 retriesRequest timeout, retries and queue size
LogsonLog channels, batching and the built-in logs
KeyDefaultWhat
ConnectoffThe whitelist
ChatoffIn-game chat and a Discord channel
StatusoffStatus message and the bot's activity line
GatewayoffThe live connection and its intents
JobRolesoffJob and grade to Discord role
PresenceoffClient rich presence: app id, art, text, buttons
DebugfalseLog every request and gateway event

With np_admin running, 40 of these settings can be changed in its settings panel. The whitelist and most log, chat, status and job role settings apply at once; the gateway and switching features on or off after a restart, presence on the next join. Tokens, webhook urls and the id maps stay in server.cfg and config.lua.

For your own scripts

Every function is a server export. With server_script '@np_discord/init.lua' in your manifest, Discord.X(...) is exports.np_discord:X(...).

RegisterCommand('duty', function(source)
  if not Discord.HasAnyRole(source, { 'police', 'ems' }) then return end
  Discord.AddRole(source, 'on-duty', 'Went on duty ingame')
  Discord.SetNickname(source, '[LSPD] ' .. GetPlayerName(source))
end)

-- result, err: with an err Discord could not be asked,
-- without one `false` simply means "no"
local member, err = Discord.GetMember(source)
if err then print(err.message) elseif not member then print('not on our Discord') end

-- throwaway accounts
if Discord.GetAccountAge(source) < 7 * 86400 then
  DropPlayer(source, 'Your Discord account is too new.')
end

-- roles changed on Discord while the player is online
AddEventHandler('np_discord:playerRolesChanged', function(source, roles, added, removed)
  print(('%s gained %d and lost %d roles'):format(GetPlayerName(source), #added, #removed))
end)
-- client: the player's own profile, for display
local profile = exports.np_discord:GetProfile()
SendNUIMessage({ avatar = profile.avatar, name = profile.displayName })
exports.np_discord:SetPresence('Robbing the Pacific Standard', 600)
  • Functions that talk to Discord wait for the answer, so call them from an event handler, a command or a thread.
  • Anything there is no function for: Discord.Request('GET', 'guilds/…/onboarding').

Questions

Does it need a framework?

No. np_discord runs standalone, without a database or another resource. With es_extended, qb-core or qbx_core running, Config.JobRoles turns jobs and grades into Discord roles; the framework is detected by its events.

Do I need the gateway?

Only for slash commands and buttons, role changes in real time, live voice states, Discord to game chat and the bot's activity line. It needs a server artifact with the Node 22 runtime. Everything else works without it, and a poll picks up role changes instead.

Can a player make the bot ping @everyone?

No. Mentions are off unless a message asks for them, and EscapeMarkdown makes player text inert. Text is cut to Discord's limits instead of being rejected.

Where does the bot token go?

In server.cfg with set discord_bot_token. Never setr, which would send it to every client. Webhook urls go into convars too, not into files.

Does it have in-game permissions?

No, and no ACE. Your scripts decide who may do what, often with HasRole. Every resource on your server can call the exports, so give the bot only the Discord permissions you use.

What can't it do?

Read a user's e-mail address, which needs an OAuth2 login, and upload binary files, because FiveM's HTTP client is text only. Text files such as logs and JSON work.

Works well with

One bot token, every script on Discord.

Every export, the events and the configuration are in the docs.

Read the docs