Example resources
Nine complete resources to download, start and learn from.
Developer Preview. Scripting is live on Neighborly servers – everything on these pages works today. The API is young, so tell us what you need next on Discord.
Every resource on this page is complete – download it as a ZIP, drop it into your server and start it. Each one shows a different part of the platform, and they all follow the rules from Best practices. The first three are short and made for learning; the others are bigger, real-world resources. Read State bags and Client ↔ server data alongside them.
resources foldernb_welcome · Events, ChatA shared lot counternb_lotcounter · GlobalState, State handlersPlayer statusnb_status · Player state, Client writesA /dice commandnb_dice · Commands, ChatA doorbell that notifies the ownernb_doorbell · Lot owners, SoundsA live player listnb_scoreboard · GlobalState, State handlersA café job with paymentnb_cafe · Context menus, Progress barsA savings banknb_bank · Server callbacks, Client callbacksA phone bank appnb_phone · NUI, Key mappingInstalling an example
- Download and unzipEvery ZIP contains one folder named after the resource. Put it into your server's
resourcesfolder, for exampleresources/[examples]/nb_bank. - ConfigureResources with a
config.luakeep every setting there, and theREADME.mdin each ZIP explains them. Set lot ids and object names for your world. - Start itRun
refreshandensure nb_bankin the server console, or add the name toresourcesinserver.json.
A welcome message
nb_welcomeThe friendliest first resource: when a player's Sim arrives, they get a welcome toast – first-timers also a subtitle – and everyone else reads in chat who just arrived or left. Returning players see how many times they have visited.
- The client waits for
playerSpawnedorlotEnteredand tells the server it is ready. The server answers withTriggerClientEvent. - Visits are counted per Neighborly account with
SetResourceKvpInt, so they survive restarts and name changes. - Texts live in a
shared_scriptsconfig, so server owners can translate them without touching code.
Files
nb_welcome/
├── resource.toml
├── config.lua
├── client.lua
├── server.lua
└── README.mdSource · 5 files
resource.tomlTOML · 10 lines
name = "nb_welcome"
version = "1.0.0"
author = "Neighborly"
description = "Greets players when they arrive and tells everyone who joined"
shared_scripts = ["config.lua"]
client_scripts = ["client.lua"]
server_scripts = ["server.lua"]
dependencies = ["neighborly", "chat"]config.luaLUA · 9 lines
Config = {
Neighborhood = 'our neighborhood',
FirstVisit = 'Welcome to %s, %s! Type /help in chat to see what you can do.',
ReturnVisit = 'Welcome back, %s! This is visit number %d.',
Joined = '%s just moved into the neighborhood for the first time!',
Returned = '%s is back in the neighborhood.',
Left = '%s left the neighborhood.',
ChatColor = { 91, 192, 248 }
}client.luaLUA · 24 lines
local announced = false
local function ready()
if announced then
return
end
announced = true
TriggerServerEvent('nb_welcome:ready')
end
AddEventHandler('playerSpawned', ready)
AddEventHandler('lotEntered', ready)
RegisterNetEvent('nb_welcome:greet', function(text, first)
exports.neighborly:notify({
title = first and 'Welcome!' or 'Welcome back!',
text = text,
type = 'success',
duration = 8000
})
if first then
ShowSubtitle(text, 6000)
end
end)server.luaLUA · 36 lines
local greeted = {}
local function visitKey(player)
return 'visits:' .. GetPlayerAccountId(player)
end
RegisterNetEvent('nb_welcome:ready', function()
local src = source
if greeted[src] then
return
end
greeted[src] = true
local name = GetPlayerName(src)
local visits = GetResourceKvpInt(visitKey(src)) + 1
SetResourceKvpInt(visitKey(src), visits)
local first = visits == 1
local text = first and Config.FirstVisit:format(Config.Neighborhood, name) or Config.ReturnVisit:format(name, visits)
TriggerClientEvent('nb_welcome:greet', src, text, first)
local news = (first and Config.Joined or Config.Returned):format(name)
for _, player in ipairs(GetPlayers()) do
if player ~= src then
SendChatMessage(player, 'Neighborly', news, Config.ChatColor)
end
end
end)
AddEventHandler('playerDropped', function()
local src = source
if greeted[src] then
SendChatMessage(-1, 'Neighborly', Config.Left:format(GetPlayerName(src) or 'Someone'), Config.ChatColor)
end
greeted[src] = nil
end)README.mdMD · 19 lines
# nb_welcome
Greets every player when their Sim arrives in the world. First-time visitors get a welcome toast and a subtitle, returning players see how often they have visited, and everyone else reads in chat who just arrived or left.
## Install
1. Put the `nb_welcome` folder into your server's `resources` folder.
2. Change the texts and the neighborhood name in `config.lua`.
3. Add `"nb_welcome"` to `resources` in `server.json`, or run `refresh` and `ensure nb_welcome` in the console.
## What it shows
- A `shared_scripts` config file used on both sides
- Built-in events: `playerSpawned` and `lotEntered` on the client, `playerDropped` on the server
- A client → server event (`TriggerServerEvent`) answered with a server → client event (`TriggerClientEvent`)
- Saving a visit counter per account with `SetResourceKvpInt` and `GetPlayerAccountId`
- Chat messages with `SendChatMessage` and toasts with `exports.neighborly:notify`
Docs: https://neighborlymp.com/docs/dev/examples#nb_welcomeA shared lot counter (GlobalState)
nb_lotcounterEvery lot counts its visits. Arriving players see the count, and everyone already on the lot sees it go up. /toplots lists the busiest lots of the neighborhood.
- The server is the only writer: the server-side
lotEnteredevent says who arrived where, and a per-player cooldown stops visit farming. - All counts live in one table in
GlobalState.nb_lotcounter. Late joiners get it before their client scripts run. - Change handlers run just before the new value is stored – the client compares the new table with
GlobalStateto see whether its own lot changed. - Counts are saved with
SetResourceKvpevery 30 seconds and when the resource stops.
Files
nb_lotcounter/
├── resource.toml
├── config.lua
├── client.lua
├── server.lua
└── README.mdSource · 5 files
resource.tomlTOML · 10 lines
name = "nb_lotcounter"
version = "1.0.0"
author = "Neighborly"
description = "Counts visits on every lot and shows the count to everyone there"
shared_scripts = ["config.lua"]
client_scripts = ["client.lua"]
server_scripts = ["server.lua"]
dependencies = ["neighborly"]config.luaLUA · 6 lines
Config = {
RevisitMinutes = 30,
ShowSeconds = 8,
SaveEverySeconds = 30,
TopCount = 5
}client.luaLUA · 36 lines
local shownFor = nil
local hideTimer = nil
local function show(zoneId)
local counts = GlobalState.nb_lotcounter or {}
local visits = counts[zoneId]
if not visits then
return
end
exports.neighborly:showTextUI(('%s · %d visits'):format(GetLotName(zoneId) or 'This lot', visits), { icon = 'home' })
shownFor = zoneId
if hideTimer then
ClearTimeout(hideTimer)
end
hideTimer = SetTimeout(Config.ShowSeconds * 1000, function()
exports.neighborly:hideTextUI()
shownFor = nil
hideTimer = nil
end)
end
AddEventHandler('lotEntered', function(zoneId)
show(zoneId)
end)
AddStateBagChangeHandler('nb_lotcounter', 'global', function(bagName, key, counts)
local zoneId = GetCurrentLot()
local before = GlobalState.nb_lotcounter or {}
if zoneId and counts and counts[zoneId] ~= before[zoneId] then
SetTimeout(0, function()
show(zoneId)
end)
end
end)
TriggerEvent('chat:addSuggestion', '/toplots', 'Show the busiest lots of the neighborhood')server.luaLUA · 56 lines
local counts = GetResourceKvp('counts') or {}
local lastVisit = {}
local dirty = false
GlobalState:set('nb_lotcounter', counts, true)
local function save()
if dirty then
SetResourceKvp('counts', counts)
dirty = false
end
end
AddEventHandler('lotEntered', function(zoneId)
local src = source
local key = GetPlayerAccountId(src) .. '@' .. zoneId
local now = os.time()
if lastVisit[key] and now - lastVisit[key] < Config.RevisitMinutes * 60 then
return
end
lastVisit[key] = now
counts[zoneId] = (counts[zoneId] or 0) + 1
dirty = true
GlobalState.nb_lotcounter = counts
end)
RegisterCommand('toplots', function(source)
local list = {}
for zoneId, visits in pairs(counts) do
list[#list + 1] = { zoneId = zoneId, visits = visits }
end
table.sort(list, function(a, b) return a.visits > b.visits end)
local lines = {}
for i = 1, math.min(Config.TopCount, #list) do
lines[#lines + 1] = ('%d. %s – %d visits'):format(i, GetLotName(list[i].zoneId) or list[i].zoneId, list[i].visits)
end
local text = #lines > 0 and table.concat(lines, ' · ') or 'No visits yet.'
if source == 0 then
print(text)
else
SendChatMessage(source, 'Busiest lots', text)
end
end, false)
CreateThread(function()
while true do
Wait(Config.SaveEverySeconds * 1000)
save()
end
end)
AddEventHandler('onResourceStop', function(name)
if name == GetCurrentResourceName() then
save()
end
end)README.mdMD · 21 lines
# nb_lotcounter
Counts how many visits every lot gets and shows the number to everyone who arrives – and to everyone already there when someone new walks in. `/toplots` lists the busiest lots. The counts survive restarts.
## Install
1. Put the `nb_lotcounter` folder into your server's `resources` folder.
2. Adjust the revisit cooldown and display time in `config.lua`.
3. Add `"nb_lotcounter"` to `resources` in `server.json`, or run `refresh` and `ensure nb_lotcounter`.
## How the data gets to players
The server keeps one table of counts, `{ [zoneId] = visits }`, and publishes it in `GlobalState.nb_lotcounter`. GlobalState replicates to every client, and players who join later receive the current table before their client scripts run.
The server is the only one that changes it: the server-side `lotEntered` event tells it who arrived where, and a per-player cooldown stops anyone from farming visits by walking back and forth. Clients only read the table – once when they arrive, then in `AddStateBagChangeHandler('nb_lotcounter', 'global', ...)`.
Change handlers run just before the new value is stored, so the client compares the new table with `GlobalState.nb_lotcounter` (still the old one) to see whether its own lot changed.
The whole table is assigned again after every change (`GlobalState.nb_lotcounter = counts`). Changing a field of a table you read from a state bag never replicates.
Docs: https://neighborlymp.com/docs/dev/examples#nb_lotcounterPlayer status (player state bags)
nb_statusEveryone gets a status – Available, Busy, Looking for friends, In roleplay or Away – plus an optional short note. /who lists everyone online, and players on your lot hear when you start looking for friends.
/statusgoes through the server, which validates the value and a cooldown before writingPlayer(src).state.nb_status./notewritesLocalPlayer.state.nb_notestraight from the client – clients may write their own player bag. The server watches the key and clears notes that break the rules./whoneeds no request: every player bag already replicates to every client.
Files
nb_status/
├── resource.toml
├── config.lua
├── client.lua
├── server.lua
└── README.mdSource · 5 files
resource.tomlTOML · 10 lines
name = "nb_status"
version = "1.0.0"
author = "Neighborly"
description = "Per-player status (available, busy, looking for friends) in player state bags"
shared_scripts = ["config.lua"]
client_scripts = ["client.lua"]
server_scripts = ["server.lua"]
dependencies = ["neighborly", "chat"]config.luaLUA · 12 lines
Config = {
Statuses = {
available = { label = 'Available', color = { 61, 220, 151 } },
busy = { label = 'Busy', color = { 255, 179, 71 } },
lfg = { label = 'Looking for friends', color = { 91, 192, 248 } },
roleplay = { label = 'In roleplay', color = { 195, 178, 255 } },
afk = { label = 'Away', color = { 160, 170, 190 } }
},
Default = 'available',
NoteLength = 60,
CooldownSeconds = 5
}client.luaLUA · 57 lines
local function statusOf(player)
local id = Player(player).state.nb_status
return Config.Statuses[id or ''], id
end
RegisterCommand('status', function(_, args)
local wanted = (args[1] or ''):lower()
if not Config.Statuses[wanted] then
local names = {}
for id in pairs(Config.Statuses) do
names[#names + 1] = id
end
table.sort(names)
return AddChatMessage('Status', 'Use /status ' .. table.concat(names, '|'))
end
TriggerServerEvent('nb_status:set', wanted)
end, false)
RegisterCommand('note', function(_, args)
local text = table.concat(args, ' ')
LocalPlayer.state:set('nb_note', text ~= '' and text:sub(1, Config.NoteLength) or nil, true)
AddChatMessage('Status', text ~= '' and ('Your note: ' .. text) or 'Your note was removed.')
end, false)
RegisterCommand('who', function()
for _, player in ipairs(GetActivePlayers()) do
local status = statusOf(player)
local note = Player(player).state.nb_note
local line = (status and status.label or 'Unknown') .. (note and (' – ' .. note) or '')
AddChatMessage(GetPlayerName(player) or ('Player ' .. player), line, status and status.color or nil)
end
end, false)
AddStateBagChangeHandler('nb_status', nil, function(bagName, key, value)
local player = GetPlayerFromStateBagName(bagName)
if not player then
return
end
local status = Config.Statuses[value or '']
if player == PlayerId() then
if status then
exports.neighborly:notify({ title = 'Status', text = 'You are now: ' .. status.label, type = 'success' })
end
return
end
if value == 'lfg' and GetPlayerLot(player) == GetCurrentLot() then
exports.neighborly:notify({ title = GetPlayerName(player) or 'Someone', text = 'is looking for friends on this lot!', icon = 'heart' })
end
end)
TriggerEvent('chat:addSuggestion', '/status', 'Show others what you are up to', {
{ name = 'status', help = 'available, busy, lfg, roleplay or afk' }
})
TriggerEvent('chat:addSuggestion', '/note', 'A short note everyone sees in /who', {
{ name = 'text', help = 'Up to 60 characters, empty removes it' }
})
TriggerEvent('chat:addSuggestion', '/who', 'List everyone online with their status')server.luaLUA · 34 lines
local lastChange = {}
AddEventHandler('playerJoining', function()
Player(source).state:set('nb_status', Config.Default, true)
end)
RegisterNetEvent('nb_status:set', function(status)
local src = source
if type(status) ~= 'string' or not Config.Statuses[status] then
return
end
local now = os.time()
if lastChange[src] and now - lastChange[src] < Config.CooldownSeconds then
return TriggerClientEvent('neighborly:notify', src, { text = 'Wait a moment before changing your status again.', type = 'warning' })
end
lastChange[src] = now
Player(src).state:set('nb_status', status, true)
end)
AddStateBagChangeHandler('nb_note', nil, function(bagName, key, value)
local player = GetPlayerFromStateBagName(bagName)
if not player or value == nil then
return
end
if type(value) ~= 'string' or #value > Config.NoteLength then
SetTimeout(0, function()
Player(player).state:set('nb_note', nil, true)
end)
end
end)
AddEventHandler('playerDropped', function()
lastChange[source] = nil
end)README.mdMD · 19 lines
# nb_status
Every player gets a status everyone can see: Available, Busy, Looking for friends, In roleplay or Away. `/status lfg` changes yours, `/note Heading to the café` adds a short note, and `/who` lists everyone online with their status and note. Players on your lot get a heads-up when someone there starts looking for friends.
## Install
1. Put the `nb_status` folder into your server's `resources` folder.
2. Add or rename statuses in `config.lua`.
3. Add `"nb_status"` to `resources` in `server.json`, or run `refresh` and `ensure nb_status`.
## Two ways to write a player state bag
**Through the server** – `/status` sends an event, the server checks the value and a cooldown, and writes `Player(src).state:set('nb_status', status, true)`. Use this for anything other players rely on.
**From the client** – `/note` writes `LocalPlayer.state:set('nb_note', text, true)` directly. Clients may write their own player bag (and only their own); the server passes the value on to everyone. Because the server can't stop such a write, it watches the key with `AddStateBagChangeHandler` and clears notes that break the rules. Server owners can turn client writes off completely with `"stateBagStrictMode": true` in `server.json`.
Every player's bag replicates to everyone, so `/who` simply reads `Player(id).state` for each player – no request to the server needed. Players who join later receive every bag before their scripts start.
Docs: https://neighborlymp.com/docs/dev/examples#nb_statusA /dice command
nb_diceThe smallest useful game: /dice 20 rolls a twenty-sided die. Everyone on the same lot sees the result in chat, and a perfect roll gets a little notification. The server picks the number, so nobody can cheat.
Files
nb_dice/
├── resource.toml
├── client.lua
├── server.lua
└── README.mdSource · 4 files
resource.tomlTOML · 9 lines
name = "nb_dice"
version = "1.0.0"
author = "Neighborly"
description = "Roll dice for everyone on your lot"
client_scripts = ["client.lua"]
server_scripts = ["server.lua"]
dependencies = ["neighborly", "chat"]client.luaLUA · 11 lines
TriggerEvent('chat:addSuggestion', '/dice', 'Roll a die for everyone on your lot', {
{ name = 'sides', help = 'Number of sides, 2 to 100 (default 6)' }
})
RegisterNetEvent('nb_dice:perfect', function(sides)
exports.neighborly:notify({
title = 'Perfect roll!',
text = ('You rolled the highest number on a %d-sided die.'):format(sides),
type = 'success'
})
end)server.luaLUA · 32 lines
local cooldown = {}
RegisterCommand('dice', function(source, args)
if source == 0 then
return print('Only players can roll dice.')
end
local now = GetGameTimer()
if cooldown[source] and now - cooldown[source] < 5000 then
return
end
cooldown[source] = now
local sides = math.floor(tonumber(args[1]) or 6)
sides = math.max(2, math.min(sides, 100))
local roll = math.random(1, sides)
local name = GetPlayerName(source)
local zoneId = GetPlayerLot(source)
local listeners = zoneId and GetPlayersOnLot(zoneId) or { source }
for _, player in ipairs(listeners) do
SendChatMessage(player, 'Dice', ('%s rolled %d (1-%d)'):format(name, roll, sides), { 255, 209, 102 })
end
if roll == sides then
TriggerClientEvent('nb_dice:perfect', source, sides)
end
end, false)
AddEventHandler('playerDropped', function()
cooldown[source] = nil
end)README.mdMD · 17 lines
# nb_dice
`/dice` rolls a die for everyone on your lot. `/dice 20` rolls a twenty-sided one. The server picks the number, so nobody can cheat a roll, and a perfect roll gets a little notification.
## Install
1. Put the `nb_dice` folder into your server's `resources` folder.
2. Add `"nb_dice"` to `resources` in `server.json`, or run `refresh` and `ensure nb_dice` in the console.
## What it shows
- `RegisterCommand` with arguments and a per-player cooldown
- Sending chat only to players on the same lot with `GetPlayersOnLot` and `SendChatMessage`
- Chat suggestions from a client script
- A server-to-client event (`TriggerClientEvent`) answered with `exports.neighborly:notify`
Docs: https://neighborlymp.com/docs/dev/examples#nb_diceA doorbell that notifies the owner
nb_doorbellVisitors type /ring on another player's home lot. Everyone on the lot hears the chime, the owner hears it wherever they are and gets a dialog, and the visitor learns whether someone is coming to the door.
- Owners choose their doorbell sound with
/doorbell. It is stored in a lot state bag, so every visitor hears the same one. - The three sounds ship in
sounds/and reach players throughfilesin the manifest.
Files
nb_doorbell/
├── resource.toml
├── config.lua
├── client.lua
├── server.lua
├── sounds/
│ ├── birds.ogg
│ ├── chime.ogg
│ └── classic.ogg
└── README.mdSource · 8 files
resource.tomlTOML · 12 lines
name = "nb_doorbell"
version = "1.0.0"
author = "Neighborly"
description = "Ring the doorbell of any home, the owner hears it and can come to the door"
shared_scripts = ["config.lua"]
client_scripts = ["client.lua"]
server_scripts = ["server.lua"]
files = ["sounds/*.ogg"]
dependencies = ["neighborly"]
escrow_ignore = ["config.lua"]config.luaLUA · 26 lines
Config = {}
-- Chat command visitors use to ring the bell of the home they are standing on
Config.RingCommand = 'ring'
-- Chat command owners use to pick their doorbell sound
Config.SoundCommand = 'doorbell'
-- Seconds a visitor must wait before ringing again
Config.Cooldown = 20
-- Seconds the owners have to answer before the request expires
Config.AnswerSeconds = 60
-- Sound used when the owners haven't picked one
Config.DefaultSound = 'chime'
-- Sounds owners can choose from; the files live in the sounds folder and are listed in resource.toml
Config.Sounds = {
chime = 'sounds/chime.ogg',
classic = 'sounds/classic.ogg',
birds = 'sounds/birds.ogg'
}
-- Volume of the bell, from 0.0 to 1.0
Config.Volume = 0.8client.luaLUA · 38 lines
local soundNames = {}
for name in pairs(Config.Sounds) do
soundNames[#soundNames + 1] = name
end
table.sort(soundNames)
RegisterCommand(Config.RingCommand, function()
TriggerServerEvent('nb_doorbell:ring')
end, false)
RegisterCommand(Config.SoundCommand, function(source, args)
local name = args[1]
if not name or not Config.Sounds[name] then
return exports.neighborly:notify({ text = 'Pick a sound: ' .. table.concat(soundNames, ', ') })
end
PlaySoundFrontend(Config.Sounds[name], Config.Volume)
TriggerServerEvent('nb_doorbell:setSound', name)
end, false)
TriggerEvent('chat:addSuggestion', '/' .. Config.RingCommand, 'Ring the doorbell of the home you are on')
TriggerEvent('chat:addSuggestion', '/' .. Config.SoundCommand, 'Choose your doorbell sound', {
{ name = 'sound', help = table.concat(soundNames, ', ') }
})
RegisterNetEvent('nb_doorbell:sound', function(file)
PlaySoundFrontend(file, Config.Volume)
end)
RegisterNetEvent('nb_doorbell:ringing', function(visitor, name, lotName)
exports.neighborly:notify({ title = lotName, text = name .. ' is at your door.', type = 'info' })
local answer = exports.neighborly:alertDialog({
header = 'Ding dong!',
content = name .. ' rang your doorbell. Will you come to the door?',
confirmLabel = 'Coming!',
cancelLabel = 'Not now'
})
TriggerServerEvent('nb_doorbell:answer', visitor, answer == 'confirm')
end)server.luaLUA · 77 lines
local lastRing = {}
local waiting = {}
local function notify(player, data)
TriggerClientEvent('neighborly:notify', player, data)
end
RegisterNetEvent('nb_doorbell:ring', function()
local src = source
local zoneId = GetPlayerLot(src)
if not zoneId or GetLotType(zoneId) ~= 'residential' then
return notify(src, { text = 'Stand on someone\'s home lot to ring their bell.', type = 'warning' })
end
local owner = GetLotOwnerPlayer(zoneId)
if owner == src then
return notify(src, { text = 'This is your own home!' })
end
local now = os.time()
if lastRing[src] and now - lastRing[src] < Config.Cooldown then
return notify(src, { text = 'Give them a moment to answer.', type = 'warning' })
end
lastRing[src] = now
local sound = Config.Sounds[Lot(zoneId).state.doorbellSound or Config.DefaultSound] or Config.Sounds[Config.DefaultSound]
for _, player in ipairs(GetPlayersOnLot(zoneId)) do
TriggerClientEvent('nb_doorbell:sound', player, sound)
end
if not owner then
return notify(src, { text = 'Nobody seems to be home right now.' })
end
if owner ~= src and GetPlayerLot(owner) ~= zoneId then
TriggerClientEvent('nb_doorbell:sound', owner, sound)
end
waiting[owner] = waiting[owner] or {}
waiting[owner][src] = now + Config.AnswerSeconds
TriggerClientEvent('nb_doorbell:ringing', owner, src, GetPlayerName(src), GetLotName(zoneId))
notify(src, { title = GetLotName(zoneId), text = 'You rang the bell. Waiting for an answer...' })
end)
RegisterNetEvent('nb_doorbell:answer', function(visitor, accepted)
local src = source
local expires = waiting[src] and waiting[src][visitor]
if not expires then
return
end
waiting[src][visitor] = nil
if expires < os.time() or not GetPlayerName(visitor) then
return
end
if accepted then
notify(visitor, { title = 'Doorbell', text = GetPlayerName(src) .. ' is coming to the door!', type = 'success' })
else
notify(visitor, { title = 'Doorbell', text = GetPlayerName(src) .. " can't come to the door right now." })
end
end)
RegisterNetEvent('nb_doorbell:setSound', function(name)
local src = source
local zoneId = GetPlayerLot(src)
if not zoneId or GetLotOwnerPlayer(zoneId) ~= src then
return notify(src, { text = 'Go home to change your doorbell.', type = 'warning' })
end
if not Config.Sounds[name] then
return
end
Lot(zoneId).state:set('doorbellSound', name, true)
notify(src, { text = 'Your doorbell now plays ' .. name .. '.', type = 'success' })
end)
AddEventHandler('playerDropped', function()
lastRing[source] = nil
waiting[source] = nil
end)README.mdMD · 16 lines
# nb_doorbell
Visitors type `/ring` on another player's home lot to ring the doorbell. Everyone on the lot hears it, the owner hears it wherever they are and gets a dialog, and the visitor learns whether they are coming to the door. Owners pick their doorbell sound with `/doorbell chime|classic|birds`.
## Install
1. Put the `nb_doorbell` folder into your server's `resources` folder. The three sounds are in `sounds/` – replace them with your own `.ogg` files if you like.
2. Add `"nb_doorbell"` to `resources` in `server.json`, or run `refresh` and `ensure nb_doorbell`.
## What it shows
- Lot owners and lot types (`GetLotOwnerPlayer`, `GetLotType`, `GetPlayersOnLot`)
- Sounds played with `PlaySoundFrontend` from files sent to players through `files`
- A lot state bag (`Lot(zoneId).state.doorbellSound`) so every visitor hears the same sound
Docs: https://neighborlymp.com/docs/dev/examples#nb_doorbellA live player list (GlobalState + NUI)
nb_scoreboardPress Home to see everyone online with their job, the lot they are on and their ping. The server publishes the list in GlobalState; clients just read it.
- The server rebuilds the list on joins, leaves, lot changes, job changes and every few seconds, and assigns it to
GlobalState.nb_scoreboardas a whole table. - Players who join later get the current list before their client scripts start – no request needed.
- The client re-renders only while the board is visible, from
AddStateBagChangeHandler('nb_scoreboard', 'global', …). - The page has no focus, so players keep moving while it is open.
Files
nb_scoreboard/
├── resource.toml
├── config.lua
├── client.lua
├── server.lua
├── html/
│ ├── app.js
│ ├── index.html
│ └── style.css
└── README.mdSource · 8 files
resource.tomlTOML · 14 lines
name = "nb_scoreboard"
version = "1.0.0"
author = "Neighborly"
description = "Hold a key to see everyone online, their job, lot and ping"
shared_scripts = ["config.lua"]
client_scripts = ["client.lua"]
server_scripts = ["server.lua"]
ui_page = "html/index.html"
files = ["html/index.html", "html/style.css", "html/app.js"]
dependencies = ["neighborly"]
escrow_ignore = ["config.lua"]config.luaLUA · 16 lines
Config = {}
-- Title shown at the top of the player list
Config.Title = 'Sunny Bay'
-- How often pings and locations are refreshed, in seconds
Config.RefreshSeconds = 5
-- Default key that shows and hides the list (players can change it with /bind +scoreboard <key>)
Config.Key = 'HOME'
-- Show the lot each player is on
Config.ShowLocation = true
-- Show the job other resources store in Player(id).state.job
Config.ShowJob = trueclient.luaLUA · 43 lines
local visible = false
local function render()
local data = GlobalState.nb_scoreboard
if not data then
return
end
SendNUIMessage({
action = 'render',
title = Config.Title,
me = PlayerId(),
max = data.max,
players = data.players
})
end
local function show(state)
visible = state
if state then
render()
end
SendNUIMessage({ action = state and 'show' or 'hide' })
end
RegisterCommand('+scoreboard', function()
if not IsNuiFocused() and not IsChatOpen() then
show(true)
end
end, false)
RegisterCommand('-scoreboard', function()
if visible then
show(false)
end
end, false)
RegisterKeyMapping('+scoreboard', 'Show the player list', 'keyboard', Config.Key)
AddStateBagChangeHandler('nb_scoreboard', 'global', function()
if visible then
render()
end
end)server.luaLUA · 51 lines
local function snapshot(leaving)
local list = {}
for _, player in ipairs(GetPlayers()) do
if player ~= leaving then
local zoneId = Config.ShowLocation and GetPlayerLot(player)
list[#list + 1] = {
id = player,
name = GetPlayerName(player),
ping = GetPlayerPing(player),
job = Config.ShowJob and Player(player).state.job or nil,
lot = zoneId and GetLotName(zoneId) or nil
}
end
end
table.sort(list, function(a, b)
return a.id < b.id
end)
return list
end
local function publish(leaving)
GlobalState.nb_scoreboard = {
players = snapshot(leaving),
max = GetMaxPlayers()
}
end
AddEventHandler('characterSelected', function()
publish()
end)
AddEventHandler('lotEntered', function()
publish()
end)
AddEventHandler('playerDropped', function()
publish(source)
end)
AddStateBagChangeHandler('job', nil, function(bagName)
if GetPlayerFromStateBagName(bagName) then
publish()
end
end)
CreateThread(function()
while true do
publish()
Wait(Config.RefreshSeconds * 1000)
end
end)html/app.jsJS · 42 lines
const board = document.getElementById('board');
const list = document.getElementById('list');
function pingClass(ping) {
if (ping < 80) return 'good';
if (ping < 160) return 'ok';
return 'bad';
}
function cell(className, text) {
const span = document.createElement('span');
span.className = className;
span.textContent = text;
return span;
}
function render(data) {
document.getElementById('title').textContent = data.title;
document.getElementById('count').textContent = `${data.players.length} / ${data.max}`;
list.innerHTML = '';
for (const player of data.players) {
const li = document.createElement('li');
if (player.id === data.me) li.className = 'me';
const who = cell('who', player.name);
if (player.job) {
const job = document.createElement('small');
job.textContent = player.job;
who.appendChild(job);
}
li.appendChild(who);
li.appendChild(cell('where', player.lot || '–'));
li.appendChild(cell(`ping ${pingClass(player.ping)}`, `${player.ping} ms`));
list.appendChild(li);
}
}
window.addEventListener('message', (event) => {
const msg = event.data;
if (msg.action === 'render') render(msg);
if (msg.action === 'show') board.classList.remove('hidden');
if (msg.action === 'hide') board.classList.add('hidden');
});html/index.htmlHTML · 23 lines
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="nui://neighborly/ui/kit.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="board" class="nb-card hidden">
<header>
<h1 id="title">Players</h1>
<span id="count" class="nb-pill">0 / 0</span>
</header>
<div class="cols">
<span>Player</span>
<span>Where</span>
<span>Ping</span>
</div>
<ul id="list"></ul>
</div>
<script src="app.js"></script>
</body>
</html>html/style.cssCSS · 111 lines
body {
margin: 0;
background: transparent;
font-family: "Nunito", sans-serif;
color: var(--navy);
}
#board {
position: absolute;
top: 80px;
left: 50%;
transform: translateX(-50%);
width: 560px;
max-height: 70vh;
display: flex;
flex-direction: column;
padding: 20px 22px;
}
#board.hidden {
display: none;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
h1 {
margin: 0;
font-size: 24px;
font-weight: 900;
}
.cols,
li {
display: grid;
grid-template-columns: 1fr 160px 70px;
gap: 10px;
align-items: center;
}
.cols {
font-size: 12px;
font-weight: 900;
text-transform: uppercase;
letter-spacing: 0.05em;
color: #5a6785;
padding: 0 12px 6px;
}
ul {
list-style: none;
margin: 0;
padding: 0;
overflow-y: auto;
}
li {
padding: 9px 12px;
border-radius: 14px;
font-weight: 800;
}
li:nth-child(odd) {
background: #f5f8fc;
}
li.me {
background: #e3f4ff;
}
.who small {
display: inline-block;
margin-left: 8px;
padding: 2px 8px;
border-radius: 999px;
background: #f1ecff;
color: #6a4fd0;
font-size: 11px;
font-weight: 900;
text-transform: capitalize;
}
.where {
color: #5a6785;
font-weight: 700;
font-size: 14px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.ping {
text-align: right;
font-size: 14px;
}
.ping.good {
color: #22b97a;
}
.ping.ok {
color: #c98a00;
}
.ping.bad {
color: #ff7a85;
}README.mdMD · 19 lines
# nb_scoreboard
Press Home to show everyone who is online – name, job, the lot they are on and their ping – and press it again to hide the list. Players can pick another key with `/bind +scoreboard <key>`.
## Install
1. Put the `nb_scoreboard` folder into your server's `resources` folder.
2. Add `"nb_scoreboard"` to `resources` in `server.json`, or run `refresh` and `ensure nb_scoreboard`.
3. Change the title and refresh rate in `config.lua`.
## How the data gets to players
The server builds the list and stores it in `GlobalState.nb_scoreboard`. Global state replicates to every client automatically – including players who join later, who get the current list before their client scripts start. Clients never ask for the list; they read it when the key is held and re-render when `AddStateBagChangeHandler` reports a change.
The list is rebuilt and assigned as a whole table. Changing a field inside a table you read from a state bag does not replicate.
Other resources can show a job on the board by setting `Player(src).state:set('job', 'barista', true)` on the server.
Docs: https://neighborlymp.com/docs/dev/examples#nb_scoreboardA café job with payment
nb_cafePlayers type /cafe to clock in, brew drinks next to the espresso machine and serve them to other players on the lot, who confirm the payment. The barista earns wages, the customer gets a caffeine buff and some energy.
- The client only shows menus and asks for things. Every check – on duty, right lot, cooldown – happens again on the server.
- Duty status and the drink in hand live in player state bags, so the client can show the right options and the server stays in charge.
- The customer must agree to pay. The server remembers the offer and only accepts an answer for an offer it made.
Files
nb_cafe/
├── resource.toml
├── config.lua
├── client.lua
├── server.lua
└── README.mdSource · 5 files
resource.tomlTOML · 11 lines
name = "nb_cafe"
version = "1.0.0"
author = "Neighborly"
description = "Barista job: clock in, brew drinks, serve customers, get paid"
shared_scripts = ["config.lua"]
client_scripts = ["client.lua"]
server_scripts = ["server.lua"]
dependencies = ["neighborly"]
escrow_ignore = ["config.lua"]config.luaLUA · 35 lines
Config = {}
-- Zone id of the café lot as a string (type "lot <name>" in the server console to find it), or false to allow every lot
Config.CafeLot = false
-- Chat command that opens the café menu
Config.Command = 'cafe'
-- Object definition (tuning name) of the espresso machine the barista must stand next to, or false to brew anywhere on the lot
Config.Machine = 'object_coffeeMaker_espresso'
-- How close (in meters) the barista must stand to the machine
Config.MachineDistance = 3.0
-- How long brewing takes, in milliseconds
Config.BrewTime = 6000
-- Seconds a barista must wait between two drinks
Config.BrewCooldown = 8
-- How close (in meters) the barista must stand to a customer to serve them
Config.ServeDistance = 4.0
-- Buff the customer gets with a drink (any Sims 4 buff tuning name), or false for none
Config.Buff = 'buff_Object_Espresso_Caffeinated'
-- Energy added to the customer's Sim, the need goes from -100 to 100
Config.Energy = 20
-- Drinks on the menu: price is what the customer pays, wage is what the barista earns
Config.Drinks = {
espresso = { label = 'Espresso', price = 8, wage = 4 },
latte = { label = 'Latte', price = 12, wage = 6 },
mocha = { label = 'Mocha', price = 14, wage = 7 }
}client.luaLUA · 108 lines
local function onDuty()
return LocalPlayer.state.onDuty == true
end
local function nearMachine()
if not Config.Machine then
return true
end
local sim = GetActiveSim()
return sim ~= nil and GetClosestObject(GetSimPosition(sim), Config.Machine, Config.MachineDistance) ~= nil
end
local function brew(id, drink)
if not nearMachine() then
return exports.neighborly:notify({ title = 'Café', text = 'Walk your Sim up to the espresso machine first.', type = 'warning' })
end
local done = exports.neighborly:progressBar({
label = 'Brewing ' .. drink.label:lower() .. '...',
duration = Config.BrewTime,
canCancel = true
})
if done then
TriggerServerEvent('nb_cafe:brew', id)
end
end
local function openBrewMenu()
local items = {}
for id, drink in pairs(Config.Drinks) do
items[#items + 1] = {
label = drink.label,
description = ('Wage %s'):format(FormatMoney(drink.wage)),
badge = FormatMoney(drink.price),
onSelect = function()
brew(id, drink)
end
}
end
table.sort(items, function(a, b)
return a.label < b.label
end)
exports.neighborly:openMenu({
id = 'nb_cafe_brew',
title = 'Espresso machine',
subtitle = 'What are you making?',
items = items
})
end
local function openServeMenu()
local customers = TriggerServerCallback('nb_cafe:customers') or {}
if #customers == 0 then
return exports.neighborly:notify({ title = 'Café', text = 'Nobody else is here yet.', type = 'info' })
end
local items = {}
for _, customer in ipairs(customers) do
items[#items + 1] = {
label = customer.name,
onSelect = function()
TriggerServerEvent('nb_cafe:serve', customer.id)
end
}
end
exports.neighborly:openMenu({ id = 'nb_cafe_serve', title = 'Serve a drink', subtitle = 'Who gets it?', items = items })
end
RegisterCommand(Config.Command, function()
local options = {}
if onDuty() then
if LocalPlayer.state.carrying then
options[#options + 1] = { title = 'Serve a drink', description = 'Hand it to a customer on this lot', onSelect = openServeMenu }
else
options[#options + 1] = { title = 'Brew a drink', description = 'At the espresso machine', onSelect = openBrewMenu }
end
options[#options + 1] = { title = 'Clock out', serverEvent = 'nb_cafe:duty', args = false }
else
options[#options + 1] = { title = 'Clock in', description = 'Start your shift', serverEvent = 'nb_cafe:duty', args = true }
end
exports.neighborly:registerContext({ id = 'nb_cafe', title = 'Bluejay Café', options = options })
exports.neighborly:showContext('nb_cafe')
end, false)
TriggerEvent('chat:addSuggestion', '/' .. Config.Command, 'Clock in, brew and serve drinks at the café')
RegisterNetEvent('nb_cafe:offer', function(barista, drinkId)
local drink = Config.Drinks[drinkId]
if not drink then
return
end
local answer = exports.neighborly:alertDialog({
header = 'Your order',
content = ('%s hands you a %s for %s. Pay for it?'):format(GetPlayerName(barista) or 'The barista', drink.label:lower(), FormatMoney(drink.price)),
confirmLabel = 'Pay',
cancelLabel = 'No thanks'
})
TriggerServerEvent('nb_cafe:pay', barista, answer == 'confirm')
end)
AddStateBagChangeHandler('onDuty', nil, function(bagName, key, value)
if GetPlayerFromStateBagName(bagName) ~= PlayerId() then
return
end
if value then
exports.neighborly:showTextUI('On duty at the café – type /' .. Config.Command .. ' for the menu')
else
exports.neighborly:hideTextUI()
end
end)server.luaLUA · 132 lines
local lastBrew = {}
local offers = {}
local function notify(player, text, kind)
TriggerClientEvent('neighborly:notify', player, { title = 'Café', text = text, type = kind or 'info' })
end
local function atCafe(player)
local zoneId = GetPlayerLot(player)
return zoneId ~= nil and (not Config.CafeLot or zoneId == Config.CafeLot)
end
local function isWorking(player)
return Player(player).state.onDuty == true and atCafe(player)
end
local function distance(a, b)
local simA, simB = GetPlayerCharacter(a), GetPlayerCharacter(b)
if not simA or not simB then
return math.huge
end
return #(GetSimPosition(simA) - GetSimPosition(simB))
end
local function setDuty(player, on)
local state = Player(player).state
state:set('onDuty', on, true)
state:set('carrying', nil, true)
end
RegisterNetEvent('nb_cafe:duty', function(on)
local src = source
if not atCafe(src) then
return notify(src, 'You can only clock in at the café.', 'warning')
end
setDuty(src, on == true)
notify(src, on and 'You clocked in. Time to make some coffee!' or 'You clocked out. See you tomorrow!', 'success')
end)
RegisterNetEvent('nb_cafe:brew', function(drinkId)
local src = source
local drink = Config.Drinks[drinkId]
if not drink or not isWorking(src) or Player(src).state.carrying then
return
end
local now = os.time()
if lastBrew[src] and now - lastBrew[src] < Config.BrewCooldown then
return notify(src, 'The machine is still warming up.', 'warning')
end
lastBrew[src] = now
Player(src).state:set('carrying', drinkId, true)
notify(src, drink.label .. ' is ready. Serve it to a customer!', 'success')
end)
RegisterServerCallback('nb_cafe:customers', function(source)
local list = {}
local zoneId = GetPlayerLot(source)
if not zoneId then
return list
end
for _, player in ipairs(GetPlayersOnLot(zoneId)) do
if player ~= source then
list[#list + 1] = { id = player, name = GetPlayerName(player) }
end
end
return list
end)
RegisterNetEvent('nb_cafe:serve', function(customer)
local src = source
local drinkId = Player(src).state.carrying
if not drinkId or not isWorking(src) then
return
end
if type(customer) ~= 'number' or customer == src or not GetPlayerName(customer) then
return
end
if GetPlayerLot(customer) ~= GetPlayerLot(src) or distance(src, customer) > Config.ServeDistance then
return notify(src, 'Get a little closer to your customer.', 'warning')
end
offers[customer] = { barista = src, drink = drinkId, expires = os.time() + 30 }
TriggerClientEvent('nb_cafe:offer', customer, src, drinkId)
end)
RegisterNetEvent('nb_cafe:pay', function(barista, accepted)
local src = source
local offer = offers[src]
offers[src] = nil
if not offer or offer.barista ~= barista or offer.expires < os.time() then
return
end
if not accepted then
return notify(barista, GetPlayerName(src) .. ' changed their mind.')
end
local drink = Config.Drinks[offer.drink]
if Player(barista).state.carrying ~= offer.drink then
return
end
if not TakeMoney(src, drink.price, 'Café: ' .. drink.label) then
notify(src, "You don't have enough simoleons.", 'error')
return notify(barista, "The customer couldn't pay.", 'warning')
end
Player(barista).state:set('carrying', nil, true)
GiveMoney(barista, drink.wage, 'Café wages')
local customerSim = GetPlayerCharacter(src)
if customerSim then
if Config.Buff then
AddSimBuff(customerSim, Config.Buff)
end
if Config.Energy and Config.Energy ~= 0 then
SetSimNeed(customerSim, 'energy', math.min(GetSimNeed(customerSim, 'energy') + Config.Energy, 100))
end
end
notify(barista, ('Served! You earned %s.'):format(FormatMoney(drink.wage)), 'success')
notify(src, 'Enjoy your ' .. drink.label:lower() .. '!', 'success')
end)
AddEventHandler('lotLeft', function()
if Player(source).state.onDuty then
setDuty(source, false)
end
end)
AddEventHandler('playerDropped', function()
lastBrew[source] = nil
offers[source] = nil
end)README.mdMD · 20 lines
# nb_cafe
A barista job. Type `/cafe` to clock in, brew drinks next to the espresso machine and serve them to other players on the lot, who confirm the payment. Baristas earn wages, customers get a caffeine buff and some energy.
## Install
1. Put the `nb_cafe` folder into your server's `resources` folder.
2. Optionally set `Config.CafeLot` in `config.lua` to the zone id of your café and `Config.Machine` to your espresso machine.
3. Add `"nb_cafe"` to `resources` in `server.json`, or run `refresh` and `ensure nb_cafe`.
## What it shows
- A context menu (`registerContext`/`showContext`), list menus, a progress bar and an alert dialog from the built-in `neighborly` resource
- A server callback that returns the customers on the lot
- Duty status and the drink in hand in player state bags (`Player(src).state`)
- Every client request checked again on the server: duty, lot, distance, cooldown
- Real Sim changes on the customer: `AddSimBuff` and `SetSimNeed`
- A two-step payment the customer has to accept
Docs: https://neighborlymp.com/docs/dev/examples#nb_cafeA savings bank (server callbacks)
nb_bankSavings accounts for every player: deposit, withdraw, daily interest and money requests between players, in a NUI app. Every question the page asks travels page → Lua → server and back with callbacks.
RegisterNUICallbackwaits forTriggerServerCallbackbefore answering the page, so the UI always shows what the server decided.- Savings are changed with
db:update, so two quick withdrawals can't both succeed. - Requesting money asks the other player with
TriggerClientCallbackand a dialog – the server only moves money after a real yes. - Every callback returns
ok, result, so errors reach the page as friendly messages.
Files
nb_bank/
├── resource.toml
├── config.lua
├── client.lua
├── server.lua
├── html/
│ ├── app.js
│ ├── index.html
│ └── style.css
└── README.mdSource · 8 files
resource.tomlTOML · 14 lines
name = "nb_bank"
version = "1.0.0"
author = "Neighborly"
description = "Savings accounts at every ATM: deposits, withdrawals, interest and money requests"
shared_scripts = ["config.lua"]
client_scripts = ["client.lua"]
server_scripts = ["server.lua"]
ui_page = "html/index.html"
files = ["html/index.html", "html/style.css", "html/app.js"]
dependencies = ["neighborly"]
escrow_ignore = ["config.lua"]config.luaLUA · 34 lines
Config = {}
-- Bank name shown in the app
Config.BankName = 'Simoleon Savings'
-- Chat command that opens the bank
Config.Command = 'bank'
-- true: the command only works while the player's Sim stands next to an ATM object
Config.RequireAtm = false
-- Object definitions (tuning names) that count as ATMs when Config.RequireAtm is true
Config.AtmObjects = {
object_atm_wall = true,
object_atm_standing = true
}
-- How close the Sim must be to an ATM, in meters
Config.AtmDistance = 3.0
-- Largest amount for one deposit, withdrawal or request
Config.MaxAmount = 50000
-- Interest paid on savings every game day, in percent
Config.DailyInterest = 0.5
-- Most interest one account can earn per game day
Config.MaxInterestPerDay = 500
-- How many entries the history keeps
Config.HistoryLength = 15
-- Seconds a player must wait between two money requests
Config.RequestCooldown = 20client.luaLUA · 92 lines
local open = false
local function setOpen(state)
open = state
SetNuiFocus(state, state)
SendNUIMessage({ action = state and 'open' or 'close' })
end
local function openBank()
if open then
return
end
local account = TriggerServerCallback('nb_bank:getAccount')
if not account then
return exports.neighborly:notify({ text = 'The bank is not answering. Try again in a moment.', type = 'error' })
end
SendNUIMessage({ action = 'account', account = account, lastAmount = GetResourceKvp('lastAmount') })
setOpen(true)
end
local function nearAtm()
if not Config.RequireAtm then
return true
end
local sim = GetActiveSim()
if not sim then
return false
end
local position = GetSimPosition(sim)
for definition in pairs(Config.AtmObjects) do
if GetClosestObject(position, definition, Config.AtmDistance) then
return true
end
end
return false
end
RegisterCommand(Config.Command, function()
if not nearAtm() then
return exports.neighborly:notify({ text = 'Walk your Sim up to an ATM first.', type = 'warning' })
end
openBank()
end, false)
TriggerEvent('chat:addSuggestion', '/' .. Config.Command, 'Open your savings account')
local function forward(cb, name, ...)
local ok, result = TriggerServerCallback(name, ...)
if ok == nil then
return cb({ ok = false, error = 'The bank is not answering. Try again in a moment.' })
end
if ok then
cb({ ok = true, account = result })
else
cb({ ok = false, error = result })
end
end
RegisterNUICallback('deposit', function(data, cb)
SetResourceKvp('lastAmount', tonumber(data.amount))
forward(cb, 'nb_bank:deposit', tonumber(data.amount))
end)
RegisterNUICallback('withdraw', function(data, cb)
SetResourceKvp('lastAmount', tonumber(data.amount))
forward(cb, 'nb_bank:withdraw', tonumber(data.amount))
end)
RegisterNUICallback('request', function(data, cb)
forward(cb, 'nb_bank:request', tonumber(data.player), tonumber(data.amount))
end)
RegisterNUICallback('close', function(_, cb)
setOpen(false)
cb({ ok = true })
end)
RegisterClientCallback('nb_bank:askPay', function(fromName, amount)
local answer = exports.neighborly:alertDialog({
header = 'Money request',
content = ('%s asks you for %s. Do you want to pay?'):format(fromName, FormatMoney(amount)),
confirmLabel = 'Pay',
cancelLabel = 'Decline'
})
return answer == 'confirm'
end)
AddEventHandler('onResourceStop', function(name)
if name == GetCurrentResourceName() and open then
SetNuiFocus(false, false)
end
end)server.luaLUA · 151 lines
local db = exports.neighborly:db()
local lastRequest = {}
local asking = {}
local function accountKey(player)
return 'account:' .. GetPlayerAccountId(player)
end
local function newAccount()
return { savings = 0, history = {} }
end
local function addHistory(account, amount, label)
table.insert(account.history, 1, { amount = amount, label = label, time = os.time() })
while #account.history > Config.HistoryLength do
table.remove(account.history)
end
end
local function view(player, account)
return {
bank = Config.BankName,
name = GetPlayerName(player),
cash = GetBalance(player),
savings = account.savings,
interest = Config.DailyInterest,
history = account.history
}
end
local function cleanAmount(amount)
if type(amount) ~= 'number' or amount ~= amount then
return nil
end
amount = math.floor(amount)
if amount < 1 or amount > Config.MaxAmount then
return nil
end
return amount
end
local function badAmount()
return false, ('Enter an amount between %s and %s.'):format(FormatMoney(1), FormatMoney(Config.MaxAmount))
end
RegisterServerCallback('nb_bank:getAccount', function(source)
return view(source, db:get(accountKey(source)) or newAccount())
end)
RegisterServerCallback('nb_bank:deposit', function(source, amount)
amount = cleanAmount(amount)
if not amount then
return badAmount()
end
if not TakeMoney(source, amount, 'Savings deposit') then
return false, "You don't have that much cash."
end
local account = db:update(accountKey(source), function(account)
account = account or newAccount()
account.savings = account.savings + amount
addHistory(account, amount, 'Deposit')
return account
end)
return true, view(source, account)
end)
RegisterServerCallback('nb_bank:withdraw', function(source, amount)
amount = cleanAmount(amount)
if not amount then
return badAmount()
end
local paid = false
local account = db:update(accountKey(source), function(account)
account = account or newAccount()
if account.savings >= amount then
account.savings = account.savings - amount
addHistory(account, -amount, 'Withdrawal')
paid = true
end
return account
end)
if not paid then
return false, 'Your savings are not enough for that.'
end
GiveMoney(source, amount, 'Savings withdrawal')
return true, view(source, account)
end)
RegisterServerCallback('nb_bank:request', function(source, target, amount)
amount = cleanAmount(amount)
if not amount then
return badAmount()
end
if type(target) ~= 'number' or target == source or not GetPlayerName(target) then
return false, 'There is no other player with that id.'
end
local now = GetGameTimer()
if lastRequest[source] and now - lastRequest[source] < Config.RequestCooldown * 1000 then
return false, 'Please wait a moment before the next request.'
end
lastRequest[source] = now
if asking[target] then
return false, GetPlayerName(target) .. ' is answering another request.'
end
asking[target] = true
local accepted = TriggerClientCallback('nb_bank:askPay', target, GetPlayerName(source), amount)
asking[target] = nil
if accepted ~= true then
return false, GetPlayerName(target) .. ' declined the request.'
end
if not TransferMoney(target, source, amount, 'Money request') then
return false, GetPlayerName(target) .. " couldn't afford it."
end
TriggerClientEvent('neighborly:notify', target, {
text = ('You paid %s to %s.'):format(FormatMoney(amount), GetPlayerName(source)),
type = 'success'
})
return true, view(source, db:get(accountKey(source)) or newAccount())
end)
AddEventHandler('dayChanged', function()
if Config.DailyInterest <= 0 then
return
end
for i, key in ipairs(db:keys('account:')) do
db:update(key, function(account)
local interest = math.min(math.floor(account.savings * Config.DailyInterest / 100), Config.MaxInterestPerDay)
if interest > 0 then
account.savings = account.savings + interest
addHistory(account, interest, 'Interest')
end
return account
end)
if i % 100 == 0 then
Wait(0)
end
end
end)
exports('getSavings', function(player)
local account = db:get(accountKey(player))
return account and account.savings or 0
end)
AddEventHandler('playerDropped', function()
lastRequest[source] = nil
asking[source] = nil
end)html/app.jsJS · 100 lines
const resource = GetParentResourceName();
const $ = (id) => document.getElementById(id);
const money = new Intl.NumberFormat('en-US');
let tab = 'deposit';
let busy = false;
function post(name, data) {
return fetch(`https://${resource}/${name}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json; charset=UTF-8' },
body: JSON.stringify(data || {})
}).then((r) => r.json());
}
function simoleons(amount) {
return '§' + money.format(amount);
}
function setStatus(text, kind) {
$('status').textContent = text || '';
$('status').className = 'status ' + (kind || '');
}
function render(account) {
$('bankName').textContent = account.bank;
$('owner').textContent = account.name;
$('cash').textContent = simoleons(account.cash);
$('savings').textContent = simoleons(account.savings);
$('interest').textContent = `${account.interest}% daily`;
$('history').innerHTML = '';
if (account.history.length === 0) {
const li = document.createElement('li');
li.textContent = 'No transactions yet.';
$('history').appendChild(li);
}
for (const entry of account.history) {
const li = document.createElement('li');
const left = document.createElement('div');
const when = document.createElement('small');
const amount = document.createElement('b');
left.textContent = entry.label;
when.textContent = new Date(entry.time * 1000).toLocaleString();
left.appendChild(when);
amount.className = entry.amount >= 0 ? 'plus' : 'minus';
amount.textContent = (entry.amount >= 0 ? '+' : '−') + simoleons(Math.abs(entry.amount));
li.appendChild(left);
li.appendChild(amount);
$('history').appendChild(li);
}
}
function selectTab(name) {
tab = name;
for (const button of document.querySelectorAll('[data-tab]')) {
button.classList.toggle('on', button.dataset.tab === name);
}
$('player').classList.toggle('hidden', name !== 'request');
$('player').required = name === 'request';
$('submit').textContent = name === 'deposit' ? 'Deposit' : name === 'withdraw' ? 'Withdraw' : 'Request';
setStatus('');
}
document.querySelectorAll('[data-tab]').forEach((button) => {
button.addEventListener('click', () => selectTab(button.dataset.tab));
});
$('form').addEventListener('submit', async (e) => {
e.preventDefault();
if (busy) return;
busy = true;
$('submit').disabled = true;
setStatus(tab === 'request' ? 'Waiting for an answer…' : 'Working…');
const res = await post(tab, { amount: $('amount').value, player: $('player').value });
busy = false;
$('submit').disabled = false;
if (res.ok) {
render(res.account);
setStatus(tab === 'request' ? 'They paid you!' : 'Done!', 'ok');
} else {
setStatus(res.error, 'error');
}
});
window.addEventListener('message', (event) => {
const msg = event.data;
if (msg.action === 'account') {
render(msg.account);
if (msg.lastAmount) $('amount').value = msg.lastAmount;
}
if (msg.action === 'open') {
selectTab('deposit');
$('bank').classList.remove('hidden');
}
if (msg.action === 'close') $('bank').classList.add('hidden');
});
$('close').onclick = () => post('close');
window.addEventListener('keydown', (e) => {
if (e.key === 'Escape') post('close');
});html/index.htmlHTML · 48 lines
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="nui://neighborly/ui/kit.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="bank" class="nb-card hidden">
<header>
<div>
<small id="bankName">Simoleon Savings</small>
<h1 id="owner">Account</h1>
</div>
<button id="close" class="nb-btn ghost" aria-label="Close">×</button>
</header>
<div class="tiles">
<div class="tile">
<small>Cash</small>
<b id="cash">§0</b>
</div>
<div class="tile savings">
<small>Savings</small>
<b id="savings">§0</b>
<span id="interest" class="nb-pill"></span>
</div>
</div>
<nav class="tabs">
<button data-tab="deposit" class="on">Deposit</button>
<button data-tab="withdraw">Withdraw</button>
<button data-tab="request">Request</button>
</nav>
<form id="form">
<input id="player" class="nb-input hidden" type="number" min="1" placeholder="Player id">
<input id="amount" class="nb-input" type="number" min="1" placeholder="Amount" required>
<button id="submit" class="nb-btn go" type="submit">Deposit</button>
</form>
<p id="status" class="status"></p>
<h2>History</h2>
<ul id="history"></ul>
</div>
<script src="app.js"></script>
</body>
</html>html/style.cssCSS · 157 lines
body {
margin: 0;
background: transparent;
font-family: "Nunito", sans-serif;
color: var(--navy);
}
#bank {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 440px;
max-height: 86vh;
overflow-y: auto;
padding: 22px;
}
#bank.hidden,
.hidden {
display: none;
}
header {
display: flex;
justify-content: space-between;
align-items: flex-start;
}
header small {
color: #5a6785;
font-weight: 800;
}
h1 {
margin: 0;
font-size: 26px;
font-weight: 900;
}
h2 {
font-size: 15px;
margin: 18px 0 8px;
}
.tiles {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin: 16px 0;
}
.tile {
background: #f5f8fc;
border-radius: 18px;
padding: 14px 16px;
}
.tile.savings {
background: linear-gradient(135deg, #5bc0f8, #a58bf0);
color: #fff;
}
.tile small {
display: block;
font-weight: 800;
opacity: 0.85;
}
.tile b {
display: block;
font-size: 26px;
font-weight: 900;
}
.tabs {
display: flex;
gap: 4px;
background: #eef3f9;
border-radius: 14px;
padding: 4px;
}
.tabs button {
flex: 1;
border: 0;
background: transparent;
font: 800 14px "Nunito", sans-serif;
color: #5a6785;
padding: 8px;
border-radius: 10px;
cursor: pointer;
}
.tabs button.on {
background: #fff;
color: var(--navy);
box-shadow: 0 2px 8px rgba(30, 42, 74, 0.12);
}
form {
display: flex;
gap: 8px;
margin-top: 12px;
}
form .nb-input {
flex: 1;
min-width: 0;
}
.status {
min-height: 20px;
margin: 8px 0 0;
font-weight: 800;
font-size: 14px;
}
.status.error {
color: #ff7a85;
}
.status.ok {
color: #22b97a;
}
ul {
list-style: none;
margin: 0;
padding: 0;
}
li {
display: flex;
justify-content: space-between;
padding: 9px 12px;
border-radius: 12px;
font-weight: 800;
}
li:nth-child(odd) {
background: #f5f8fc;
}
li small {
display: block;
color: #5a6785;
font-weight: 700;
}
.plus {
color: #22b97a;
}
.minus {
color: #ff7a85;
}README.mdMD · 20 lines
# nb_bank
Savings accounts for every player. Type `/bank` (optionally only next to an ATM) to deposit cash, withdraw it again, earn a little interest every game day and request money from other players.
## Install
1. Put the `nb_bank` folder into your server's `resources` folder.
2. Optionally set `Config.RequireAtm = true` and list your ATM objects in `Config.AtmObjects` in `config.lua`.
3. Add `"nb_bank"` to `resources` in `server.json`, or run `refresh` and `ensure nb_bank`.
## How the data gets to players
- The NUI page asks Lua with `fetch`, Lua asks the server with `TriggerServerCallback`, and the answer travels all the way back to the page – no event pairs, no lost replies.
- The server keeps savings in the Neighborly database, keyed by `GetPlayerAccountId`, and changes them with `db:update` so two requests can never spend the same simoleons.
- Requesting money uses a client callback: the server asks the other player with `TriggerClientCallback`, they answer in a dialog, and only then the server moves the money.
- The last amount you typed is remembered on your PC with `SetResourceKvp`.
Other resources can read savings with `exports.nb_bank:getSavings(player)`.
Docs: https://neighborlymp.com/docs/dev/examples#nb_bankA phone bank app (NUI + bills)
nb_phoneAn HTML phone that opens with F10: the balance, open bills with a Pay button, the last ten transactions and a form to send money to another player. The page never decides anything – it only shows what the server sends.
- The JavaScript uses
textContentinstead ofinnerHTMLfor data, so a bill called<script>can't break the page. - Every action is rate-limited on the server and answered with a fresh data event.
- Compare it with nb_bank, which does the same round trip with server callbacks instead of event pairs.
Files
nb_phone/
├── resource.toml
├── client.lua
├── server.lua
├── html/
│ ├── app.js
│ ├── index.html
│ └── style.css
└── README.mdSource · 7 files
resource.tomlTOML · 12 lines
name = "nb_phone"
version = "1.0.0"
author = "Neighborly"
description = "A bank app on the Sim's phone: balance, bills, history and transfers"
client_scripts = ["client.lua"]
server_scripts = ["server.lua"]
ui_page = "html/index.html"
files = ["html/index.html", "html/style.css", "html/app.js"]
dependencies = ["neighborly"]client.luaLUA · 41 lines
local open = false
local function setOpen(state)
open = state
SetNuiFocus(state, state)
SendNUIMessage({ action = state and 'open' or 'close' })
if state then
TriggerServerEvent('nb_phone:refresh')
end
end
RegisterCommand('phone', function()
setOpen(not open)
end, false)
RegisterKeyMapping('phone', 'Open the bank app', 'keyboard', 'F10')
RegisterNetEvent('nb_phone:data', function(data)
SendNUIMessage({ action = 'data', data = data })
end)
RegisterNUICallback('close', function(_, cb)
setOpen(false)
cb({ ok = true })
end)
RegisterNUICallback('payBill', function(data, cb)
TriggerServerEvent('nb_phone:payBill', tonumber(data.id))
cb({ ok = true })
end)
RegisterNUICallback('sendMoney', function(data, cb)
TriggerServerEvent('nb_phone:sendMoney', tonumber(data.to), tonumber(data.amount))
cb({ ok = true })
end)
AddEventHandler('onResourceStop', function(name)
if name == GetCurrentResourceName() and open then
SetNuiFocus(false, false)
end
end)server.luaLUA · 93 lines
local lastAction = {}
local function tooFast(player)
local now = GetGameTimer()
if lastAction[player] and now - lastAction[player] < 1500 then
return true
end
lastAction[player] = now
return false
end
local function sendData(player)
local bills = {}
for _, bill in ipairs(GetBills(player)) do
bills[#bills + 1] = { id = bill.id, label = bill.label, amount = FormatMoney(bill.amount) }
end
local history = {}
for _, t in ipairs(GetTransactions(player, 10)) do
history[#history + 1] = {
reason = t.reason,
amount = (t.amount >= 0 and '+' or '-') .. FormatMoney(math.abs(t.amount)),
positive = t.amount >= 0,
time = os.date('%d.%m. %H:%M', t.time)
}
end
TriggerClientEvent('nb_phone:data', player, {
name = GetPlayerName(player),
balance = FormatMoney(GetBalance(player)),
bills = bills,
history = history
})
end
RegisterNetEvent('nb_phone:refresh', function()
local src = source
if not tooFast(src) then
sendData(src)
end
end)
RegisterNetEvent('nb_phone:payBill', function(billId)
local src = source
if type(billId) ~= 'number' or tooFast(src) then
return
end
local mine = false
for _, bill in ipairs(GetBills(src)) do
if bill.id == billId then
mine = true
break
end
end
if not mine then
return
end
if PayBill(billId) then
TriggerClientEvent('neighborly:notify', src, { text = 'Bill paid.', type = 'success' })
else
TriggerClientEvent('neighborly:notify', src, { text = 'Not enough simoleons for this bill.', type = 'error' })
end
sendData(src)
end)
RegisterNetEvent('nb_phone:sendMoney', function(to, amount)
local src = source
if type(to) ~= 'number' or type(amount) ~= 'number' or tooFast(src) then
return
end
amount = math.floor(amount)
if amount < 1 or amount > 10000 or to == src or not GetPlayerName(to) then
return TriggerClientEvent('neighborly:notify', src, { text = 'Check the player id and amount.', type = 'warning' })
end
if TransferMoney(src, to, amount, 'Phone transfer') then
TriggerClientEvent('neighborly:notify', to, {
title = 'Money received',
text = ('%s sent you %s.'):format(GetPlayerName(src), FormatMoney(amount)),
type = 'success'
})
TriggerClientEvent('neighborly:notify', src, { text = 'Money sent.', type = 'success' })
else
TriggerClientEvent('neighborly:notify', src, { text = 'Not enough simoleons.', type = 'error' })
end
sendData(src)
end)
AddEventHandler('playerDropped', function()
lastAction[source] = nil
end)html/app.jsJS · 65 lines
const resource = GetParentResourceName();
const $ = (id) => document.getElementById(id);
function post(name, data) {
return fetch(`https://${resource}/${name}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json; charset=UTF-8' },
body: JSON.stringify(data || {})
}).then((r) => r.json());
}
function row(title, subtitle, right) {
const li = document.createElement('li');
const left = document.createElement('div');
left.textContent = title;
if (subtitle) {
const small = document.createElement('small');
small.textContent = subtitle;
left.appendChild(small);
}
li.appendChild(left);
if (right) li.appendChild(right);
return li;
}
function render(data) {
$('balance').textContent = data.balance;
$('owner').textContent = data.name;
$('bills').innerHTML = '';
if (data.bills.length === 0) $('bills').appendChild(row('No open bills', 'You are all paid up!'));
for (const bill of data.bills) {
const pay = document.createElement('button');
pay.className = 'nb-btn sky';
pay.textContent = 'Pay ' + bill.amount;
pay.onclick = () => post('payBill', { id: bill.id });
$('bills').appendChild(row(bill.label, null, pay));
}
$('history').innerHTML = '';
for (const t of data.history) {
const amount = document.createElement('b');
amount.className = t.positive ? 'plus' : 'minus';
amount.textContent = t.amount;
$('history').appendChild(row(t.reason, t.time, amount));
}
}
window.addEventListener('message', (event) => {
const msg = event.data;
if (msg.action === 'open') $('phone').classList.remove('hidden');
if (msg.action === 'close') $('phone').classList.add('hidden');
if (msg.action === 'data') render(msg.data);
});
$('send').addEventListener('submit', (e) => {
e.preventDefault();
post('sendMoney', { to: $('to').value, amount: $('amount').value });
$('amount').value = '';
});
$('close').onclick = () => post('close');
window.addEventListener('keydown', (e) => {
if (e.key === 'Escape') post('close');
});html/index.htmlHTML · 41 lines
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="nui://neighborly/ui/kit.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="phone" class="hidden">
<div class="screen">
<header>
<small>Simoleon Savings</small>
<h1 id="balance">§0</h1>
<span id="owner"></span>
</header>
<section>
<h2>Open bills</h2>
<ul id="bills"></ul>
</section>
<section>
<h2>Send money</h2>
<form id="send">
<input class="nb-input" id="to" type="number" min="1" placeholder="Player id" required>
<input class="nb-input" id="amount" type="number" min="1" max="10000" placeholder="Amount" required>
<button class="nb-btn go" type="submit">Send</button>
</form>
</section>
<section>
<h2>History</h2>
<ul id="history"></ul>
</section>
<button id="close" class="nb-btn ghost">Close</button>
</div>
</div>
<script src="app.js"></script>
</body>
</html>html/style.cssCSS · 92 lines
body {
margin: 0;
background: transparent;
font-family: "Nunito", sans-serif;
color: var(--navy);
}
#phone {
position: absolute;
right: 60px;
bottom: 60px;
width: 340px;
height: 640px;
padding: 14px;
border-radius: 44px;
background: #1e2a4a;
box-shadow: 0 30px 60px rgba(20, 30, 55, 0.45);
}
#phone.hidden {
display: none;
}
.screen {
height: 100%;
overflow-y: auto;
border-radius: 32px;
background: #f5f8fc;
padding: 22px 18px;
box-sizing: border-box;
}
header {
background: linear-gradient(135deg, #5bc0f8, #a58bf0);
color: #fff;
border-radius: 22px;
padding: 18px;
margin-bottom: 16px;
}
header h1 {
margin: 2px 0;
font-size: 34px;
}
h2 {
font-size: 15px;
margin: 14px 0 8px;
}
ul {
list-style: none;
padding: 0;
margin: 0;
}
li {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
background: #fff;
border-radius: 14px;
padding: 10px 12px;
margin-bottom: 6px;
font-weight: 700;
}
li small {
display: block;
color: #5a6785;
font-weight: 600;
}
.plus {
color: #22b97a;
}
.minus {
color: #ff7a85;
}
form {
display: grid;
grid-template-columns: 1fr 1fr auto;
gap: 6px;
}
#close {
width: 100%;
margin-top: 16px;
}README.mdMD · 17 lines
# nb_phone
A bank app on the Sim's phone, opened with F10: balance, open bills with a Pay button, the last ten transactions and a form to send money to another player.
## Install
1. Put the `nb_phone` folder into your server's `resources` folder.
2. Add `"nb_phone"` to `resources` in `server.json`, or run `refresh` and `ensure nb_phone`.
## What it shows
- A NUI page with `SendNUIMessage`, `RegisterNUICallback` and `SetNuiFocus`
- A key mapping players can rebind
- The server sending fresh data back after every action with events
- Rendering player data with `textContent`, never `innerHTML`
Docs: https://neighborlymp.com/docs/dev/examples#nb_phone
Built something cool? Share it with other creators in the #developers channel on our Discord.