======================== CODE SNIPPETS ======================== TITLE: Run FiveM Server Startup Script (Linux) DESCRIPTION: Executes the run.sh script located in the current directory to start the FiveM server. This command should be run within a screen session. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/linux-installation.md#_snippet_12 LANGUAGE: Shell CODE: ``` ./run.sh ``` ---------------------------------------- TITLE: Creating Street Race - qb-core - FiveM Command DESCRIPTION: Initiates the setup or start of a street race event. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qb-core/commands.md#_snippet_53 LANGUAGE: English CODE: ``` /createrace ``` ---------------------------------------- TITLE: Installing MariaDB Server - Linux Shell DESCRIPTION: Installs the MariaDB database server package on the Linux system using the apt package manager. Follow the prompts during installation. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/linux-installation.md#_snippet_1 LANGUAGE: Shell CODE: ``` sudo apt-get install mariadb-server ``` ---------------------------------------- TITLE: Example Configuration File Structure (Lua) DESCRIPTION: Provide an example structure for a `config.lua` file in Lua, demonstrating how to centralize configurable values like coordinates and payment amounts. This practice avoids hardcoding and simplifies script management. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/script-optimization.md#_snippet_7 LANGUAGE: Lua CODE: ``` Config = { Zones = { PoliceStation = vector3(441.1, -981.1, 30.7), Hospital = vector3(1151.21, -1529.62, 34.84) }, Payments = { Police = 150, EMS = 120 } } ``` ---------------------------------------- TITLE: Example: Getting and Setting Vehicle Properties (Lua) DESCRIPTION: Demonstrates how to retrieve the current properties of the player's current vehicle using QBCore.Functions.GetVehicleProperties and then apply them back using QBCore.Functions.SetVehicleProperties. This serves as a basic example of the functions' usage. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qb-core/client-function-reference.md#_snippet_29 LANGUAGE: Lua CODE: ``` -- Example local vehicle = GetVehiclePedIsUsing(PlayerPedId()) local vehicleProps = QBCore.Functions.GetVehicleProperties(vehicle) QBCore.Functions.SetVehicleProperties(vehicle, vehicleProps) ``` ---------------------------------------- TITLE: Updating System Packages - Linux Shell DESCRIPTION: Updates the package list on the Linux system to ensure you are installing the latest versions of software. This is a recommended first step before installing new packages like MariaDB. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/linux-installation.md#_snippet_0 LANGUAGE: Shell CODE: ``` sudo apt-get update ``` ---------------------------------------- TITLE: Shop Item Configuration with License Requirement in Lua DESCRIPTION: This Lua snippet from `qb-shops/config.lua` provides an example configuration for a shop item (a pistol). The `requiresLicense` property is set to `true`, indicating that a player must possess the corresponding license (in this case, the weapon license) to purchase this item from the shop. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/miscellaneous-guides.md#_snippet_2 LANGUAGE: Lua CODE: ``` [4] = { name = "weapon_pistol", price = 2500, amount = 5, info = {}, type = "item", slot = 4, requiresLicense = true }, ``` ---------------------------------------- TITLE: Example: Getting Core Object - Lua DESCRIPTION: Demonstrates two ways to retrieve the QBCore object using the `exports` mechanism. The first shows getting it locally, and the second shows assigning it globally (or in a wider scope) in a file loaded early. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qb-core/client-function-reference.md#_snippet_10 LANGUAGE: Lua CODE: ``` local QBCore = exports['qb-core']:GetCoreObject() OR -- call the core in a single file that loads before the others QBCore = exports['qb-core']:GetCoreObject() ``` ---------------------------------------- TITLE: Starting Current Street Race - qb-core - FiveM Command DESCRIPTION: Begins the street race that has been set up. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qb-core/commands.md#_snippet_56 LANGUAGE: English CODE: ``` /startrace ``` ---------------------------------------- TITLE: Example: Saving Player Inventory (Server) - qb-inventory - Lua DESCRIPTION: This server-side command provides a simple example of how to call the `SaveInventory` export to persist a player's inventory data to the database. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-inventory.md#_snippet_6 LANGUAGE: Lua CODE: ``` RegisterCommand('saveInv', function(source) exports['qb-inventory']:SaveInventory(source, false) end) ``` ---------------------------------------- TITLE: Starting a Single Skillbar (Lua) DESCRIPTION: This snippet demonstrates how to start a single instance of the qb-skillbar mini-game using the exported object. It configures the skillbar's duration, static box position, and width, and defines callback functions for success and cancellation. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-skillbar.md#_snippet_0 LANGUAGE: lua CODE: ``` RegisterCommand('skillbar', function() local Skillbar = exports['qb-skillbar']:GetSkillbarObject() Skillbar.Start({ duration = math.random(7500, 15000), -- how long the skillbar runs for pos = math.random(10, 30), -- how far to the right the static box is width = math.random(10, 20), -- how wide the static box is }, function() print('Player succeeded!') end, function() print('Player cancelled the skillbar!') end) end) ``` ---------------------------------------- TITLE: Starting Multiple Sequential Skillbars (Lua) DESCRIPTION: This snippet illustrates how to initiate and manage a series of skillbar attempts. It tracks the number of successful attempts and uses the Skillbar.Repeat() function within the success callback to start the next skillbar instance until a predefined number of successes is achieved. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-skillbar.md#_snippet_1 LANGUAGE: lua CODE: ``` local neededAttempts = 5 -- how many succesful attempts it takes to pass local succeededAttempts = 0 -- changes dynamically do not edit RegisterCommand('skillbarmulti', function() local Skillbar = exports['qb-skillbar']:GetSkillbarObject() Skillbar.Start({ duration = math.random(7500, 15000), -- how long the skillbar runs for pos = math.random(10, 30), -- how far to the right the static box is width = math.random(10, 20), -- how wide the static box is }, function() if succeededAttempts + 1 >= neededAttempts then print('Player succeeded enough times!') else Skillbar.Repeat({ duration = math.random(500, 1000), pos = math.random(10, 30), width = math.random(5, 12), }) succeededAttempts = succeededAttempts + 1 end end, function() print('Player cancelled the skillbar!') end) end) ``` ---------------------------------------- TITLE: Extract FiveM Artifacts with Tar (Linux) DESCRIPTION: Uses the tar command with the -xf flags to extract the contents of the downloaded fx.tar.xz archive into the current directory. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/linux-installation.md#_snippet_11 LANGUAGE: Shell CODE: ``` tar -xf fx.tar.xz ``` ---------------------------------------- TITLE: Configuring Apartments Integration (Lua) DESCRIPTION: Details the configuration for integrating with starting apartments, allowing enabling/disabling the feature and setting a fallback default spawn location if starting apartments are disabled. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-multicharacter.md#_snippet_1 LANGUAGE: lua CODE: ``` Config.StartingApartment = true -- enable/disable starting apartments -- Default spawn coords if you have the above false Config.DefaultSpawn = vector3(-1035.71, -2731.87, 12.86) ``` ---------------------------------------- TITLE: Download FiveM Artifacts with Wget (Linux) DESCRIPTION: Uses the wget command to download the FiveM server artifact archive directly from the provided URL. The URL should be replaced with the link to the desired latest artifact version. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/linux-installation.md#_snippet_10 LANGUAGE: Shell CODE: ``` wget https://runtime.fivem.net/artifacts/fivem/build_proot_linux/master/5742-ded89bc6acf29a720a7686a1de70d28b62c75af8/fx.tar.xz ``` ---------------------------------------- TITLE: Recommended QBCore Resource Folder Structure DESCRIPTION: Provides an example directory layout for a qbcore resource. It includes standard client, server, and shared folders for separating code based on where it runs, along with an fxmanifest.lua file for resource configuration. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/script-optimization.md#_snippet_15 LANGUAGE: Text CODE: ``` my_script/ ├── client/ │ ├── main.lua │ ├── utils.lua ├── server/ │ ├── main.lua │ ├── events.lua ├── shared/ │ ├── config.lua └── fxmanifest.lua ``` ---------------------------------------- TITLE: Example: Calling GetPlayers - Lua DESCRIPTION: Shows how to call `QBCore.Functions.GetPlayers` and print the result. It also includes the preferred method of directly calling `GetActivePlayers()`. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qb-core/client-function-reference.md#_snippet_12 LANGUAGE: Lua CODE: ``` local players = QBCore.Functions.GetPlayers() print(QBCore.Debug(players)) OR -- preferred method local players = GetActivePlayers() print(QBCore.Debug(players)) ``` ---------------------------------------- TITLE: Connecting to MariaDB as Root - Linux Shell DESCRIPTION: Connects to the MariaDB server as the root user, prompting for the password set during the secure installation. This command is used to access the MariaDB console. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/linux-installation.md#_snippet_3 LANGUAGE: Shell CODE: ``` mysql -u root -p ``` ---------------------------------------- TITLE: Securing MariaDB Installation - Linux Shell DESCRIPTION: Runs a script to improve the security of the MariaDB installation. It prompts for setting the root password, removing anonymous users, restricting root access, and removing the test database. It is recommended to answer “Y” to all questions. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/linux-installation.md#_snippet_2 LANGUAGE: Shell CODE: ``` sudo mysql_secure_installation ``` ---------------------------------------- TITLE: Basic server.cfg Template (cfg) DESCRIPTION: This snippet provides a basic template for the server.cfg file used in FiveM servers, particularly for QBCore. It includes essential settings like maximum clients, Steam Web API key, and server tags, often pre-filled by deployment tools like txAdmin. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/miscellaneous-guides.md#_snippet_10 LANGUAGE: cfg CODE: ``` # ____ ____ _____ # / __ \| _ \ / ____| # | | | | |_) | | ___ _ __ ___ # | | | | _ <| | / _ \| '__/ _ \ # | |__| | |_) | |___| (_) | | | __/ # \___\_\____/ \____\___/|_| \___| ## You CAN edit the following: {{serverEndpoints}} sv_maxclients {{maxClients}} set steam_webApiKey "none" sets tags "default, deployer, qbcore, qb-core" ``` ---------------------------------------- TITLE: Example: Calling GetPeds - Lua DESCRIPTION: Demonstrates how to call `QBCore.Functions.GetPeds` with an ignore list containing a specific ped model hash and prints the resulting table of peds. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qb-core/client-function-reference.md#_snippet_14 LANGUAGE: Lua CODE: ``` local peds = QBCore.Functions.GetPeds({`mp_m_freemode_01`}) print(QBCore.Debug(peds)) ``` ---------------------------------------- TITLE: Basic FiveM Server Configuration (cfg) DESCRIPTION: This configuration block sets fundamental server parameters such as the license key, hostname, project name and description, locale, server icon, game build, and database connection string. It also configures voice chat settings, QBCore locale, resource loading order, and basic permissions for admin groups and specific identifiers. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/miscellaneous-guides.md#_snippet_11 LANGUAGE: cfg CODE: ``` ## You MAY edit the following: sv_licenseKey "{{svLicense}}" sv_hostname "{{serverName}} built with {{recipeName}} by {{recipeAuthor}}!" sets sv_projectName "[{{recipeName}}] {{serverName}}" sets sv_projectDesc "{{recipeDescription}}" sets locale "en-US" load_server_icon myLogo.png set sv_enforceGameBuild 2372 set mysql_connection_string "{{dbConnectionString}}" # Voice config setr voice_useNativeAudio true setr voice_useSendingRangeOnly true setr voice_defaultCycle "GRAVE" setr voice_defaultVolume 0.3 setr voice_enableRadioAnim 1 setr voice_syncData 1 # QBCore locale config setr qb_locale "en" # QBCore UseTarget setr UseTarget false # These resources will start by default. ensure mapmanager ensure chat ensure spawnmanager ensure sessionmanager ensure basic-gamemode ensure hardcap ensure baseevents # QBCore & Extra stuff ensure qb-core ensure [qb] ensure [standalone] ensure [voice] ensure [defaultmaps] ## Permissions ## add_ace group.admin command allow # allow all commands #add_principal identifier.{{principalMasterIdentifier}} qbcore.god <- doesn't exist yet, change the generated one below to qbcore.god {{addPrincipalsMaster}} # Resources add_ace resource.qb-core command allow # Allow qb-core to execute commands # Gods add_ace qbcore.god command allow # Allow all commands # Inheritance add_principal qbcore.god group.admin # Allow gods access to the main admin group used to get all default permissions add_principal qbcore.god qbcore.admin # Allow gods access to admin commands add_principal qbcore.admin qbcore.mod # Allow admins access to mod commands ``` ---------------------------------------- TITLE: Example: Loading Player Inventory (Server) - qb-inventory - Lua DESCRIPTION: This server-side command demonstrates how to use the `LoadInventory` export to fetch a player's inventory data and print it to the console. It requires the player's source ID and citizen ID. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-inventory.md#_snippet_4 LANGUAGE: Lua CODE: ``` RegisterCommand('getInv', function(source) local Player = QBCore.Functions.GetPlayer(source) local citizenId = Player.PlayerData.citizenid local items = exports['qb-inventory']:LoadInventory(source, citizenid) print(json.encode(items, { indent = true })) end) ``` ---------------------------------------- TITLE: Toggling Lap Race Setup - qb-core - FiveM Command DESCRIPTION: Turns the race setup mode on or off, allowing or disallowing the configuration of a lap race. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qb-core/commands.md#_snippet_36 LANGUAGE: English CODE: ``` /togglesetup ``` ---------------------------------------- TITLE: Example: Calling GetVehicles - Lua DESCRIPTION: Shows how to call `QBCore.Functions.GetVehicles` and print the result. It also includes the preferred method of directly calling `GetGamePool('CVehicle')`. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qb-core/client-function-reference.md#_snippet_8 LANGUAGE: Lua CODE: ``` local vehicles = QBCore.Functions.GetVehicles() print(QBCore.Debug(vehicles)) OR -- preferred method local vehicles = GetGamePool('CVehicle') print(QBCore.Debug(vehicles)) ``` ---------------------------------------- TITLE: Example: Closing Player Inventory (Server) - qb-inventory - Lua DESCRIPTION: These server-side commands illustrate how to use the `CloseInventory` export to close a player's inventory, showing examples with and without specifying an inventory identifier. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-inventory.md#_snippet_10 LANGUAGE: Lua CODE: ``` RegisterCommand('closeInventory', function(source) exports['qb-inventory']:CloseInventory(source) print('Inventory closed for player '..source) end, true) RegisterCommand('closeInventoryByName', function(source, identifier) exports['qb-inventory']:CloseInventory(source, identifier) print('Inventory closed for player '..source..' and inventory '..identifier..' set to closed') end, true) ``` ---------------------------------------- TITLE: Registering Custom Command (Lua) DESCRIPTION: This example demonstrates how to register a new server command using the `QBCore.Commands.Add` function. It defines a 'greet' command that takes an optional name argument and sends a chat message to the player. Requires the full Core Object or at least the 'Commands' component. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qb-core/core-object.md#_snippet_5 LANGUAGE: Lua CODE: ``` local QBCore = exports['qb-core']:GetCoreObject() QBCore.Commands.Add('greet', 'Send a greeting', {}, false, function(source, args) local name = args[1] or 'player' TriggerClientEvent('chat:addMessage', source, { template = '
Hello, {0}!
', args = { name } }) end) ``` ---------------------------------------- TITLE: Triggering Server Log Event from Server (Lua) DESCRIPTION: Example of how to trigger the server-side log creation event from a server script using `TriggerEvent`, providing the webhook type, title, color, and message. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-smallresources.md#_snippet_8 LANGUAGE: Lua CODE: ``` RegisterCommand('serverlogtest', function() TriggerEvent('qb-log:server:CreateLog', 'testwebhook', 'Test Webhook', 'default', 'Webhook Client Side setup successfully') end) ``` ---------------------------------------- TITLE: Example: Calling Progressbar - Lua DESCRIPTION: Demonstrates how to call the `QBCore.Functions.Progressbar` function with common parameters. It shows how to set the name, label, duration, cancellation options, control disables, and provide callback functions for success and cancellation. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qb-core/client-function-reference.md#_snippet_6 LANGUAGE: Lua CODE: ``` QBCore.Functions.Progressbar('Changeme', 'What the player sees', 1500, false, true, { disableMovement = true, disableCarMovement = true, disableMouse = false, disableCombat = true }, {}, {}, {}, function() -- This code runs if the progress bar completes successfully end, function() -- This code runs if the progress bar gets cancelled end) ``` ---------------------------------------- TITLE: Configuring Target Models in Config.TargetModels (etlua) DESCRIPTION: Provides an example configuration entry for the `Config.TargetModels` table, demonstrating how to define models, interaction options, distance, and various conditions like job, gang, or item requirements. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-target.md#_snippet_20 LANGUAGE: etlua CODE: ``` ["index"] = { -- This can be a string or a number models = { -- This is your models table, here you define all the target models to be interacted with, this can be a string or a table 'a_m_m_indian_01', } options = { -- This is your options table, in this table all the options will be specified for the target to accept { -- This is the first table with options, you can make as many options inside the options table as you want num = 1, -- This is the position number of your option in the list of options in the qb-target context menu (OPTIONAL) type = "client", -- This specifies the type of event the target has to trigger on click, this can be "client", "server", "command" or "qbcommand", this is OPTIONAL and will only work if the event is also specified event = "Test:Event", -- This is the event it will trigger on click, this can be a client event, server event, command or qbcore registered command, NOTICE: Normal command can't have arguments passed through, QBCore registered ones can have arguments passed through icon = 'fas fa-example', -- This is the icon that will display next to this trigger option label = 'Test', -- This is the label of this option which you would be able to click on to trigger everything, this has to be a string targeticon = 'fas fa-example', -- This is the icon of the target itself, the icon changes to this when it turns blue on this specific option, this is OPTIONAL item = 'handcuffs', -- This is the item it has to check for, this option will only show up if the player has this item, this is OPTIONAL action = function(entity) -- This is the action it has to perform, this REPLACES the event and this is OPTIONAL if IsPedAPlayer(entity) then return false end -- This will return false if the entity interacted with is a player and otherwise returns true TriggerEvent('testing:event', 'test') -- Triggers a client event called testing:event and sends the argument 'test' with it end, canInteract = function(entity, distance, data) -- This will check if you can interact with it, this won't show up if it returns false, this is OPTIONAL if IsPedAPlayer(entity) then return false end -- This will return false if the entity interacted with is a player and otherwise returns true return true end, job = 'police', -- This is the job, this option won't show up if the player doesn't have this job, this can also be done with multiple jobs and grades, if you want multiple jobs you always need a grade with it: job = {["police"] = 0, ["ambulance"] = 2}, gang = 'ballas', -- This is the gang, this option won't show up if the player doesn't have this gang, this can also be done with multiple gangs and grades, if you want multiple gangs you always need a grade with it: gang = {["ballas"] = 0, ["thelostmc"] = 2}, citizenid = 'JFD98238', -- This is the citizenid, this option won't show up if the player doesn't have this citizenid, this can also be done with multiple citizenid's, if you want multiple citizenid's there is a specific format to follow: citizenid = {["JFD98238"] = true, ["HJS29340"] = true}, } }, distance = 2.5, -- This is the distance for you to be at for the target to turn blue, this is in GTA units and has to be a float value }, ``` ---------------------------------------- TITLE: Checking iptables Version (Shell) DESCRIPTION: Command to check if the iptables firewall software is installed on the system and display its version. This is a prerequisite for configuring firewall rules. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/linux-installation.md#_snippet_8 LANGUAGE: Shell CODE: ``` sudo iptables --version ``` ---------------------------------------- TITLE: Enabling oxmysql UI (cfg) DESCRIPTION: This server.cfg line enables the oxmysql in-game UI by setting the mysql_ui convar to true. Accessing the UI typically requires appropriate ACE permissions. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/miscellaneous-guides.md#_snippet_9 LANGUAGE: cfg CODE: ``` set mysql_ui true ``` ---------------------------------------- TITLE: Restarting MariaDB Service (Shell) DESCRIPTION: Command to restart the MariaDB service after configuration changes have been made, such as modifying the bind address. This applies the new settings. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/linux-installation.md#_snippet_6 LANGUAGE: Shell CODE: ``` sudo systemctl restart mariadb ``` ---------------------------------------- TITLE: Defining a Basic Job (Unemployed) (Lua) DESCRIPTION: This example demonstrates the basic structure for defining a job within the `QBShared.Jobs` table. It shows the configuration for the 'unemployed' job, including its display label, default duty status, off-duty pay setting, and a simple grades table with a single entry. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qb-core/shared.md#_snippet_11 LANGUAGE: Lua CODE: ``` QBShared.Jobs = { unemployed = { label = 'Civilian', -- Display name defaultDuty = true, -- Automatically on duty at login offDutyPay = false, -- No payment while off duty grades = { { name = 'Freelancer', payment = 10 } -- Single grade with payment } } } ``` ---------------------------------------- TITLE: Creating MariaDB Admin User and Granting Privileges - SQL DESCRIPTION: A sequence of SQL commands executed within the MariaDB console to create a new user, verify its creation, grant global administrative privileges, and reload the privilege tables. The username, password, and host ('localhost' or '%') should be modified. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/linux-installation.md#_snippet_5 LANGUAGE: SQL CODE: ``` CREATE USER 'user1'@localhost IDENTIFIED BY 'password1'; (Check the user created by running this line) SELECT User FROM mysql.user; GRANT ALL PRIVILEGES ON *.* TO 'user1'@localhost IDENTIFIED BY 'password1'; GRANT ALL PRIVILEGES ON *.* TO 'user1'@localhost IDENTIFIED BY 'password1'; FLUSH PRIVILEGES; ``` ---------------------------------------- TITLE: Checking MariaDB Service Status (Shell) DESCRIPTION: Command to check the current status of the MariaDB service. Useful for verifying if the service is running correctly after a restart or configuration change. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/linux-installation.md#_snippet_7 LANGUAGE: Shell CODE: ``` sudo systemctl status mariadb ``` ---------------------------------------- TITLE: Example: Clearing Player Inventory (Server) - qb-inventory - Lua DESCRIPTION: These server-side commands demonstrate how to use the `ClearInventory` export to remove items from a player's inventory, showing examples of excluding a single item or a list of items. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-inventory.md#_snippet_8 LANGUAGE: Lua CODE: ``` RegisterCommand('clearInventoryExcludeItem', function(source, args) local filterItem = args[1] if not filterItem then return end exports['qb-inventory']:ClearInventory(source, filterItem) print('Inventory cleared for player '..source..', excluding item: '..filterItem) end, true) RegisterCommand('clearInventoryExcludeItems', function(source) local filterItems = {'item1', 'item2'} exports['qb-inventory']:ClearInventory(source, filterItems) print('Inventory cleared for player '..source..', excluding items: '..table.concat(filterItems, ', ')) end, true) ``` ---------------------------------------- TITLE: Triggering Server Log Event from Client (Lua) DESCRIPTION: Example of how to trigger the server-side log creation event from a client script using `TriggerServerEvent`, providing the webhook type, title, color, and message. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-smallresources.md#_snippet_7 LANGUAGE: Lua CODE: ``` RegisterCommand('clientlogtest', function() TriggerServerEvent('qb-log:server:CreateLog', 'testwebhook', 'Test Webhook', 'default', 'Webhook Client Side setup successfully') end) ``` ---------------------------------------- TITLE: Iterating Through Starter Items in QBCore Lua DESCRIPTION: This Lua example demonstrates how to iterate through the `QBCore.Shared.StarterItems` table. It uses a `for` loop with `pairs` to access each item name and its corresponding amount, then prints a message using item label retrieved from `QCore.Shared.Items`. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qb-core/shared.md#_snippet_1 LANGUAGE: Lua CODE: ``` for item, amount in pairs(QBCore.Shared.StarterItems) do local item_info = QCore.Shared.Items[item] print('Received '..amount..' '..item_info.label) end ``` ---------------------------------------- TITLE: Configuring General Weather Settings - qb-weathersync - Lua DESCRIPTION: This configuration block defines the general behavior of the weather synchronization script. It allows setting dynamic weather, initial weather and time on server start, time offsets, time freezing, blackout states, and the interval for automatic weather changes. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-weathersync.md#_snippet_0 LANGUAGE: Lua CODE: ``` Config = {} Config.DynamicWeather = true -- set this to false if you don't want the weather to change automatically every 10 minutes. -- On server start Config.StartWeather = 'EXTRASUNNY' -- default weather Config.BaseTime = 8 -- time Config.TimeOffset = 0 -- time offset Config.FreezeTime = false -- freeze time Config.Blackout = false -- set blackout Config.BlackoutVehicle = false -- set blackout affects vehicles Config.NewWeatherTimer = 10 -- time (in minutes) between each weather change Config.Disabled = false -- set weather disabled ``` ---------------------------------------- TITLE: Enabling Onesync-infinity in Server Config DESCRIPTION: This command is used in the FiveM server.cfg file to enable the Onesync-infinity mode. Onesync-infinity is crucial for supporting a large number of players by managing entity visibility and synchronization within a limited 'scope' around each player. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/miscellaneous-guides.md#_snippet_3 LANGUAGE: Server Config CODE: ``` set onesync on ``` ---------------------------------------- TITLE: Localizing Variables and Functions in Lua DESCRIPTION: Explain why using `local` is preferred for performance in Lua by reducing global scope lookups. Show examples of global vs. local declarations for variables and functions. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/script-optimization.md#_snippet_0 LANGUAGE: Lua CODE: ``` myVariable = false -- Don't use this local myVariable = false -- Use this function someFunction() -- Don't use this print('Im a global function!') end local function someFunction() -- Use this print('Im a local function!') end ``` ---------------------------------------- TITLE: Configuration for qb-garages (Lua) DESCRIPTION: This configuration block defines global settings for the garage script, such as auto-respawn and shared garages, and provides an example structure for defining individual garage locations and properties like labels, spawn points, blips, and types. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-garages.md#_snippet_0 LANGUAGE: lua CODE: ``` AutoRespawn = false --True == auto respawn cars that are outside into your garage on script restart, false == does not put them into your garage and players have to go to the impound SharedGarages = false --True == Gang and job garages are shared, false == Gang and Job garages are personal VisuallyDamageCars = true --True == Visually damage cars that go out of the garage depending of body damage, false == Do not visually damage cars (damage is still applied to car values) Garages = { ["motelgarage"] = { -- Name of the garage label = "Motel Parking", -- Label of the garage takeVehicle = vector3(273.43, -343.99, 44.91), -- vehicle withdraw point spawnPoint = vector4(270.94, -342.96, 43.97, 161.5), -- vehicle spawn point putVehicle = vector3(276.69, -339.85, 44.91), -- vehicle store point showBlip = true, -- enable/disable the blip on the map blipName = "Public Parking", -- name of blip blipNumber = 357, -- https://docs.fivem.net/docs/game-references/blips/ type = 'public', -- public, job, gang, depot vehicle = 'car' -- car, air, sea }, } ``` ---------------------------------------- TITLE: Example Usage of GetVehicleProperties in Lua DESCRIPTION: This snippet demonstrates how to call the `QBCore.Functions.GetVehicleProperties` function. It first gets the vehicle the player is currently using via `GetVehiclePedIsUsing` and `PlayerPedId`, and then passes the resulting vehicle entity handle to the function. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qb-core/client-function-reference.md#_snippet_25 LANGUAGE: Lua CODE: ``` -- Example local vehicle = GetVehiclePedIsUsing(PlayerPedId()) ``` ---------------------------------------- TITLE: Calling setTime Export - qb-weathersync - Lua DESCRIPTION: This Lua example demonstrates calling the `setTime` export to set the in-game time. The function takes the hour as a required argument and the minute as an optional argument. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-weathersync.md#_snippet_6 LANGUAGE: Lua CODE: ``` local success = exports["qb-weathersync"]:setTime(8, 10); -- 8:10 AM ``` ---------------------------------------- TITLE: Calling setTime Export - qb-weathersync - JavaScript DESCRIPTION: This JavaScript example demonstrates calling the `setTime` export to set the in-game time. The function takes the hour as a required argument and the minute as an optional argument. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-weathersync.md#_snippet_7 LANGUAGE: JavaScript CODE: ``` const success = global.exports["qb-weathersync"].setTime(15, 30); // 3:30PM ``` ---------------------------------------- TITLE: Accessing Player Job Data (Lua) DESCRIPTION: This example demonstrates how to retrieve a player's job information using the QBCore Core Object. It first gets the player object via `QBCore.Functions.GetPlayer` and then accesses the job details from the `PlayerData` property. Requires the full Core Object or at least the 'Functions' component. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qb-core/core-object.md#_snippet_3 LANGUAGE: Lua CODE: ``` local QBCore = exports['qb-core']:GetCoreObject() local function getPlayerJob(source) local player = QBCore.Functions.GetPlayer(source) if player then local job = player.PlayerData.job print("Player's job:", job.name) end end ``` ---------------------------------------- TITLE: Example: Calling GetClosestPed - Lua DESCRIPTION: Shows how to call `QBCore.Functions.GetClosestPed` using the player's current coordinates and prints the handle of the closest ped found and the distance to it. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qb-core/client-function-reference.md#_snippet_16 LANGUAGE: Lua CODE: ``` local coords = GetEntityCoords(PlayerPedId()) local closestPed, distance = QBCore.Functions.GetClosestPed(coords) print(closestPed, distance) ``` ---------------------------------------- TITLE: Getting Into Vehicle Trunk - qb-core - FiveM Command DESCRIPTION: Allows the player to enter the trunk of a vehicle. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qb-core/commands.md#_snippet_47 LANGUAGE: English CODE: ``` /getintrunk ``` ---------------------------------------- TITLE: Configuring qb-apartments locations and settings - Lua DESCRIPTION: This Lua code snippet defines the main configuration table for the qb-apartments resource. It includes settings to enable/disable starting apartments, set the spawn offset for interiors, and define multiple apartment locations with their names, labels, entrance coordinates (vector4), and polyzone box data for interaction. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-apartments.md#_snippet_0 LANGUAGE: Lua CODE: ``` Apartments = {} Apartments.Starting = true/false -- Enable or disable starting apartments Apartments.SpawnOffset = 30 -- How far under the map the apartment shell will spawn Apartments.Locations = { -- Create new apartment locations ["apartment1"] = { name = "apartment1", -- The apartment name that saves in the database label = "South Rockford Drive", -- The label of the apartment (shown in preview) coords = { -- The apartment entrance location enter = vector4(-667.02, -1105.24, 14.63, 242.32), }, polyzoneBoxData = { -- The polyzone box information for the entrance heading = 245, minZ = 13.5, maxZ = 16.0, debug = false, length = 1, width = 3, distance = 2.0, created = false } }, } ``` ---------------------------------------- TITLE: Spawning Vehicle at Distance Server-Side (etlua) DESCRIPTION: This server-side QBCore callback (qb-truckrobbery:server:spawntruck) demonstrates how to spawn a vehicle (stockade) at a predefined distant coordinate using native functions (Citizen.InvokeNative, GetHashKey). It waits for the entity to exist, gets its network ID, and returns it via the callback, noting that the entity is server-owned until a client is in range. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/miscellaneous-guides.md#_snippet_6 LANGUAGE: etlua CODE: ``` local SpawnPoints = { vector4(-1327.479736328, -86.045326232910, 49.31, 52), vector4(-2075.888183593, -233.73908996580, 21.10, 52), vector4(-972.1781616210, -1530.9045410150, 4.890, 52), vector4(798.18426513672, -1799.8173828125, 29.33, 52), vector4(1247.0718994141, -344.65634155273, 69.08, 52), } QBCore.Functions.CreateCallback('qb-truckrobbery:server:spawntruck', function(source, cb) local coords = SpawnPoints[math.random(#SpawnPoints)] local CreateAutomobile = GetHashKey("CREATE_AUTOMOBILE") local truck = Citizen.InvokeNative(CreateAutomobile, GetHashKey('stockade'), coords, coords.w, true, false) while not DoesEntityExist(truck) do Wait(25) end if DoesEntityExist(truck) then local netId = NetworkGetNetworkIdFromEntity(truck) cb(netId) else cb(0) end end) ``` ---------------------------------------- TITLE: Configuring Starter Items in QBCore Lua DESCRIPTION: This Lua snippet defines the `QBShared.StarterItems` table, which lists the items and their quantities given to a player upon their first join. It's a simple key-value structure where keys are item names (strings) and values are amounts (numbers). SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qb-core/shared.md#_snippet_0 LANGUAGE: Lua CODE: ``` QBShared.StarterItems = { phone = 1, id_card = 1, driver_license = 1, } ``` ---------------------------------------- TITLE: Creating Static Menu and Handling Events (etlua) DESCRIPTION: This snippet demonstrates how to define a static menu structure with headers and buttons, register a command to open it, and handle button clicks via client-side events, including opening a sub-menu and returning to the main menu. It utilizes the `qb-menu` export to display the menu. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-menu.md#_snippet_0 LANGUAGE: etlua CODE: ``` RegisterCommand('qbmenutest', function() exports['qb-menu']:openMenu({ { header = 'QBCore Test Menu', icon = 'fas fa-code', isMenuHeader = true, -- Set to true to make a nonclickable title }, { header = 'First Button', txt = 'Print a message!', icon = 'fas fa-code-merge', params = { event = 'qb-menu:client:testButton', args = { message = 'This was called by clicking a button' } } }, { header = 'Second Button', txt = 'Open a secondary menu!', icon = 'fas fa-code-pull-request', -- disabled = false, -- optional, non-clickable and grey scale -- hidden = true, -- optional, hides the button completely params = { -- isServer = false, -- optional, specify event type event = 'qb-menu:client:subMenu', args = { number = 2, } } }, }) end) RegisterNetEvent('qb-menu:client:subMenu', function(data) local number = data.number exports['qb-menu']:openMenu({ { header = 'Return to main menu', icon = 'fa-solid fa-backward', params = { event = 'qb-menu:client:mainMenu', args = {} } }, { header = 'Sub-menu button', txt = 'Print a message!', icon = 'fas fa-code-merge', params = { event = 'qb-menu:client:testButton', args = { message = 'This was called by clicking a button' } } } }) end) RegisterNetEvent('qb-menu:client:mainMenu', function() ExecuteCommand('qbmenutest') end) RegisterNetEvent('qb-menu:client:testButton', function(data) print(data.message) end) ``` ---------------------------------------- TITLE: Registering/Triggering RevivePlayer Server Event (Lua) DESCRIPTION: Documents the 'hospital:server:RevivePlayer' server event used to revive a specified player, potentially for a fee if 'isOldMan' is true. It requires the player's server ID and a boolean. The example shows how to get the closest player's server ID and trigger the event. Note: This event always removes a first aid kit from the source player. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-ambulancejob.md#_snippet_4 LANGUAGE: Lua CODE: ``` RegisterNetEvent('hospital:server:RevivePlayer', function(playerId, isOldMan) ``` LANGUAGE: Lua CODE: ``` local player, distance = QBCore.Functions.GetClosestPlayer() local playerId = GetPlayerServerId(player) TriggerServerEvent('hospital:server:RevivePlayer', playerId, true) ``` ---------------------------------------- TITLE: Configuring a qb-target BoxZone Entry DESCRIPTION: This snippet provides a detailed example of how to define a BoxZone entry in the `Config.BoxZones` table for the qb-target resource. It covers physical properties like coordinates, dimensions, and debug options, as well as a nested `options` table to specify interactive actions, required items, jobs, gangs, citizen IDs, and drawing properties. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-target.md#_snippet_4 LANGUAGE: Etlua CODE: ``` ["index"] = { -- This can be a string or a number name = "name", -- This is the name of the zone recognized by PolyZone, this has to be unique so it doesn't mess up with other zones coords = vector3(x, y, z), -- These are the coords for the zone, this has to be a vector3 and the coords have to be a float value, fill in x, y and z with the coords length = 1.5, -- The length of the boxzone calculated from the center of the zone, this has to be a float value width = 1.6, -- The width of the boxzone calculated from the center of the zone, this has to be a float value heading = 12.0, -- The heading of the boxzone, this has to be a float value debugPoly = false, -- This is for enabling/disabling the drawing of the box, it accepts only a boolean value (true or false), when true it will draw the polyzone in green minZ = 36.7, -- This is the bottom of the boxzone, this can be different from the Z value in the coords, this has to be a float value maxZ = 38.9, -- This is the top of the boxzone, this can be different from the Z value in the coords, this has to be a float value options = { -- This is your options table, in this table all the options will be specified for the target to accept { -- This is the first table with options, you can make as many options inside the options table as you want num = 1, -- This is the position number of your option in the list of options in the qb-target context menu (OPTIONAL) type = "client", -- This specifies the type of event the target has to trigger on click, this can be "client", "server", "command" or "qbcommand", this is OPTIONAL and will only work if the event is also specified event = "Test:Event", -- This is the event it will trigger on click, this can be a client event, server event, command or qbcore registered command, NOTICE: Normal command can't have arguments passed through, QBCore registered ones can have arguments passed through icon = 'fas fa-example', -- This is the icon that will display next to this trigger option label = 'Test', -- This is the label of this option which you would be able to click on to trigger everything, this has to be a string targeticon = 'fas fa-example', -- This is the icon of the target itself, the icon changes to this when it turns blue on this specific option, this is OPTIONAL item = 'handcuffs', -- This is the item it has to check for, this option will only show up if the player has this item, this is OPTIONAL action = function(entity) -- This is the action it has to perform, this REPLACES the event and this is OPTIONAL if IsPedAPlayer(entity) then return false end -- This will return false if the entity interacted with is a player and otherwise returns true TriggerEvent('testing:event', 'test') -- Triggers a client event called testing:event and sends the argument 'test' with it end, canInteract = function(entity, distance, data) -- This will check if you can interact with it, this won't show up if it returns false, this is OPTIONAL if IsPedAPlayer(entity) then return false end -- This will return false if the entity interacted with is a player and otherwise returns true return true end, job = 'police', -- This is the job, this option won't show up if the player doesn't have this job, this can also be done with multiple jobs and grades, if you want multiple jobs you always need a grade with it: job = {["police"] = 0, ["ambulance"] = 2}, gang = 'ballas', -- This is the gang, this option won't show up if the player doesn't have this gang, this can also be done with multiple gangs and grades, if you want multiple gangs you always need a grade with it: gang = {["ballas"] = 0, ["thelostmc"] = 2}, citizenid = 'JFD98238', -- This is the citizenid, this option won't show up if the player doesn't have this citizenid, this can also be done with multiple citizenid's, if you want multiple citizenid's there is a specific format to follow: citizenid = {["JFD98238"] = true, ["HJS29340"] = true}, drawDistance = 10.0, -- This is the distance for the sprite to draw if Config.DrawSprite is enabled, this is in GTA Units (OPTIONAL) drawColor = {255, 255, 255, 255}, -- This is the color of the sprite if Config.DrawSprite is enabled, this will change the color for this PolyZone only, if this is not present, it will fallback to Config.DrawColor, for more information, check the comment above Config.DrawColor (OPTIONAL) successDrawColor = {30, 144, 255, 255} -- This is the color of the sprite if Config.DrawSprite is enabled, this will change the color for this PolyZone only, if this is not present, it will fallback to Config.DrawColor, for more information, check the comment above Config.DrawColor (OPTIONAL) } } } ``` ---------------------------------------- TITLE: Using qb-keyminigame with Callback (Lua) DESCRIPTION: This snippet shows how to integrate the qb-keyminigame resource into a FiveM script using Lua. It defines a callback function `minigameResults` to process the outcome of the minigame (the number of faults) and registers a command `keyminigame` that triggers the game's UI display and starts the game, passing the callback function to receive the results. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-keyminigame.md#_snippet_0 LANGUAGE: Lua CODE: ``` local function minigameResults(faults) -- callback function with fault amount if faults == 0 then print('Player finished game with 0 faults!') elseif faults == 1 then print('Player finished game with 1 faults!') elseif faults == 2 then print('Player finished game with 2 faults!') end end RegisterCommand('keyminigame', function() TriggerEvent('qb-keyminigame:show') -- displays game UI on screen TriggerEvent('qb-keyminigame:start', minigameResults) -- starts game end) ``` ---------------------------------------- TITLE: Configuration for qb-crypto (Lua) DESCRIPTION: This configuration block defines the parameters for the qb-crypto resource, including crypto value ranges, history storage, starting worth, exchange point coordinates, auto-update timers, crash/luck chances, and settings for integrating a real-life crypto ticker via API. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/qbcore-resources/qb-crypto.md#_snippet_0 LANGUAGE: Lua CODE: ``` Crypto = { Lower = 500, -- Lowest possible crypto worth Upper = 5000, -- Highest possible crypto worth History = { ["qbit"] = {}}, -- Stores crypto worth history for viewing Worth = {["qbit"] = 1000}, -- Starting crypto worth (can add more) Labels = {["qbit"] = "Qbit"}, -- Crypto type label (can add more) Exchange = { -- Exchange point for cryptosticks coords = vector3(1276.21, -1709.88, 54.57), RebootInfo = { state = false, percentage = 0 }, }, -- For auto updating the value of qbit Coin = 'qbit', RefreshTimer = 10, -- In minutes, so every 10 minutes. -- Crashes or luck ChanceOfCrashOrLuck = 2, -- This is in % (1-100) Crash = {20,80}, -- Min / Max Luck = {20,45}, -- Min / Max -- If not not Chance of crash or luck ChanceOfDown = 30, -- If out of 100 hits less or equal to ChanceOfUp = 60, -- If out of 100 is greater or equal to CasualDown = {1,10}, -- Min / Max (If it goes down) CasualUp = {1,10}, -- Min / Max (If it goes up) } Ticker = { Enabled = false, -- Enable/disable real life crypto prices coin = 'BTC', --- The coin, please make sure you find the actual name, for example: Bitcoin vs BTC, BTC would be correct currency = 'USD', -- For example USD, NOK, SEK, EUR, CAD and more here https://www.countries-ofthe-world.com/world-currencies.html tick_time = 2, --- Minutes (Minimum is 2 minutes) 20,160 Requests a month, Its recommended to get the free API key so the crypto script doesnt switch on and off if ratelimit is encountered Api_key = 'put_api_key_here', -- If you decide to get an api key for the API (https://min-api.cryptocompare.com/pricing) The free plan should be more than enough for 1 Fivem server --- Error handle stuff, for more user friendly and readable errors, Don't touch. Error_handle = { ['fsym is a required param.'] = 'Config error: Invalid / Missing coin name', ['tsyms is a required param.'] = 'Config error: Invalid / Missing currency', ['cccagg_or_exchange'] = 'Config error: Invalid currency / coin combination', -- For some reason api throws this error if either coin or currency is invalid }, } ``` ---------------------------------------- TITLE: Organizing QBCore Lua Script Structure DESCRIPTION: Illustrates a standard organizational pattern for qbcore Lua scripts. It includes sections for variable declarations (like getting the QBCore object), custom function definitions, event registration using RegisterNetEvent, and the main script execution flow within a CreateThread. SOURCE: https://github.com/qbcore-framework/qb-docs/blob/main/guides/script-optimization.md#_snippet_14 LANGUAGE: Lua CODE: ``` -- Variables local QBCore = exports['qb-core']:GetCoreObject() -- Functions local function calculateDistance(pos1, pos2) return #(pos1 - pos2) end -- Events RegisterNetEvent('exampleEvent', function() print('Event triggered!') end) -- Main Logic CreateThread(function() print('Script started!') end) ```