Skip to content

Exports ​

Every export of np_discord, grouped like docs/API.md in the resource (which its test suite checks against the code). Server exports are called as exports.np_discord:HasRole(source, 'police'); with server_script '@np_discord/init.lua' in your manifest you can write Discord.HasRole(source, 'police') instead. Events are on Events.

server everything except Client exports.

Conventions ​

Result result on success; on failure a falsy first value and err as the second: local ok, err = …; if err then. err = { code, message, status }: status is the HTTP status, code is Discord's JSON error code (50013 = missing permissions, 10007 = unknown member …) or one of no_token, no_guild, no_discord, invalid_user, invalid_role, invalid_channel, invalid_guild, ambiguous_role, ambiguous_channel, ambiguous_guild, mixed_guilds, invalid_webhook, network, queue_full, no_gateway.
"No" is not an error Lookups that can legitimately find nothing return false without an err (not a member, not banned, not in voice, no role with that name). With an err the answer is "could not find out". Either way the first value is falsy, so if HasRole(src, 'police') then is safe.
user a player source (source), a Discord user id ('175928847299117063'), 'discord:<id>', or a user / member object.
role a name from the config (Config.Roles or a guild's roles), a role id, the role's name on Discord (any case, or as a slug: 'LSPD Officer' = 'lspd-officer'), or 'guild/name' ('lsmd/Doctor').
channel a name from the config (Config.Channels or a guild's channels), a channel id, the channel's name on Discord, or 'guild/name'.
guild? always the last argument and optional: 'main', a name from Config.Guilds, the name of a discovered guild (see GetBotGuilds), its name on Discord, or a guild id. Left out, the guild follows from the role or channel (see Several guilds), otherwise it is the main guild from discord_guild_id.
reason? shown in the Discord audit log.
Threads Functions that talk to Discord yield. Call them from an event handler, a command or CreateThread, not from the top level of a file.
Ids Discord ids are strings. As numbers they lose precision.
Explicit null Use { __null = true } where Discord wants null in a raw body (ModifyMember, Request).

Rate limits are handled for you: requests queue per route, wait when a bucket is empty and are retried on 429 / 5xx.

Guilds, roles and caching ​

How discovery, names and caching work: Guilds & discovery.

Export Returns
GetBotGuilds() { { id, name, label, icon, owner, tracked, available } } Every guild the bot is in. name is what you pass as guild, label its name on Discord. No request.
GetAllRoles() roles Every role of every tracked guild, each with guild_id, highest first. From memory.
RefreshGuilds(guild?) true Re-read the guild list and roles / channels (of one guild, or all) from Discord now.
IsReady() boolean The start-up load is done (see np_discord:ready).

Several guilds ​

How roles and channels find their guild: Guilds & discovery → Several guilds.

Export Returns
GetGuilds() { { id, name, label } } Every tracked guild (main, Config.Guilds, discovered), main first. No request.
GetGuildName(guildId) name | false 'main', a Config.Guilds name or the discovered name; false for a guild the bot is not in.
GetMemberRolesByGuild(user) { [guild name] = role ids | false } false = not a member there. Fails as a whole if one guild cannot be asked.
GetMemberGuilds(user) names Tracked guilds the user is a member of.
GetPlayersInGuild(guild?) sources Online players that are members of the guild. No request.

Players ​

No request is made by these unless noted. See Members & roles → Players.

Export Returns
GetDiscordId(user) id Discord id of a player. nil, err (no_discord) when the player has no Discord linked.
GetPlayerByDiscordId(user) source | false The online player that belongs to a Discord account.
GetPlayerProfile(src) profile { linked, id, member, username, displayName, avatar, roles, roleNames, roleInfo, guilds, boosting } as synced on join. roleNames holds every name a held role answers to (config name, lower-case Discord name, 'guild/name'), roleInfo the role badges ({ id, name, colour, guild, position, icon, emoji }). member, the name and avatar refer to the main guild.
GetPlayersWithRole(role, guild?) sources Online players holding the role, in whichever guild it lives.
SyncPlayer(src) profile Re-reads the player's roles from Discord now and fires the change events.
CheckWhitelist(src) boolean, message Runs the Config.Connect checks by hand.

Members ​

Export Returns
GetMember(user, guild?) member | false Cached. false = not in the guild.
RefreshMember(user, guild?) member | false Same, skipping the cache.
IsMember(user, guild?) boolean
GetMemberRoles(user, guild?) role ids Empty for non-members.
GetMemberRoleObjects(user, guild?) roles Full role objects, highest first.
GetHighestRole(user, guild?) role | false
HasRole(user, role, guild?) boolean
HasAnyRole(user, roles, guild?) boolean
HasAllRoles(user, roles, guild?) boolean
AddRole(user, role, reason?, guild?) true
RemoveRole(user, role, reason?, guild?) true
SetRoles(user, roles, reason?, guild?) member Replaces all roles of one guild in one request.
SetNickname(user, nickname, reason?, guild?) member nil / '' resets it. Cut to 32 characters.
ModifyMember(user, data, reason?, guild?) member Raw PATCH: nick, roles, mute, deaf, channel_id, communication_disabled_until.
GetJoinedAt(user, guild?) unix | false
IsBoosting(user, guild?) unix | false Since when the member boosts.
GetMemberPermissions(user, channel?, guild?) bitfield string With channel, overwrites are applied.
HasPermission(user, permission, channel?, guild?) boolean permission: 'BAN_MEMBERS' or a list of names.
ListMembers(opts?, guild?) members opts = { limit ≤ 1000, after }. Needs the Server Members intent.
GetAllMembers(max?, guild?) members Paged, max defaults to 10000. Needs the Server Members intent.
GetMembersWithRole(role, max?, guild?) members Walks the member list: use GetPlayersWithRole for online players.
SearchMembers(query, limit?, guild?) members Username / nickname starts with query.

Moderation ​

Export Returns
Timeout(user, seconds, reason?, guild?) member Max 28 days. 0 removes it.
RemoveTimeout(user, reason?, guild?) member
IsTimedOut(user, guild?) unix | false When the timeout ends.
Kick(user, reason?, guild?) true
Ban(user, opts?, guild?) true opts: a reason string or { reason, deleteMessageSeconds } (max 7 days).
Unban(user, reason?, guild?) true
GetBan(user, guild?) ban | false { reason, user }
IsBanned(user, guild?) boolean
GetBans(opts?, guild?) bans opts = { limit ≤ 1000, before, after }
BulkBan(users, opts?, guild?) { banned_users, failed_users } Up to 200 users.
GetAuditLog(opts?, guild?) audit log opts = { user, actionType, before, after, limit }

Voice ​

Export Returns
GetVoiceState(user, guild?) state | false { channel_id, mute, deaf, self_mute, self_deaf, self_stream … }. Live from the gateway when connected.
GetVoiceChannel(user, guild?) channel id | false
MoveMember(user, channel, reason?, guild?) member The member has to be in a voice channel already.
DisconnectMember(user, reason?, guild?) member
MuteMember(user, muted?, reason?, guild?) member Server mute. false unmutes.
DeafenMember(user, deafened?, reason?, guild?) member

Users ​

Export Returns
GetUser(user) user Global user object, cached.
GetUsername(user) string
GetDisplayName(user, guild?) string Server nickname, else global display name, else username.
GetAvatar(user, opts?, guild?) url Server avatar, else user avatar, else the default one. opts = { size, format, animated, global }
GetBanner(user, opts?) url | false
GetCreatedAt(user) unix Read from the id, no request.
GetAccountAge(user) seconds No request.
CreateDM(user) channel
SendDM(user, message) message Fails with code 50007 when the user blocks DMs.
GetBotUser() user The bot itself.

Guild ​

Export Returns
GetGuild(guild?) guild Includes approximate_member_count / approximate_presence_count. Cached.
GetMemberCount(guild?) number
GetOnlineMemberCount(guild?) number
GetBoostCount(guild?) boosts, tier
GetGuildIcon(opts?, guild?) url | false
GetVanityUrl(guild?) { code, uses }
ModifyGuild(data, reason?, guild?) guild
GetGuildId(guild?) id Resolves a Config.Guilds name. No request.

Roles ​

Export Returns
GetGuildRoles(guild?) roles Cached.
GetRoles(guild?) roles Same as GetGuildRoles.
GetRole(role, guild?) role | false
GetRoleByName(name, guild?) role, guild id | false Case-insensitive. Without guild main + Config.Guilds are searched.
ResolveRole(role, guild?) id, guild id Name / id → id and the guild it belongs to.
CreateRole(data, reason?, guild?) role { name, colour, hoist, mentionable, permissions = { 'KICK_MEMBERS' }, icon, unicode_emoji }
EditRole(role, data, reason?, guild?) role
DeleteRole(role, reason?, guild?) true
SetRolePositions(positions, reason?, guild?) roles { [role] = position }

Channels and threads ​

Export Returns
GetChannels(guild?) channels Cached.
GetChannel(channel, guild?) channel
GetChannelByName(name, kind?, guild?) channel | false kind: 'text', 'voice', 'category' … Without guild main + Config.Guilds are searched.
ResolveChannel(channel, guild?) id, guild id Name / id → id; the guild is nil for an id from a guild nobody has looked at.
CreateChannel(data, reason?, guild?) channel { name, type = 'text' | 'voice' | 'category' | 'announcement' | 'stage' | 'forum', parent, topic, nsfw, position, user_limit, bitrate, rate_limit_per_user, permissions }
EditChannel(channel, data, reason?, guild?) channel Same keys. parent = false moves it out of its category.
DeleteChannel(channel, reason?, guild?) channel
SetChannelPermission(channel, entry, reason?, guild?) true { id = role | user | 'everyone', type = 'role' | 'member', allow = { … }, deny = { … } }
DeleteChannelPermission(channel, target, reason?, guild?) true
TriggerTyping(channel, guild?) true
StartThread(channel, data, reason?, guild?) thread { name, autoArchive, private, message = id to branch from }
CreateForumPost(channel, data, reason?, guild?) thread { name, message, tags }
ArchiveThread(thread, locked?, reason?) thread
AddThreadMember(thread, user) true
RemoveThreadMember(thread, user) true
GetActiveThreads(guild?) threads

Messages ​

Message shapes, limits and mentions: Messages & channels.

Export Returns
SendMessage(channel, message, guild?) message
SendEmbed(channel, embed, guild?) message
EditMessage(channel, messageId, message, guild?) message
DeleteMessage(channel, messageId, reason?, guild?) true
BulkDeleteMessages(channel, messageIds, reason?, guild?) true 2 – 100 messages, none older than 14 days.
GetMessage(channel, messageId, guild?) message
GetMessages(channel, opts?, guild?) messages opts = { limit ≤ 100, before, after, around }, newest first.
CrosspostMessage(channel, messageId, guild?) message Publishes an announcement.
PinMessage(channel, messageId, reason?, guild?) true
UnpinMessage(channel, messageId, reason?, guild?) true
GetPinnedMessages(channel, guild?) messages
AddReaction(channel, messageId, emoji, guild?) true '👍', 'name:id' or '<:name:id>'
RemoveReaction(channel, messageId, emoji, user?, guild?) true Without user: the bot's own.
ClearReactions(channel, messageId, emoji?, guild?) true
GetReactions(channel, messageId, emoji, opts?, guild?) users

Webhooks ​

webhook is a webhook url or { id, token }. Only Discord's own hosts are accepted. Webhook calls do not use the bot token.

Export Returns
ExecuteWebhook(webhook, message, opts?) true | message opts = { wait, thread, username, avatar }; wait = true returns the message.
EditWebhookMessage(webhook, messageId, message, opts?) message
DeleteWebhookMessage(webhook, messageId, opts?) true
CreateWebhook(channel, name, avatar?, reason?, guild?) webhook Includes url. Treat it like a password.
GetChannelWebhooks(channel, guild?) webhooks
GetGuildWebhooks(guild?) webhooks
EditWebhook(webhookId, data, reason?) webhook
DeleteWebhook(webhookId, reason?) true

Logs ​

entry is a string, an embed (player = source adds the player field) or a full message. See Webhooks & logs.

Export Returns
Log(channel, entry) true Queued, returns at once. channel is a log name (Config.Logs.channels, convar discord_webhook_<name>) or a Config.Channels name.

Invites ​

Export Returns
CreateInvite(channel, opts?, guild?) invite opts = { maxAge = 86400, maxUses = 0, temporary, unique, reason }. Has code and url.
GetInvite(code) invite Code or full link. With member counts.
DeleteInvite(code, reason?) invite
GetGuildInvites(guild?) invites
GetChannelInvites(channel, guild?) invites

Scheduled events ​

Export Returns
GetScheduledEvents(guild?) events
GetScheduledEvent(eventId, guild?) event
CreateScheduledEvent(data, reason?, guild?) event { name, description, start, finish, location = 'Legion Square' } or channel = voice channel. Times are unix seconds or ISO strings.
EditScheduledEvent(eventId, data, reason?, guild?) event status: 2 start, 3 end, 4 cancel.
DeleteScheduledEvent(eventId, guild?) true
GetScheduledEventUsers(eventId, opts?, guild?) users Who is interested.

Emojis ​

Export Returns
GetEmojis(guild?) emojis Cached.
GetEmoji(name, guild?) '<:name:id>', emoji | false Ready to paste into a message.
CreateEmoji(name, image, reason?, guild?) emoji image is a data uri.
DeleteEmoji(emojiId, reason?, guild?) true

Slash commands and components ​

Needs Config.Gateway.enabled. Handlers get (interaction, argument, source). See Slash commands & interactions.

Export Returns
RegisterCommand(def, handler) true def = { name, description, options, permissions, guild | guilds | global, contexts }; guilds = 'all' = every configured guild. contexts (global only): { 'guild', 'dm', 'private' }, { 'dm' } = only in DMs with the bot. Sent to Discord only when it changed.
UnregisterCommand(name) true Also removes it from Discord, in every guild it was registered in.
OnComponent(prefix, handler) true Buttons / selects whose custom_id starts with prefix. argument = selected values.
OnModal(prefix, handler) true argument = { [field id] = text }
OnAutocomplete(command, handler) true argument = { name, value } of the focused option. Return up to 25 choices.
InteractionReply(interaction, message, ephemeral?) true A second call sends a follow-up.
InteractionDefer(interaction, ephemeral?) true "Thinking…", then InteractionEdit.
InteractionEdit(interaction, message) message Edits the original reply.
InteractionFollowup(interaction, message, ephemeral?) message
InteractionDelete(interaction) true
InteractionUpdate(interaction, message) true Components: change the message the button is on.
InteractionDeferUpdate(interaction) true Components: acknowledge only.
InteractionModal(interaction, modal) true { id, title, fields = { { id, label, style = 'short' | 'paragraph', required, value, placeholder, min, max } } }
InteractionAutocomplete(interaction, choices) true

Gateway and bot ​

Export Returns
IsGatewayConnected() boolean
HasIntent(intent) boolean Config.Gateway.intents asks for it ('DIRECT_MESSAGES' …). false with the gateway off.
SetBotActivity(text, kind?, status?) true kind: playing watching listening competing custom. status: online idle dnd invisible.

Helpers ​

No request is made by any of these.

Export Returns
Timestamp(unix?, style?) '<t:…>' Styles t T d D f F R (R = "3 minutes ago").
SnowflakeTime(id) unix When an id was created.
Colour(value) number
EscapeMarkdown(text) string Makes player text inert (no formatting, mentions or links).
MentionUser(user) '<@id>'
MentionRole(role, guild?) '<@&id>'
MentionChannel(channel, guild?) '<#id>'
PermissionBits(permissions) bitfield string From a name or a list of names.
PermissionNames(bits) names
Request(method, path, body?, opts?) body Any endpoint this resource has no function for. opts = { query, reason, files, auth }
GetStats() { requests, retries, rateLimited, pending, gateway, cache, registry } cache = { hits, misses, entries }, registry = { guilds, tracked, live, discovered }
ClearCache(prefix?) true 'member:', 'user:', 'roles:', 'channels:', 'guild:', 'emojis:' or everything.

Client exports ​

client

The client only knows its own profile, and only for display. See Client.

Export Returns
GetProfile() profile { linked, id, member, username, displayName, avatar, roles, roleNames, roleInfo, guilds, boosting }
IsLoaded() boolean
GetDiscordId() id
GetAvatar() url
GetDisplayName() string
IsMember(guild) boolean Without guild the main guild.
GetRoles(guild) role ids Without guild every guild in one list.
GetGuilds() names Tracked guilds the player is a member of.
GetRoleInfo() badges { { id, name, colour, guild, position, icon, emoji } } of the player's roles, for a UI.
HasRole(role) boolean Config name, Discord name (any case; main + Config.Guilds), 'guild/name' or id.
HasAnyRole(roles) boolean
SetPresence(text, seconds?) Overrides the rich presence text.
ResetPresence()

Client event: np_discord:profile (profile), sent on join and whenever the roles change.