### Git Submodule and Symlink Setup (Linux)
Source: https://github.com/citizenfx/cfx-server-data/blob/master/README.md
This snippet demonstrates how to add the cfx-server-data repository as a Git submodule and create a symbolic link for resources on a Linux system.
```bash
git submodule add https://github.com/citizenfx/cfx-server-data.git vendor/server-data
ln -s ../vendor/server-data/resources/ 'resources/[base]/'
```
--------------------------------
### Git Submodule and Symlink Setup (Windows)
Source: https://github.com/citizenfx/cfx-server-data/blob/master/README.md
This snippet demonstrates how to add the cfx-server-data repository as a Git submodule and create a directory junction (symlink) for resources on a Windows system.
```batch
git submodule add https://github.com/citizenfx/cfx-server-data.git vendor/server-data
mklink /d resources\[base] ..\vendor\server-data\resources
```
--------------------------------
### Player Data: Get Player ID (Lua)
Source: https://context7.com/citizenfx/cfx-server-data/llms.txt
Assigns persistent database IDs to players based on their identifiers (license, steam, etc.), enabling cross-session data storage and retrieval. Dependencies: 'player-data' export. Inputs: player source or database ID, or player identifier. Outputs: Database ID or player source. Limitations: Requires server-side execution.
```lua
-- Server-side: Get database ID for a connected player
local playerSource = 1
local dbId = exports['player-data']:getPlayerId(tostring(playerSource))
if dbId then
print('Player database ID: ' .. dbId)
-- Load player data from external database
local playerData = LoadPlayerDataFromDatabase(dbId)
end
-- Server-side: Get player source from database ID
local dbId = 12345
local playerSource = exports['player-data']:getPlayerById(tostring(dbId))
if playerSource then
TriggerClientEvent('notify', playerSource, 'Your data has been loaded')
end
-- Server-side: Find player ID from identifier
local steamId = 'steam:110000103fa5f9c'
local dbId = exports['player-data']:getPlayerIdFromIdentifier(steamId)
-- Access via state bag
local playerId = Player(playerSource).state['cfx.re/playerData@id']
```
--------------------------------
### Resource Manifest: fxmanifest.lua Configuration (Lua)
Source: https://context7.com/citizenfx/cfx-server-data/llms.txt
Defines the structure and metadata for a FiveM resource using the `fxmanifest.lua` file. It specifies the FiveM version, game, author, description, version, client/server/shared scripts, UI files, dependencies, and exported functions. This file is crucial for resource loading and execution.
```lua
-- fxmanifest.lua - Basic resource configuration
fx_version 'cerulean'
game 'gta5'
author 'Your Name'
description 'Custom gameplay resource'
version '1.0.0'
-- Client-side scripts
client_scripts {
'client/main.lua',
'client/ui.lua'
}
-- Server-side scripts
server_scripts {
'@mysql-async/lib/MySQL.lua',
'server/database.lua',
'server/main.lua'
}
-- Shared scripts (loaded on both client and server)
shared_scripts {
'config.lua',
'shared/utils.lua'
}
-- UI files
ui_page 'html/index.html'
files {
'html/index.html',
'html/style.css',
'html/script.js',
'data/*.json'
}
-- Dependencies
dependencies {
'mysql-async',
'chat'
}
-- Export functions
exports {
'GetPlayerData',
'SavePlayerData'
}
-- Server exports
server_exports {
'GetAllPlayers'
}
```
--------------------------------
### Money System: Add and Remove Money (Lua)
Source: https://context7.com/citizenfx/cfx-server-data/llms.txt
Provides a simple economy framework with bank and cash accounts, automatic synchronization to game stats, and event-driven updates. Dependencies: 'money' export. Inputs: player source, money type ('cash' or 'bank'), amount. Outputs: success status, current balances, money update events. Limitations: Requires server-side execution for most operations.
```lua
-- Server-side: Add money to player's cash
local playerSource = 1
local success = exports['money']:addMoney(playerSource, 'cash', 1000)
if success then
print('Added $1000 cash to player')
end
-- Server-side: Remove money from player's bank
local success = exports['money']:removeMoney(playerSource, 'bank', 500)
if not success then
print('Player has insufficient funds')
TriggerClientEvent('notify', playerSource, 'Insufficient bank balance')
end
-- Server-side: Get current money balance
local cashBalance = exports['money']:getMoney(playerSource, 'cash')
local bankBalance = exports['money']:getMoney(playerSource, 'bank')
print('Player has $' .. cashBalance .. ' cash and $' .. bankBalance .. ' in bank')
-- Server-side: Listen for money updates
AddEventHandler('money:updated', function(data)
print('Player ' .. data.source .. ' now has $' .. data.money .. ' ' .. data.moneyType)
-- Log transaction to database
LogMoneyChange(data.dbId, data.moneyType, data.money)
end)
```
--------------------------------
### Register Server and Client Commands with ACE Permissions in Lua
Source: https://context7.com/citizenfx/cfx-server-data/llms.txt
Registers commands on both server and client, including ACE permission checks for server commands and basic argument parsing. The client-side command demonstrates toggling UI elements.
```lua
-- Server-side: Register admin command with ACE permissions
RegisterCommand('kick', function(source, args, rawCommand)
if source == 0 then -- Console
local targetId = tonumber(args[1])
local reason = table.concat(args, ' ', 2)
DropPlayer(targetId, reason)
return
end
-- Check player permissions
if not IsPlayerAceAllowed(source, 'command.kick') then
TriggerClientEvent('chat:addMessage', source, {
color = { 255, 0, 0 },
args = { 'Error', 'You do not have permission to use this command' }
})
return
end
local targetId = tonumber(args[1])
local reason = table.concat(args, ' ', 2) or 'No reason specified'
DropPlayer(targetId, reason)
end, true) -- Restricted command
-- Client-side: Register toggle command
RegisterCommand('toggleHUD', function(source, args)
isHudVisible = not isHudVisible
DisplayRadar(isHudVisible)
TriggerEvent('chat:addMessage', {
args = { 'HUD ' .. (isHudVisible and 'shown' or 'hidden') }
})
end, false)
-- Add command suggestions to chat
TriggerEvent('chat:addSuggestion', '/kick', 'Kick a player from the server', {
{ name = 'id', help = 'Player server ID' },
{ name = 'reason', help = 'Reason for kick' }
})
```
--------------------------------
### Spawn Manager: Manual Player Spawn (Lua)
Source: https://context7.com/citizenfx/cfx-server-data/llms.txt
Provides fine-grained control over player spawning with fade effects, model loading, and collision preloading handled automatically. Dependencies: 'spawnmanager' export. Inputs: spawn point (nil for random, index, or coordinates), optional callback function. Outputs: Player spawned. Limitations: Requires client-side execution.
```lua
-- Client-side: Spawn at random spawn point
exports['spawnmanager']:spawnPlayer(nil, function(spawn)
print('Player spawned at: ' .. spawn.x .. ', ' .. spawn.y .. ', ' .. spawn.z)
end)
-- Client-side: Spawn at specific spawn point index
exports['spawnmanager']:spawnPlayer(1, function(spawn)
TriggerServerEvent('playerSpawned', spawn)
end)
-- Client-side: Spawn at custom coordinates with callback
exports['spawnmanager']:spawnPlayer({
x = 200.0,
y = -800.0,
z = 31.0,
heading = 180.0,
model = 'mp_m_freemode_01'
}, function(spawn)
-- Give weapons after spawn
GiveWeaponToPed(PlayerPedId(), GetHashKey('WEAPON_PISTOL'), 150, false, true)
end)
```
--------------------------------
### Spawn Manager API
Source: https://context7.com/citizenfx/cfx-server-data/llms.txt
Provides functions for managing player spawn points, including adding, loading from JSON, and removing spawn points.
```APIDOC
## Spawn Manager - Add Spawn Point
### Description
Adds a single spawn point to the spawn manager.
### Method
exports['spawnmanager']:addSpawnPoint
### Parameters
- **spawnData** (table) - Required - A table containing the spawn point's properties.
- **x** (number) - Required - The X coordinate of the spawn point.
- **y** (number) - Required - The Y coordinate of the spawn point.
- **z** (number) - Required - The Z coordinate of the spawn point.
- **heading** (number) - Optional - The heading (rotation) of the spawn point.
- **model** (string) - Optional - The model of the player or object to spawn.
### Request Example
```lua
-- Client-side: Add a single spawn point
local spawnIdx = exports['spawnmanager']:addSpawnPoint({
x = 195.72,
y = -933.07,
z = 30.68,
heading = 140.0,
model = 'a_m_y_skater_01'
})
```
### Response
- **spawnIdx** (number) - The unique index assigned to the added spawn point.
```
```APIDOC
## Spawn Manager - Load Spawns
### Description
Loads multiple spawn points from a JSON string.
### Method
exports['spawnmanager']:loadSpawns
### Parameters
- **spawnsJson** (string) - Required - A JSON string containing an array of spawn point objects.
- **spawns** (array) - An array of spawn point objects, each with x, y, z, heading, and model properties.
### Request Example
```lua
-- Client-side: Load multiple spawn points from JSON
local spawnsJson = [[{
"spawns": [
{ "x": 195.72, "y": -933.07, "z": 30.68, "heading": 140.0, "model": "a_m_y_skater_01" },
{ "x": -273.43, "y": -957.12, "z": 31.22, "heading": 205.0, "model": "a_m_y_hipster_01" }
]
}]]
exports['spawnmanager']:loadSpawns(spawnsJson)
```
### Response
This function does not return a value.
```
```APIDOC
## Spawn Manager - Remove Spawn Point
### Description
Removes a previously added spawn point using its unique index.
### Method
exports['spawnmanager']:removeSpawnPoint
### Parameters
- **spawnIdx** (number) - Required - The unique index of the spawn point to remove.
### Request Example
```lua
-- Later: Remove a spawn point
exports['spawnmanager']:removeSpawnPoint(spawnIdx)
```
### Response
This function does not return a value.
```
--------------------------------
### Add and Load Spawn Points - FiveM/RedM
Source: https://context7.com/citizenfx/cfx-server-data/llms.txt
Manages spawn points for players. Allows adding individual spawn points with precise coordinates, heading, and model information, or loading multiple spawns from a JSON string. Spawn points can also be programmatically removed. This functionality is client-side.
```lua
-- Client-side: Add a single spawn point
local spawnIdx = exports['spawnmanager']:addSpawnPoint({
x = 195.72,
y = -933.07,
z = 30.68,
heading = 140.0,
model = 'a_m_y_skater_01'
})
-- Client-side: Load multiple spawn points from JSON
local spawnsJson = [[{
"spawns": [
{ "x": 195.72, "y": -933.07, "z": 30.68, "heading": 140.0, "model": "a_m_y_skater_01" },
{ "x": -273.43, "y": -957.12, "z": 31.22, "heading": 205.0, "model": "a_m_y_hipster_01" }
]
}]]
exports['spawnmanager']:loadSpawns(spawnsJson)
-- Later: Remove a spawn point
exports['spawnmanager']:removeSpawnPoint(spawnIdx)
```
--------------------------------
### NUI Initialization and Event Handling (JavaScript)
Source: https://github.com/citizenfx/cfx-server-data/blob/master/resources/[system]/runcode/web/index.html
This JavaScript code handles the initialization of the NUI (Natural User Interface) for the 'runcode' feature. It checks if the NUI is available, fetches initial data from the parent resource, and configures UI elements based on permissions (e.g., disabling server-side options if not allowed). It also sets up event listeners for closing the NUI and initiating callbacks for saved data.
```javascript
const inNui = (!!window.invokeNative);
let openData = {};
if (inNui) {
document.querySelector('#passwordField').style.display = 'none';
document.querySelector('html').classList.add('in-nui');
fetch(`http://${window.parent.GetParentResourceName()}/getOpenData`, {
method: 'POST',
body: '{}'
}).then(a => a.json())
.then(a => {
openData = a;
if (!openData.options.canServer) {
document.querySelector('#cl-sv-toggle').style.display = 'none';
const trigger = document.createEvent('HTMLEvents');
trigger.initEvent('click', true, true);
document.querySelector('#cl-button').dispatchEvent(trigger);
} else if (!openData.options.canClient && !openData.options.canSelf) {
document.querySelector('#cl-sv-toggle').style.display = 'none';
document.querySelector('#cl-field').style.display = 'none';
const trigger = document.createEvent('HTMLEvents');
trigger.initEvent('click', true, true);
document.querySelector('#sv-button').dispatchEvent(trigger);
}
if (!openData.options.canClient && openData.options.canSelf) {
document.querySelector('#cl-field').style.display = 'none';
}
if (openData.options.saveData) {
const cb = () => {
if (initCb) {
initCb({ lastLang: openData.options.saveData.lastLang, lastSnippet: openData.options.saveData.lastSnippet });
} else {
setTimeout(cb, 50);
}
};
setTimeout(cb, 50);
}
fetch(`https://${window.parent.GetParentResourceName()}/doOk`, {
method: 'POST',
body: '{}'
});
});
document.querySelector('#close button').addEventListener('click', ev => {
fetch(`https://${window.parent.GetParentResourceName()}/doClose`, {
method: 'POST',
body: '{}'
});
ev.preventDefault();
});
}
const defFiles = ['index.d.ts'];
const defFilesServer = [...defFiles, 'natives_server.d.ts'];
const defFilesClient = [...defFiles, 'natives_universal.d.ts'];
const prefix = 'https://unpkg.com/@citizenfx/{}/';
```
--------------------------------
### Spawn Manager: Auto-Spawn Configuration (Lua)
Source: https://context7.com/citizenfx/cfx-server-data/llms.txt
Enables automatic player respawning on death. It supports default behavior and custom spawn callbacks for implementing custom spawn selection logic or loading screens. Dependencies: 'spawnmanager' export. Inputs: boolean for enabling, function for callback. Outputs: Player respawned. Limitations: Requires client-side execution.
```lua
-- Client-side: Enable auto-spawn with default behavior
exports['spawnmanager']:setAutoSpawn(true)
-- Client-side: Set custom spawn callback with team-based spawns
exports['spawnmanager']:setAutoSpawnCallback(function()
local playerTeam = GetPlayerTeam(PlayerId())
local teamSpawn = GetTeamSpawnPoint(playerTeam)
exports['spawnmanager']:spawnPlayer({
x = teamSpawn.x,
y = teamSpawn.y,
z = teamSpawn.z,
heading = teamSpawn.heading,
model = teamSpawn.model,
skipFade = false
}, function(spawn)
-- Post-spawn logic
TriggerEvent('chat:addMessage', {
args = { 'Spawned at ' .. teamSpawn.name }
})
end)
end)
-- Force immediate respawn (useful for admin commands)
exports['spawnmanager']:forceRespawn()
```
--------------------------------
### Fetch and Manage Client List (JavaScript)
Source: https://github.com/citizenfx/cfx-server-data/blob/master/resources/[system]/runcode/web/index.html
This JavaScript function fetches the list of available clients from the server and updates the client selection dropdown. It handles adding new clients and removing disconnected ones, ensuring the UI stays synchronized with the server's client list. It's designed to be called periodically.
```javascript
function fetchClients() {
fetch('/runcode/clients').then(res => res.json()).then(res => {
const el = document.querySelector('#cl-select');
const clients = res.clients;
const realClients = [['All', '-1'], ...clients];
const createdClients = new Set([...el.querySelectorAll('option').entries()].map(([i, el]) => el.value));
const existentClients = new Set(realClients.map(([ name, id ]) => id));
const toRemove = [...createdClients].filter(a => !existentClients.has(a));
for (const [name, id] of realClients) {
const ex = el.querySelector(`option[value="${id}"]`);
if (!ex) {
const l = document.createElement('option');
l.setAttribute('value', id);
l.appendChild(document.createTextNode(name));
el.appendChild(l);
}
}
for (const id of toRemove) {
const l = el.querySelector(`option[value="${id}"]`);
if (l) {
el.removeChild(l);
}
}
});
}
setInterval(() => fetchClients(), 1000);
```
--------------------------------
### Chat System API
Source: https://context7.com/citizenfx/cfx-server-data/llms.txt
Provides functions for managing chat messages, including sending messages to players, registering custom chat modes, and intercepting messages with hooks.
```APIDOC
## Chat System - Add Message
### Description
Sends a chat message to all players, a specific player, or as a local client-side message.
### Method
exports['chat']:addMessage
### Parameters
- **target** (number | object) - Required - The target player ID, or a table for client-side messages.
- **messageData** (table) - Required - A table containing message details.
- **color** (table) - Optional - RGB color values for the message.
- **multiline** (boolean) - Optional - Whether the message should be multiline.
- **args** (table) - Required - An array of arguments for the message template.
### Request Example
```lua
-- Server-side: Send a message to all players
exports['chat']:addMessage(-1, {
color = { 255, 100, 100 },
multiline = true,
args = { 'System', 'Server is restarting in 5 minutes!' }
})
-- Server-side: Send a message to specific player
local targetPlayer = 1
exports['chat']:addMessage(targetPlayer, {
color = { 100, 255, 100 },
args = { 'Admin', 'You have been granted moderator privileges' }
})
-- Client-side: Add a local message
exports['chat']:addMessage({
args = { 'This message only appears for you' }
})
```
### Response
This function does not return a value.
```
```APIDOC
## Chat System - Register Custom Mode
### Description
Registers a custom chat mode with specific display name, color, and routing logic.
### Method
exports['chat']:registerMode
### Parameters
- **modeData** (table) - Required - A table containing the mode's configuration.
- **name** (string) - Required - The internal name of the chat mode.
- **displayName** (string) - Required - The display name shown to users.
- **color** (string) - Optional - The color of the mode's display name (e.g., '#00FF00').
- **isChannel** (boolean) - Optional - Whether this mode represents a channel.
- **seObject** (string) - Optional - A string representing the object in the state system.
- **cb** (function) - Required - The callback function to handle message routing and modification.
- **source** (number) - The ID of the player sending the message.
- **outMessage** (table) - The message data being processed.
- **hookRef** (table) - A reference object for routing and updating the message.
### Request Example
```lua
-- Server-side: Register a team chat mode with ACE permissions
exports['chat']:registerMode({
name = 'team',
displayName = 'Team',
color = '#00FF00',
isChannel = true,
seObject = 'chat.team',
cb = function(source, outMessage, hookRef)
-- Custom logic to route message only to team members
local playerTeam = GetPlayerTeam(source)
local teamMembers = GetTeamMembers(playerTeam)
hookRef.setRouting(teamMembers)
hookRef.updateMessage({
template = '[TEAM] {0}: {1}',
color = '#00FF00'
})
end
})
```
### Response
This function does not return a value.
```
```APIDOC
## Chat System - Register Message Hook
### Description
Registers a hook to intercept and modify chat messages before they are delivered to recipients.
### Method
exports['chat']:registerMessageHook
### Parameters
- **callback** (function) - Required - The callback function to be executed for each message.
- **source** (number) - The ID of the player sending the message.
- **outMessage** (table) - The message data being processed.
- **hookRef** (table) - A reference object for cancelling the message or modifying its properties.
- **cancel** (function) - Cancels the current message.
- **setRouting** (function) - Sets the recipients for the message.
- **updateMessage** (function) - Updates the message template and color.
### Request Example
```lua
-- Server-side: Add a message hook for logging
exports['chat']:registerMessageHook(function(source, outMessage, hookRef)
-- Log all messages to database
local playerName = GetPlayerName(source)
local message = outMessage.args[#outMessage.args]
LogChatMessage(playerName, message)
-- Block messages containing blacklisted words
if ContainsProfanity(message) then
hookRef.cancel()
TriggerClientEvent('chat:addMessage', source, {
color = { 255, 0, 0 },
args = { 'System', 'Your message was blocked due to inappropriate content' }
})
end
end)
```
### Response
This function does not return a value.
```
--------------------------------
### Define Spawn Points and Map Objects in Lua
Source: https://context7.com/citizenfx/cfx-server-data/llms.txt
Defines spawn points for spawnmanager integration and adds custom map objects using Lua scripting. This snippet is intended for use within the map definition files.
```lua
-- map.lua - Define spawn points and map objects
fx_version 'cerulean'
game 'gta5'
-- Define spawn points for spawnmanager integration
spawnpoint 'a_m_y_skater_01' {
x = 195.72,
y = -933.07,
z = 30.68,
heading = 140.0
}
spawnpoint 'a_m_y_hipster_01' {
x = -273.43,
y = -957.12,
z = 31.22,
heading = 205.0
}
-- Add custom map objects
Citizen.CreateThread(function()
-- Create a custom object
local obj = CreateObject(GetHashKey('prop_bench_01a'), 200.0, -900.0, 30.0, false, false, false)
SetEntityHeading(obj, 90.0)
FreezeEntityPosition(obj, true)
end)
```
--------------------------------
### Base Events: Handle Player Death and Vehicle Interactions (Lua)
Source: https://context7.com/citizenfx/cfx-server-data/llms.txt
Server-side event handlers for critical game events like player deaths, kills, and vehicle interactions. These events allow for implementing game logic, tracking statistics, and triggering specific responses such as respawning or displaying death screens. Events include `baseevents:onPlayerDied`, `baseevents:onPlayerKilled`, `baseevents:enteredVehicle`, and `baseevents:leftVehicle`.
```lua
-- Server-side: Handle player death (no attacker)
AddEventHandler('baseevents:onPlayerDied', function(killedBy, pos)
local victim = source
print('Player ' .. GetPlayerName(victim) .. ' died at ' .. pos.x .. ', ' .. pos.y)
-- Respawn logic or death penalty
TriggerClientEvent('showDeathScreen', victim, 'You died')
end)
-- Server-side: Handle player killed by another player
AddEventHandler('baseevents:onPlayerKilled', function(killedBy, data)
local victim = source
local killer = killedBy
if data.weaponHash then
print(GetPlayerName(killer) .. ' killed ' .. GetPlayerName(victim) .. ' with weapon ' .. data.weaponHash)
end
-- Update kill stats
AddPlayerKill(killer)
AddPlayerDeath(victim)
end)
-- Server-side: Handle vehicle entry
AddEventHandler('baseevents:enteredVehicle', function(veh, seat, displayName)
local player = source
print(GetPlayerName(player) .. ' entered vehicle ' .. displayName .. ' in seat ' .. seat)
end)
-- Server-side: Handle vehicle exit
AddEventHandler('baseevents:leftVehicle', function(veh, seat, displayName)
local player = source
print(GetPlayerName(player) .. ' left vehicle ' .. displayName)
end)
```
--------------------------------
### Initialize Monaco Editor with Lua Language
Source: https://github.com/citizenfx/cfx-server-data/blob/master/resources/[system]/runcode/web/index.html
Initializes the Monaco editor with a container element, sets the initial code value to 'return 42', and specifies the language as 'lua'. It also sets the editor theme to 'vs-dark'.
```javascript
require.config({
paths: { 'vs': 'https://unpkg.com/monaco-editor@0.18.1/min/vs' }
});
require(['vs/editor/editor.main'], function() {
const editor = monaco.editor.create(document.getElementById('code-container'), {
value: 'return 42',
language: 'lua'
});
monaco.editor.setTheme('vs-dark');
});
```
--------------------------------
### Run Code via Fetch POST Request
Source: https://github.com/citizenfx/cfx-server-data/blob/master/resources/[system]/runcode/web/index.html
Attaches an event listener to a 'run' button to execute code. It fetches the code value from the editor and sends it via a POST request to either '/runcode/' or a NUI-specific endpoint. The response, which may contain errors or results, is then displayed in the designated result element.
```javascript
document.querySelector('#run').addEventListener('click', e => {
const text = editor.getValue();
fetch((!inNui) ? '/runcode/' : `https://${openData.res}/runCodeInBand`, {
method: 'post',
body: JSON.stringify({
password: document.querySelector('#password').value,
client: (useClient) ? document.querySelector('#cl-select').value : '',
code: text,
lang: lang
})
}).then(res => res.json()).then(res => {
if (inNui) {
res = JSON.parse(res); // double packing for sad msgpack-to-json
}
const resultElement = document.querySelector('#result');
if (res.error) {
resultElement.classList.remove('notification', 'is-success');
resultElement.classList.add('notification', 'is-danger');
} else {
resultElement.classList.remove('notification', 'is-danger');
resultElement.classList.add('notification', 'is-success');
}
resultElement.innerHTML = res.error || res.result;
if (res.from) {
resultElement.innerHTML += ' (from ' + res.from + ')';
}
});
e.preventDefault();
});
```
--------------------------------
### Player Names API: Customize Name Display (Lua)
Source: https://context7.com/citizenfx/cfx-server-data/llms.txt
Provides server or client-side functions for customizing player name tags. This includes setting custom name templates, modifying component colors and transparency, toggling visibility of HUD elements, setting wanted levels, and extending name tag context with custom data. Utilizes functions like `setName`, `setComponentColor`, `setComponentAlpha`, `setComponentVisibility`, `setWantedLevel`, `setNameTemplate`, and event handlers for extending context.
```lua
-- Server or Client: Set custom name template for player
local playerId = GetPlayerServerId(PlayerId())
setName(playerId, 'VIP_' .. GetPlayerName(playerId))
-- Server or Client: Set name tag component color
setComponentColor(playerId, 'healthBar', 255, 0, 0, 255) -- Red health bar
-- Server or Client: Set component transparency
setComponentAlpha(playerId, 'nameTag', 200) -- Slightly transparent
-- Server or Client: Toggle component visibility
setComponentVisibility(playerId, 'wantedLevel', false) -- Hide wanted stars
-- Server or Client: Set wanted level
setWantedLevel(playerId, 3) -- 3-star wanted level
-- Server or Client: Custom name template with formatting
setNameTemplate(playerId, '[ADMIN] {{name}}')
-- Server or Client: Extend name tag context
AddEventHandler('playernames:extendContext', function(playerId, addContext)
local rank = GetPlayerRank(playerId)
addContext('rank', rank)
addContext('level', GetPlayerLevel(playerId))
end)
```
--------------------------------
### Map Manager: Change Map and Game Type (Lua)
Source: https://context7.com/citizenfx/cfx-server-data/llms.txt
Server-side functions to control map loading and game type selection. It allows changing to specific maps, setting game types (which automatically load compatible maps), retrieving current game state, checking map compatibility, and triggering round transitions. Relies on the 'mapmanager' export.
```lua
-- Server-side: Change to specific map
exports['mapmanager']:changeMap('fivem-map-skater')
-- Server-side: Change game type (automatically loads compatible map)
exports['mapmanager']:changeGameType('basic-gamemode')
-- Server-side: Get current map and game type
local currentMap = exports['mapmanager']:getCurrentMap()
local currentGameType = exports['mapmanager']:getCurrentGameType()
print('Current map: ' .. (currentMap or 'none'))
print('Current game type: ' .. (currentGameType or 'none'))
-- Server-side: Check map compatibility
local isCompatible = exports['mapmanager']:doesMapSupportGameType('basic-gamemode', 'fivem-map-hipster')
-- Server-side: Trigger round end (loads next map in rotation)
TriggerEvent('mapmanager:roundEnded')
-- Server-side: Get all available maps
local maps = exports['mapmanager']:getMaps()
for mapName, mapData in pairs(maps) do
print('Map: ' .. mapName .. ' - ' .. (mapData.name or 'unnamed'))
end
```
--------------------------------
### Handle Loading Screen Events with JavaScript
Source: https://github.com/citizenfx/cfx-server-data/blob/master/resources/[test]/example-loadscreen/index.html
This JavaScript code listens for messages from the game's loading screen system. It updates the UI to show progress, display messages, and append emojis based on the event type. It relies on the presence of specific HTML elements like '.letni h3', '.thingy', and '.letni p'.
```javascript
var count = 0;
var thisCount = 0;
const emoji = {
INIT_BEFORE_MAP_LOADED: [ '🍉' ],
INIT_AFTER_MAP_LOADED: [ '🍋', '🍊' ],
INIT_SESSION: [ '🍐', '🍅', '🍆' ],
};
const handlers = {
startInitFunctionOrder(data) {
count = data.count;
document.querySelector('.letni h3').innerHTML += emoji[data.type][data.order - 1] || '';
},
initFunctionInvoking(data) {
document.querySelector('.thingy').style.left = '0%';
document.querySelector('.thingy').style.width = ((data.idx / count) * 100) + '%';
},
startDataFileEntries(data) {
count = data.count;
document.querySelector('.letni h3').innerHTML += "\u{1f358}";
},
performMapLoadFunction(data) {
++thisCount;
document.querySelector('.thingy').style.left = '0%';
document.querySelector('.thingy').style.width = ((thisCount / count) * 100) + '%';
},
onLogLine(data) {
document.querySelector('.letni p').innerHTML = data.message + "..!";
}
};
window.addEventListener('message', function(e) {
(handlers[e.data.eventName] || function() {})(e.data);
});
```
--------------------------------
### Register Custom Chat Mode - FiveM/RedM
Source: https://context7.com/citizenfx/cfx-server-data/llms.txt
Registers a custom chat mode, allowing for specialized communication channels such as team or admin chat. This function enables custom message routing and formatting based on defined rules and permissions. It requires server-side execution.
```lua
-- Server-side: Register a team chat mode with ACE permissions
exports['chat']:registerMode({
name = 'team',
displayName = 'Team',
color = '#00FF00',
isChannel = true,
seObject = 'chat.team',
cb = function(source, outMessage, hookRef)
-- Custom logic to route message only to team members
local playerTeam = GetPlayerTeam(source)
local teamMembers = GetTeamMembers(playerTeam)
hookRef.setRouting(teamMembers)
hookRef.updateMessage({
template = '[TEAM] {0}: {1}',
color = '#00FF00'
})
end
})
```
--------------------------------
### Add Chat Message - FiveM/RedM
Source: https://context7.com/citizenfx/cfx-server-data/llms.txt
Adds messages to the chat system. Supports targeting all players, specific players, or only the local client. Messages can be customized with colors and multiline formatting. This function is primarily used server-side but can be invoked client-side for local messages.
```lua
-- Server-side: Send a message to all players
exports['chat']:addMessage(-1, {
color = { 255, 100, 100 },
multiline = true,
args = { 'System', 'Server is restarting in 5 minutes!' }
})
-- Server-side: Send a message to specific player
local targetPlayer = 1
exports['chat']:addMessage(targetPlayer, {
color = { 100, 255, 100 },
args = { 'Admin', 'You have been granted moderator privileges' }
})
-- Client-side: Add a local message
exports['chat']:addMessage({
args = { 'This message only appears for you' }
})
```
--------------------------------
### Toggle Client/Server Execution Mode (JavaScript)
Source: https://github.com/citizenfx/cfx-server-data/blob/master/resources/[system]/runcode/web/index.html
This JavaScript code handles the UI toggling between client-side and server-side code execution. It updates the selected button's appearance and enables/disables the client selection dropdown accordingly. It also provides a callback mechanism for other parts of the UI to react to mode changes.
```javascript
let useClient = false;
let editServerCb = null;
[['#cl-button', true], ['#sv-button', false]].forEach(([ selector, isClient ]) => {
const eh = () => {
if (isClient) {
document.querySelector('#cl-select').disabled = false;
useClient = true;
} else {
document.querySelector('#cl-select').disabled = true;
useClient = false;
}
document.querySelectorAll('#cl-sv-toggle button').forEach(el => {
el.classList.remove('is-selected', 'is-info');
});
const tgt = document.querySelector(selector);
tgt.classList.add('is-selected', 'is-info');
if (editServerCb) {
editServerCb();
}
};
// default to not-client
if (!isClient) {
eh();
}
document.querySelector(selector).addEventListener('click', ev => {
eh();
ev.preventDefault();
});
});
```
--------------------------------
### NUI HTML and CSS for Runcode
Source: https://github.com/citizenfx/cfx-server-data/blob/master/resources/[system]/runcode/web/nui.html
This snippet defines the basic HTML structure and CSS styling for the NUI (New User Interface) component in the Cfx-Server-Data project. It ensures the iframe fills the available space and the background is transparent.
```html
runcode nui html { overflow: hidden; }
body { background-color: transparent; margin: 0px; padding: 0px; }
iframe { width: 100%; height: 100%; position: absolute; top: 0px; bottom: 0px; left: 0px; right: 0px; overflow: hidden; }
```
--------------------------------
### Register Chat Message Hook - FiveM/RedM
Source: https://context7.com/citizenfx/cfx-server-data/llms.txt
Registers a hook to intercept and modify chat messages before they are delivered. This is useful for implementing features like profanity filters, command parsing, or logging. The hook operates server-side and can cancel messages or trigger client events.
```lua
-- Server-side: Add a message hook for logging
exports['chat']:registerMessageHook(function(source, outMessage, hookRef)
-- Log all messages to database
local playerName = GetPlayerName(source)
local message = outMessage.args[#outMessage.args]
LogChatMessage(playerName, message)
-- Block messages containing blacklisted words
if ContainsProfanity(message) then
hookRef.cancel()
TriggerClientEvent('chat:addMessage', source, {
color = { 255, 0, 0 },
args = { 'System', 'Your message was blocked due to inappropriate content' }
})
end
end)
```
--------------------------------
### Toggle Code Language (JavaScript)
Source: https://github.com/citizenfx/cfx-server-data/blob/master/resources/[system]/runcode/web/index.html
This JavaScript code manages the selection of the programming language (Lua or JavaScript) for the code editor. It updates the visual indication of the selected language and provides a callback for other UI components to be notified of language changes. It also includes a helper function to map language names to their corresponding syntax highlighting identifiers.
```javascript
let lang = 'lua';
let editLangCb = null;
let initCb = null;
function getLangCode(lang) {
switch (lang) {
case 'js':
return 'javascript';
case 'ts':
return 'typescript';
}
return lang;
}
[['#lua-button', 'lua'], ['#js-button', 'js']/*, ['#ts-button', 'ts']*/].forEach(([ selector, langOpt ]) => {
const eh = () => {
lang = langOpt;
document.querySelectorAll('#lang-toggle button').forEach(el => {
el.classList.remove('is-selected', 'is-info');
});
const tgt = document.querySelector(selector);
tgt.classList.add('is-selected', 'is-info');
if (editLangCb) {
editLangCb();
}
};
// default to not-client
if (langOpt === 'lua') {
eh();
}
document.querySelector(selector).addEventListener('click', ev => {
eh();
ev.preventDefault();
});
});
```
--------------------------------
### Update Script and Add Extra Libraries for JS/TS
Source: https://github.com/citizenfx/cfx-server-data/blob/master/resources/[system]/runcode/web/index.html
Handles updating the script based on client/server selection and language. For JavaScript and TypeScript, it configures compiler options and fetches and adds extra libraries. It manages disposal of these libraries using a finalizer array.
```javascript
let finalizers = [];
const updateScript = (client, lang) => {
finalizers.forEach(a => a());
finalizers = [];
if (lang === 'js' || lang === 'ts') {
const defaults = (lang === 'js') ? monaco.languages.typescript.javascriptDefaults : monaco.languages.typescript.typescriptDefaults;
defaults.setCompilerOptions({
noLib: true,
allowNonTsExtensions: true
});
for (const file of (client ? defFilesClient : defFilesServer)) {
const prefix = (client ? prefixClient : prefixServer);
fetch(`${prefix}${file}`)
.then(a => a.text())
.then(a => {
const l = defaults.addExtraLib(a, file);
finalizers.push(() => l.dispose());
});
}
}
}
```
--------------------------------
### JavaScript Event Listener for NUI Message Handling
Source: https://github.com/citizenfx/cfx-server-data/blob/master/resources/[system]/runcode/web/nui.html
This JavaScript code handles messages from the game environment to control an iframe. It manages opening the iframe by setting its source and visibility, and closing it when requested. It relies on a message event listener.
```javascript
let openData = null;
window.addEventListener('message', ev => {
switch (ev.data.type) {
case 'open':
const frame = document.createElement('iframe');
frame.name = 'rc';
frame.allow = 'microphone *;';
frame.src = ev.data.url;
frame.style.visibility = 'hidden';
openData = ev.data;
openData.frame = frame;
document.querySelector('#holder').appendChild(frame);
break;
case 'ok':
openData.frame.style.visibility = 'visible';
break;
case 'close':
document.querySelector('#holder').removeChild(openData.frame);
openData = null;
break;
}
});
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.