Pisanie skryptów FiveM tradycyjnie wymagało głębokiej wiedzy o Lua, JavaScript i FiveM API. Dziś narzędzia AI, takie jak Claude Code, GitHub Copilot i ChatGPT, zmieniają sposób, w jaki deweloperzy tworzą wszystko, od Skrypty ESX do złożonych systemy standalone. Ten kompleksowy przewodnik pokazuje dokładnie, jak wykorzystać AI do rozwoju FiveM, z konkretnymi przykładami i sprawdzonymi przepływami pracy.
Why AI-Assisted FiveM Development Changes Everything
Tradycyjne tworzenie skryptów FiveM wymaga opanowania wielu technologii jednocześnie: Lua dla logiki serwerowej, JavaScript dla interfejsów NUI, SQL dla operacji na bazie danych oraz rozległego Biblioteka natywnych funkcji FiveM. AI tools can speed up routine drafting and debugging, but they do not replace learning the FiveM runtime, framework APIs or security boundaries.
Rzeczywisty wpływ dla właścicieli serwerów:
- Draft routine boilerplate faster when requirements and dependencies are explicit
- Generuj kod szablonowy natychmiast dla typowych wzorców
- Debuguj złożone problemy synchronizacji między klientem a serwerem
- Przekształcaj pomysły bezpośrednio w działające prototypy
Niezbędne narzędzia AI do tworzenia FiveM
Claude Code (Anthropic)
Claude Code can review context across multiple files. Installation methods change, so follow the current official Claude Code documentation linked above instead of copying an unverified third-party package command.
Zalety specyficzne dla FiveM:
- Generuje kompletne konfiguracje fxmanifest.lua
- Rozumie frameworki ESX, QBCore i VRP
- Automatycznie tworzy pasujące procedury obsługi zdarzeń klient/serwer
GitHub Copilot
Integruje się bezpośrednio z VS Code, zapewniając sugestie w czasie rzeczywistym podczas pisania. Szczególnie skuteczny dla:
- Uzupełnianie wywołań funkcji natywnych
- Generowanie wzorców obsługi zdarzeń
- Autouzupełnianie zapytań do bazy danych
ChatGPT z niestandardowymi instrukcjami
Skonfiguruj ChatGPT specjalnie dla FiveM, ustawiając niestandardowe instrukcje:
You are a FiveM script developer. Always use: - Lua 5.4 syntax for server scripts - Modern JavaScript for client scripts - FiveM natives from the latest game build - Proper event security with server-side validation
Krok po kroku: Tworzenie pierwszego skryptu wygenerowanego przez AI
Zbudujmy kompletny skrypt sklepu z pojazdami, używając Claude Code, demonstrując cały przepływ pracy od koncepcji do wdrożenia.
Krok 1: Zdefiniuj jasne wymagania
Utwórz requirements.md plik:
## Vehicle Shop Script Requirements - Framework: ESX Legacy 1.9.0+ - Database: MySQL with oxmysql - Features: - Browse vehicles by category - Test drive system with time limit - Finance options with weekly payments - Admin commands for adding vehicles - UI: Modern NUI with React
Step 2: Generate the Resource Structure
Komenda dla Claude Code:
claude-code generate "Create a complete FiveM vehicle shop resource based on requirements.md"
To generuje:
vehicle_shop/ ├── fxmanifest.lua ├── config.lua ├── server/ │ ├── main.lua │ ├── database.lua │ └── commands.lua ├── client/ │ ├── main.lua │ ├── showroom.lua │ └── testdrive.lua ├── ui/ │ ├── index.html │ ├── style.css │ └── script.js └── sql/ └── vehicle_shop.sql
Krok 3: Wygenerowany przez AI fxmanifest.lua
fx_version 'cerulean'
game 'gta5'
author 'YourName'
description 'AI-Generated Vehicle Shop'
version '1.0.0'
shared_scripts {
'@es_extended/imports.lua',
'@ox_lib/init.lua',
'config.lua'
}
client_scripts {
'client/*.lua'
}
server_scripts {
'@oxmysql/lib/MySQL.lua',
'server/*.lua'
}
ui_page 'ui/index.html'
files {
'ui/index.html',
'ui/style.css',
'ui/script.js'
}
dependencies {
'es_extended',
'oxmysql',
'ox_lib'
}
Krok 4: Wdrożenie podstawowej funkcjonalności za pomocą AI
Prompt for Server-Side Vehicle Loading:
-- AI-Generated: server/database.lua
local vehicles = {}
CreateThread(function()
local result = MySQL.query.await('SELECT * FROM vehicle_shop WHERE stock > 0')
for i = 1, #result do
local vehicle = result[i]
vehicles[vehicle.model] = {
model = vehicle.model,
name = vehicle.name,
price = vehicle.price,
category = vehicle.category,
stock = vehicle.stock
}
end
print(('[^2INFO^7] Loaded %d vehicles from database'):format(#result))
end)
-- Secure server event for purchasing
RegisterNetEvent('vehicle_shop:server:purchaseVehicle', function(vehicleModel, paymentMethod)
local src = source
local xPlayer = ESX.GetPlayerFromId(src)
-- Security check
if not vehicles[vehicleModel] then
return TriggerClientEvent('ox_lib:notify', src, {
title = 'Error',
description = 'Invalid vehicle model',
type = 'error'
})
end
local vehicleData = vehicles[vehicleModel]
-- Payment processing
if paymentMethod == 'cash' then
if xPlayer.getMoney() >= vehicleData.price then
xPlayer.removeMoney(vehicleData.price)
-- Generate plate and spawn vehicle
local plate = GeneratePlate()
MySQL.insert('INSERT INTO owned_vehicles (owner, plate, vehicle) VALUES (?, ?, ?)', {
xPlayer.identifier,
plate,
json.encode({model = vehicleModel, plate = plate})
})
TriggerClientEvent('vehicle_shop:client:spawnVehicle', src, vehicleModel, plate)
else
TriggerClientEvent('ox_lib:notify', src, {
title = 'Insufficient Funds',
description = ('You need $%d'):format(vehicleData.price),
type = 'error'
})
end
end
end)
Krok 5: Implementacja po stronie klienta
Podpowiedź AI: “Utwórz showroom po stronie klienta z kontrolą kamery i podglądem pojazdu”
-- AI-Generated: client/showroom.lua
local currentVehicle = nil
local cam = nil
local inShowroom = false
local showroomCoords = vector3(-42.34, -1097.35, 26.42)
local vehicleSpawnCoords = vector4(-47.52, -1097.29, 26.42, 340.0)
function OpenShowroom(category)
inShowroom = true
DoScreenFadeOut(500)
Wait(500)
-- Setup camera
cam = CreateCam('DEFAULT_SCRIPTED_CAMERA', true)
SetCamCoord(cam, -54.31, -1097.29, 28.42)
PointCamAtCoord(cam, vehicleSpawnCoords.x, vehicleSpawnCoords.y, vehicleSpawnCoords.z)
SetCamActive(cam, true)
RenderScriptCams(true, false, 0, true, false)
-- Request vehicles from server
ESX.TriggerServerCallback('vehicle_shop:getVehicles', function(vehicles)
SendNUIMessage({
action = 'showVehicles',
vehicles = vehicles,
category = category
})
SetNuiFocus(true, true)
end, category)
DoScreenFadeIn(500)
end
RegisterNUICallback('previewVehicle', function(data, cb)
if currentVehicle then
DeleteEntity(currentVehicle)
end
local model = GetHashKey(data.model)
RequestModel(model)
while not HasModelLoaded(model) do
Wait(10)
end
currentVehicle = CreateVehicle(model, vehicleSpawnCoords.x, vehicleSpawnCoords.y,
vehicleSpawnCoords.z, vehicleSpawnCoords.w, false, false)
SetEntityAsMissionEntity(currentVehicle, true, true)
SetVehicleOnGroundProperly(currentVehicle)
SetVehicleDoorsLocked(currentVehicle, 2)
cb('ok')
end)
Zaawansowane techniki AI dla złożonych systemów
Zarządzanie kontekstem wielu plików
Podczas tworzenia połączonych systemów, takich jak skrypty telefonu, provide AI with complete context:
# Feed multiple files to Claude Code claude-code analyze --files "server/*.lua,client/*.lua,config.lua" --prompt "Add a garage system that integrates with the existing vehicle shop"
Framework-Specific Prompting
Różne frameworki wymagają różnych podejść. Oto jak zoptymalizować prompty AI dla każdego z nich:
Dla ESX:
Generate an ESX job script with: - Grades/ranks system using ESX.Jobs - Salary payments via ESX.GetJobs() - Boss menu with society funds - Use esx_society patterns
Dla QBCore:
Create a QBCore gang system with: - Gang territories using PolyZone - Reputation system with QB.Shared.Gangs - Stash/storage using qb-inventory - Gang management via qb-gangmenu patterns
Dla Skrypty VRP:
Build a VRP business system using: - vRP.getUserId for player identification - vRP permissions system - vRP money methods (giveMoney, tryPayment) - vRPclient tunnel for client callbacks
Generowanie schematu bazy danych
AI doskonale radzi sobie z tworzeniem zoptymalizowanych struktur baz danych:
-- AI Prompt: "Create MySQL schema for advanced vehicle shop with financing" -- Generated Result: CREATE TABLE IF NOT EXISTS `vehicle_shop_catalog` ( `id` int(11) NOT NULL AUTO_INCREMENT, `model` varchar(60) NOT NULL, `name` varchar(60) NOT NULL, `manufacturer` varchar(60) DEFAULT NULL, `category` varchar(60) DEFAULT NULL, `price` int(11) NOT NULL, `stock` int(11) DEFAULT 10, `max_speed` int(11) DEFAULT NULL, `acceleration` float DEFAULT NULL, `braking` float DEFAULT NULL, `handling` float DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `model` (`model`), KEY `idx_category` (`category`), KEY `idx_price` (`price`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; CREATE TABLE IF NOT EXISTS `vehicle_financing` ( `id` int(11) NOT NULL AUTO_INCREMENT, `identifier` varchar(60) NOT NULL, `vehicle_id` int(11) NOT NULL, `down_payment` int(11) NOT NULL, `weekly_payment` int(11) NOT NULL, `weeks_remaining` int(11) NOT NULL, `last_payment` timestamp DEFAULT CURRENT_TIMESTAMP, `repo_warning_sent` boolean DEFAULT FALSE, PRIMARY KEY (`id`), KEY `idx_identifier` (`identifier`), FOREIGN KEY (`vehicle_id`) REFERENCES `owned_vehicles`(`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Debugowanie i optymalizacja z użyciem AI
Wskazówki dotyczące profilowania wydajności
-- Prompt: "Add performance monitoring to this resource"
-- AI generates:
local performanceStats = {
events = {},
queries = {}
}
local function profileEvent(eventName, func)
return function(...)
local startTime = GetGameTimer()
local result = {func(...)}
local executionTime = GetGameTimer() - startTime
performanceStats.events[eventName] = performanceStats.events[eventName] or {}
table.insert(performanceStats.events[eventName], executionTime)
if executionTime > 50 then
print(('[^3WARNING^7] Event %s took %dms'):format(eventName, executionTime))
end
return table.unpack(result)
end
end
-- Wrap existing events
RegisterNetEvent('vehicle_shop:server:purchaseVehicle',
profileEvent('purchaseVehicle', purchaseVehicleHandler))
Walidacja bezpieczeństwa
AI może identyfikować i naprawiać luki w zabezpieczeniach:
-- Prompt: "Add security validation to this client-to-server event"
-- Before (vulnerable):
RegisterNetEvent('giveWeapon', function(weapon)
local src = source
GiveWeaponToPed(GetPlayerPed(src), weapon, 250, false, true)
end)
-- After (AI-secured):
local allowedWeapons = {
['WEAPON_PISTOL'] = true,
['WEAPON_COMBATPISTOL'] = true
}
RegisterNetEvent('giveWeapon', function(weapon)
local src = source
local xPlayer = ESX.GetPlayerFromId(src)
-- Multiple validation layers
if not xPlayer then return end
if not allowedWeapons[weapon] then
return DropPlayer(src, 'Attempted to spawn invalid weapon')
end
if not xPlayer.hasPermission('weapons.spawn') then
return TriggerClientEvent('ox_lib:notify', src, {
title = 'Access Denied',
type = 'error'
})
end
-- Log the action
print(('[^3WEAPON^7] %s spawned %s'):format(xPlayer.getName(), weapon))
xPlayer.addWeapon(weapon, 250)
end)
NUI Rozwój z AI
Tworzenie nowoczesnych interfejsów dla FiveM wymaga znajomości HTML/CSS/JavaScript. AI usprawnia ten proces:
Generowanie komponentów React
// Prompt: "Create a React vehicle shop UI with category filtering"
// AI generates:
import React, { useState, useEffect } from 'react';
import './VehicleShop.css';
const VehicleShop = () => {
const [vehicles, setVehicles] = useState([]);
const [selectedCategory, setSelectedCategory] = useState('all');
const [selectedVehicle, setSelectedVehicle] = useState(null);
const [searchTerm, setSearchTerm] = useState('');
useEffect(() => {
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, []);
const handleMessage = (event) => {
const { action, data } = event.data;
switch(action) {
case 'showVehicles':
setVehicles(data.vehicles);
break;
case 'updateStock':
updateVehicleStock(data.model, data.stock);
break;
}
};
const filteredVehicles = vehicles.filter(vehicle => {
const matchesCategory = selectedCategory === 'all' ||
vehicle.category === selectedCategory;
const matchesSearch = vehicle.name.toLowerCase()
.includes(searchTerm.toLowerCase());
return matchesCategory && matchesSearch;
});
const purchaseVehicle = (vehicle, paymentMethod) => {
fetch(`https://${GetParentResourceName()}/purchaseVehicle`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: vehicle.model,
paymentMethod: paymentMethod
})
});
};
return (
<div className="vehicle-shop-container">
<div className="shop-header">
<h1>Premium Deluxe Motorsport</h1>
<input
type="text"
placeholder="Search vehicles..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="search-input"
/>
</div>
<div className="category-filters">
{['all', 'sports', 'super', 'sedan', 'suv', 'motorcycle'].map(cat => (
<button
key={cat}
className={`category-btn ${selectedCategory === cat ? 'active' : ''}`}
onClick={() => setSelectedCategory(cat)}
>
{cat.toUpperCase()}
</button>
))}
</div>
<div className="vehicles-grid">
{filteredVehicles.map(vehicle => (
<VehicleCard
key={vehicle.model}
vehicle={vehicle}
onSelect={() => setSelectedVehicle(vehicle)}
/>
))}
</div>
{selectedVehicle && (
<VehicleDetails
vehicle={selectedVehicle}
onPurchase={purchaseVehicle}
onClose={() => setSelectedVehicle(null)}
/>
)}
</div>
);
};
Typowe pułapki AI i ich rozwiązania
Problem 1: Outdated Native Functions
Problem: AI sugeruje przestarzałe natywne funkcje FiveM Rozwiązanie: Zawsze określ wersję gry w swoim zapytaniu:
Use only FiveM natives compatible with game build 3095+ Replace deprecated natives like GetPlayerPed(-1) with PlayerPedId()
Problem 2: Wycieki pamięci w pętlach
Problem: AI tworzy nieskończone pętle bez odpowiedniego czyszczenia Rozwiązanie: Request garbage collection patterns:
-- AI-improved version with cleanup
local activeThreads = {}
local function createManagedThread(id, func)
if activeThreads[id] then
-- Kill existing thread
activeThreads[id] = false
end
activeThreads[id] = true
CreateThread(function()
while activeThreads[id] do
func()
Wait(0)
end
end)
end
-- Cleanup on resource stop
AddEventHandler('onResourceStop', function(resourceName)
if GetCurrentResourceName() == resourceName then
for id, _ in pairs(activeThreads) do
activeThreads[id] = false
end
end
end)
Problem 3: Problemy z synchronizacją
Problem: Niezgodności stanu klienta i serwera Rozwiązanie: Użyj AI do generowania zarządzania stanem:
-- Prompt: "Create a synchronized state manager for client-server data"
-- AI generates:
-- Server-side state manager
local StateManager = {}
StateManager.states = {}
function StateManager:set(key, value)
self.states[key] = value
TriggerClientEvent('stateManager:sync', -1, key, value)
end
function StateManager:get(key)
return self.states[key]
end
RegisterNetEvent('stateManager:requestSync', function()
local src = source
TriggerClientEvent('stateManager:fullSync', src, StateManager.states)
end)
-- Client-side state manager
local ClientState = {}
RegisterNetEvent('stateManager:sync', function(key, value)
ClientState[key] = value
end)
RegisterNetEvent('stateManager:fullSync', function(states)
ClientState = states
end)
-- Request initial sync
CreateThread(function()
Wait(1000)
TriggerServerEvent('stateManager:requestSync')
end)
Strategie testowania i wdrażania
Zautomatyzowane testowanie z AI
Generate comprehensive test suites:
-- Prompt: "Create unit tests for the vehicle shop purchase function"
-- AI generates:
local function runTests()
local testResults = {
passed = 0,
failed = 0,
tests = {}
}
-- Test 1: Valid purchase with sufficient funds
local function testValidPurchase()
local mockPlayer = {
identifier = 'test_player_1',
money = 50000,
getMoney = function() return 50000 end,
removeMoney = function(amount)
mockPlayer.money = mockPlayer.money - amount
return true
end
}
local result = attemptPurchase(mockPlayer, 'adder', 45000)
assert(result.success == true, 'Valid purchase should succeed')
assert(mockPlayer.money == 5000, 'Money should be deducted correctly')
return true
end
-- Test 2: Purchase with insufficient funds
local function testInsufficientFunds()
local mockPlayer = {
identifier = 'test_player_2',
money = 1000,
getMoney = function() return 1000 end
}
local result = attemptPurchase(mockPlayer, 'adder', 45000)
assert(result.success == false, 'Purchase should fail with insufficient funds')
assert(result.error == 'insufficient_funds', 'Should return correct error code')
return true
end
-- Run all tests
local tests = {
{name = 'Valid Purchase', func = testValidPurchase},
{name = 'Insufficient Funds', func = testInsufficientFunds}
}
for _, test in ipairs(tests) do
local success, error = pcall(test.func)
if success then
testResults.passed = testResults.passed + 1
print(('[^2✓^7] %s passed'):format(test.name))
else
testResults.failed = testResults.failed + 1
print(('[^1✗^7] %s failed: %s'):format(test.name, error))
end
table.insert(testResults.tests, {
name = test.name,
passed = success,
error = error
})
end
return testResults
end
-- Run tests on resource start in development mode
if Config.Debug then
CreateThread(function()
Wait(1000)
local results = runTests()
print(('Tests completed: %d passed, %d failed'):format(
results.passed, results.failed
))
end)
end
Monitorowanie wydajności
-- Prompt: "Add performance monitoring for production deployment"
-- AI generates:
local Monitor = {
metrics = {
eventCalls = {},
dbQueries = {},
memoryUsage = {}
}
}
function Monitor:trackEvent(eventName)
self.metrics.eventCalls[eventName] = (self.metrics.eventCalls[eventName] or 0) + 1
end
function Monitor:trackQuery(queryType, duration)
table.insert(self.metrics.dbQueries, {
type = queryType,
duration = duration,
timestamp = os.time()
})
end
function Monitor:getReport()
local report = {
uptime = GetGameTimer() / 1000,
totalEvents = 0,
averageQueryTime = 0,
memoryUsage = collectgarbage('count')
}
for _, count in pairs(self.metrics.eventCalls) do
report.totalEvents = report.totalEvents + count
end
if #self.metrics.dbQueries > 0 then
local totalTime = 0
for _, query in ipairs(self.metrics.dbQueries) do
totalTime = totalTime + query.duration
end
report.averageQueryTime = totalTime / #self.metrics.dbQueries
end
return report
end
-- Export metrics endpoint
RegisterCommand('metrics', function(source)
if source == 0 or IsPlayerAceAllowed(source, 'admin.metrics') then
print(json.encode(Monitor:getReport(), {indent = true}))
end
end, true)
Integracja z istniejącymi zasobami
Podczas dodawania skryptów wygenerowanych przez AI do istniejących serwerów z Skrypty ESX Lub skrypty standalone, postępuj zgodnie z tymi wzorcami integracji:
Zależności zasobów
-- config.lua - AI-generated configuration for compatibility
Config = {}
-- Framework detection
Config.Framework = nil
CreateThread(function()
if GetResourceState('es_extended') == 'started' then
Config.Framework = 'esx'
ESX = exports['es_extended']:getSharedObject()
elseif GetResourceState('qb-core') == 'started' then
Config.Framework = 'qbcore'
QBCore = exports['qb-core']:GetCoreObject()
else
Config.Framework = 'standalone'
end
print(('[^2INFO^7] Detected framework: %s'):format(Config.Framework))
end)
-- Framework-agnostic money functions
function GetPlayerMoney(source)
if Config.Framework == 'esx' then
local xPlayer = ESX.GetPlayerFromId(source)
return xPlayer.getMoney()
elseif Config.Framework == 'qbcore' then
local Player = QBCore.Functions.GetPlayer(source)
return Player.PlayerData.money.cash
else
-- Standalone implementation
return exports['your_economy']:GetMoney(source)
end
end
Lista kontrolna najlepszych praktyk
Przed wdrożeniem skryptów wygenerowanych przez AI:
- [ ] Walidacja bezpieczeństwa: Wszystkie zdarzenia klient-serwer są walidowane
- [ ] Performance Testing: Żadnych pętli bez Wait()
- [ ] Zarządzanie pamięcią: Prawidłowe czyszczenie po zatrzymaniu zasobu
- [ ] Indeksy baz danych: Indeksy na często używanych kolumnach
- [ ] Błąd Obsługiwanie: Bloki try-catch wokół krytycznych operacji
- [ ] Logowanie: Structured logging for debugging
- [ ] Konfiguracja: Eksternalizowane wartości konfiguracji
- [ ] Dokumentacja: README z krokami instalacji
- [ ] Kontrola wersji: Wersjonowanie semantyczne w fxmanifest
- [ ] Licencja: Dołączony odpowiedni plik licencji
Zoptymalizowane zapytanie dla agenta deweloperskiego FiveM
You are an expert FiveM developer with 5+ years of production experience managing high-population servers. Your expertise spans all major frameworks and you prioritize secure, performant code.
Podsumowanie
Narzędzia AI, takie jak Claude Code, przekształcają rozwój FiveM z wielomiesięcznego procesu nauki w produktywne skryptowanie w ciągu kilku godzin, umożliwiając szybkie prototypowanie i rozwój złożonych systemów przy jednoczesnym zachowaniu standardów bezpieczeństwa i wydajności.
Gotowy na ulepszenie serwera? Przeglądaj naszą starannie wyselekcjonowaną kolekcję skrypty premium lub przejrzyj rozwiązania samodzielne które uzupełniają twoje zasoby wygenerowane przez AI.
AI dla następnych kroków FiveM
- Jak używać AI z FiveM
- Pisz skrypty FiveM przy użyciu AI
- Podpowiedzi ChatGPT dla FiveM
- Tłumacz skrypty FiveM za pomocą AI
- Narzędzia deweloperskie FiveM
- Skrypty FiveM, Skrypty ESX, Skrypty QBCore, oraz skrypty QBOX
Give AI the right context without exposing secrets
State whether the resource uses ESX, QBCore, QBOX, ox_lib, oxmysql, NUI or standalone code, and ask the tool to list every dependency it assumes. Do not paste licence keys, database passwords, webhook URLs, customer data or private server code into a service unless its data-handling terms and your permission to share that code are clear.
Review generated event handlers, callbacks, player-supplied values, permission checks, reward logic and database writes manually. Test changes on staging with normal-player permissions as well as admin permissions, inspect client and server logs, and keep a rollback copy before production deployment.
Editorial review and source policy
AI can draft code but cannot establish that an event is authorized or a dependency API exists. Require primary-source links, review every network event server-side, run lint/tests, and inspect the diff before staging. Never paste secrets or private player data into a model.
