AI Core
Referencia de la API

Exports de scripts

Los exports de cada script ai-*, y las API de otros scripts que sustituyen.

Los scripts ai-* nunca se llaman entre sí para una tarea compartida: objetos, llaves, alertas, prisión, médico, aspectos, elementos del radial y clima pasan por ai-core (la lib), que llama a los exports de abajo. Llámalos tú mismo solo para lo que es propio de ese script. Los exports tipados en @aicore-fivem/shared funcionan con resourceExport("ai-..."); los demás con callExport(resource, name, ...args) o una llamada normal a exports[...].

Cuando un script sustituye a otro (provide), también responden los nombres de export del otro script, así que exports.ox_inventory:AddItem(...) llega a ai-inventory.

ai-lib

La interfaz compartida del jugador. Exports de cliente, tipados AiLibClientExports; notify, progress, showPrompt, menu, input, skillCheck y lockpick de la lib los llaman por ti.

ExportQué
Notify(notification: Notification): voidUna tarjeta de notificación (text, title?, kind, duration?).
ShowProgress(label: string, duration: number): voidMuestra la barra de progreso durante duration ms (quien llama ejecuta la acción).
HideProgress(): voidLa oculta.
ShowPrompt(id: string, text: string, at?: { x, y, z }): voidMuestra o actualiza el prompt de quien llama; at lo dibuja sobre un punto del mundo.
HidePrompt(id: string): voidOculta un prompt.
OpenMenu(requestId: number, request: MenuRequest): voidUn menú; la elección llega como MENU_EVENTS.menuResult.
OpenInput(requestId: number, request: InputRequest): voidUn diálogo de entrada; los valores llegan como MENU_EVENTS.inputResult.
OpenMinigame(requestId: number, request: MinigameRequest): voidUna prueba de habilidad o una cerradura; el resultado llega como MENU_EVENTS.menuResult.
CloseDialog(): voidCierra el menú o la entrada abiertos de quien llama (responde con null).

El evento de servidor ai-lib:client:notify (LIB_UI.notifyEvent) con una Notification muestra una tarjeta en la pantalla de ese jugador.

ai-inventory

Exports de servidor (propios): los demás scripts ai-* llegan a ellos a través de la capa de inventario de ai-core.

ExportQué
AddItem(inv: number | string, item: string, count: number, metadata?, slot?): booleanAñade objetos.
RemoveItem(inv: number | string, item: string, count: number, metadata?, slot?): booleanQuita objetos.
GetItemCount(inv: number | string, item: string, metadata?): numberCuántos hay.
GetItems(inv: number | string): { name, label, count, slot, metadata }[]Cada pila con su etiqueta.
CanCarryItem(inv: number | string, item: string, count: number, metadata?): booleanSi cabe.
RegisterUsableItem(name: string, handler: (source, item) => unknown): voidSi handler devuelve false se conserva el objeto; si no, se toma su cantidad consume.
RegisterStash(name: string, label: string, slots: number, maxWeight: number, jobs?: string[], personal?: boolean): voidUn stash.
OpenInventory(source: number, inv: number | string): booleanAbre un inventario en la pantalla de un jugador.
ClearInventory(inv: number | string): voidLo vacía.
Items(name?: string): unknownUna definición de objeto (forma de ox), o todas.
GetWeight(inv: number | string): { weight, maxWeight } | nullPeso cargado y límite en gramos.

Exports de cliente: OpenInventory(type, data), CloseInventory(), OpenSelf() (el inventario propio con el suelo, el maletero o la guantera alrededor), GetItemCount(item), HasItem(items: string \| string[] \| Record<string, number>, amount?), GetPlayerItems().

Evento local del servidor ai-inventory:usedItem (source, name, slot, metadata, status).

API de ox_inventory

ai-inventory hace provide de ox_inventory y responde a sus exports (ox_inventory 2.44). Los inventarios se nombran como en ox: el source de un jugador, un nombre de stash, { id, owner } para stashes personales, una matrícula para maleteros.

  • Servidor: AddItem (devuelve success, response, llama a cb), RemoveItem, GetItem, GetItemCount, Search (count / slots), CanCarryItem, CanCarryWeight, CanCarryAmount, GetInventory, GetInventoryItems, GetSlot, GetSlotWithItem, GetSlotsWithItem, GetSlotIdWithItem, GetSlotIdsWithItem, GetEmptySlot, SetMetadata, SetDurability, SetMaxWeight, RegisterStash, ClearInventory, Items, ItemList, forceOpenInventory (stash, jugador, tienda), CreateTemporaryStash, CustomDrop, RemoveInventory, SwapSlots.
  • Cliente: openInventory, closeInventory, Search, GetItemCount, GetPlayerItems, GetPlayerWeight, GetPlayerMaxWeight, Items, useSlot, getCurrentWeapon / GetCurrentWeapon; displayMetadata, weaponWheel, setStashTarget se aceptan y no hacen nada.
  • Sin respuesta: hooks (registerHook, removeHooks), UpdateVehicle, ConfiscateInventory / ReturnInventory, GetContainerFromSlot, RegisterShop (las tiendas vienen del panel).

API de qb-inventory

ai-inventory hace provide de qb-inventory (API 2.0). Los objetos devueltos llevan ambas formas: count / metadata y amount / info.

  • Servidor: AddItem(identifier, item, amount, slot, info), RemoveItem, HasItem (nombre, lista o { name = amount }), GetItemCount, GetItemByName, GetItemsByName, GetItemBySlot, CanAddItem, GetFreeWeight, GetSlots, ClearInventory, SetItemData, CreateInventory, OpenInventory, OpenInventoryById, RemoveInventory, CloseInventory.
  • Cliente: HasItem, CloseInventory.
  • Sin respuesta: hooks y listeners, CreateShop / OpenShop, SetInventory, GetInventory, SaveInventory, LoadInventory, UseItem, GetFirstSlotByItem, GetSlotsByItem, GetTotalWeight.

ai-vehicles

Vehículos con dueño. Exports de servidor, tipados AiVehiclesServerExports. VehicleOwner es { type: "character" \| "job" \| "gang" \| "resource", id }.

ExportQué
CreateVehicle(owner: VehicleOwner, model: string, garage: string | null, props?): { id, plate } | nullRegistra un nuevo vehículo con dueño.
GetVehicle(ref: number | string): OwnedVehicle | nullUn vehículo por id o matrícula.
GetVehicles(owner: VehicleOwner): OwnedVehicle[]Vehículos de un personaje conectado, o la flota de un trabajo o banda.
IsOwnedPlate(plate: string): booleanSi una matrícula pertenece a un vehículo con dueño.
GetVehicleIdByEntity(entity: number): number | nullEl id de un vehículo con dueño aparecido.
GetPlateOwners(): [plate, type, id][]Cada vehículo con dueño en memoria (después sigue ai-vehicles:owners).
GetEntity(id: number): number | nullLa entidad aparecida de un vehículo.
SaveVehicle(id: number, change: { props?, fuel?, engine?, body?, state?, garage? }): voidGuarda estado y aspecto; el tuning guardado se mantiene.
SaveTuning(id: number, props: unknown): voidGuarda las props completas con el tuning (solo talleres de tuning).
StoreVehicle(id: number, garage: string | null, state?: VehicleState): voidMete un vehículo en un garaje (garage, out, impound).
SetOwner(id: number, owner: VehicleOwner): voidCambia el dueño.
DeleteVehicle(id: number): voidBorra un vehículo.
SpawnVehicle(id: number, at: { x, y, z, heading }, asker: number, cb: (netId: number | null) => void, purpose?: KeyPurpose, setup?): voidCrea la entidad; cb recibe su net id.

ai-vehicles hace provide de qbx_vehicles: GetPlayerVehicles(filters), GetPlayerVehicle(id), CreatePlayerVehicle(request), SetPlayerVehicleOwner(id, citizenid), DeletePlayerVehicles(idType, idValue), GetVehicleIdByPlate(plate), DoesPlayerVehiclePlateExist(plate), SaveVehicle(entity, options) (los filtros por citizenid necesitan al dueño conectado).

ai-vehicleshop

ExportQué
GetCatalogPrice(model: string): number | nullEl precio de catálogo de un modelo (servidor).

ai-vehiclekeys

Exports de servidor, también bajo qbx_vehiclekeys. Un vehículo es una entidad o una matrícula. Los scripts dan llaves a través de ai-core (GiveVehicleKeys, vehicleKeys de la lib), que los llama mientras ai-vehiclekeys es el sistema de llaves activo.

ExportQué
HasKeys(source: number, vehicle: number | string): booleanSi el jugador tiene las llaves.
GiveKeys(source: number, vehicle: number | string): voidDa llaves.
RemoveKeys(source: number, vehicle: number | string): voidQuita llaves.
SetLockState(vehicle, state)Cierra ("lock", true, 2) o abre una entidad de vehículo.
IsPlayerNearVehicle(source, vehicle)Si el jugador está cerca del vehículo.

ai-death

Exports de servidor, tipados AiDeathServerExports; Revive e IsDead también bajo qbx_medical. Los scripts usan en su lugar la capa médica de ai-core (medical de la lib).

ExportQué
Revive(source: number): booleanLevanta a un jugador abatido; false si no está abatido.
IsDead(source: number): booleanSi el jugador está abatido.
Heal(source: number): voidSalud completa para un jugador que no está abatido.

El evento de cliente hospital:client:Revive enviado desde el servidor reanima al jugador.

ai-prison

Exports de servidor; los llama la capa de prisión de ai-core (prison de la lib).

ExportQué
JailPlayer(source, minutes, by?)Encarcela a un jugador; true si funcionó.
ReleasePlayer(source)Libera a un jugador encarcelado.
GetJailTime(source)Minutos restantes (0 si está libre).

ai-policealert

ExportQué
DispatchAlert(alert: DispatchAlert): voidMuestra una tarjeta de alerta; solo la llama la capa de despacho de ai-core (los scripts usan SendDispatchAlert / dispatch de la lib).

ai-doorlock

Exports de servidor, tipados AiDoorlockServerExports; puertas por su id del panel. También responde a setDoorState y getDoor de ox_doorlock.

ExportQué
SetDoorState(id: string, locked: boolean): voidCierra o abre una puerta.
IsLocked(id: string): booleanSi una puerta está cerrada.

ai-banking

Dinero de sociedad para scripts de QB (una cuenta es el nombre de un trabajo). Exports de servidor, también bajo qb-banking; getAccountMoney, addAccountMoney, removeAccountMoney de Renewed-Banking responden igual.

ExportQué
GetAccountBalance(job)El saldo bancario de la cuenta de un trabajo.
AddMoney(job, amount, reason)Añade a ella.
RemoveMoney(job, amount, reason)Quita de ella.

ai-hud

ExportLadoQué
OpenSettings()ClienteAbre los ajustes del HUD.
SetMinimapAlways(on: boolean)ClienteUn interruptor propio de un admin: el minimapa a pie diga lo que diga el panel.
GetMinimapAlways(): booleanClienteSi está activo.
GetNeeds(source)Servidorhunger, thirst, stress del jugador, o null.
SetNeed(source, need, value)ServidorFija una necesidad.
AddNeed(source, need, delta)ServidorCambia una necesidad en delta.

ai-smallresources

Exports de cliente.

ExportQué
GetSeatbelt(): boolean | nullSi el jugador lleva cinturón; null a pie o con los cinturones desactivados. Los cambios llegan como ai-smallresources:seatbelt.
IsHandsUp(): booleanManos arriba (los scripts usan gestures de la lib).
IsPointing(): booleanSeñalando.

ai-sirens

Exports de cliente para vehículos de emergencia; vehicle es por defecto aquel en el que está sentado el jugador. Los cambios de estado funcionan en el cliente del conductor.

ExportQué
SetLights(vehicle, on)Luces encendidas o apagadas.
ToggleLights(vehicle)Alterna las luces.
SetSirenTone(vehicle, tone)Tono 0-3 (0 = apagada).
ToggleSiren(vehicle)Sirena encendida o apagada.
CycleTone(vehicle)El siguiente tono.
GetSirenTone(vehicle)El tono actual.
AreLightsOn(vehicle)Si las luces están encendidas.
GetAirManuState(vehicle)El estado del tono manual.
GetLightbarModel(vehicle)El modelo de la barra de luces, o null.

ai-exitsleeping

ExportLadoQué
AddCreateCheck(id, fn(source, charId, coords) => boolean)ServidorDevuelve false para no dejar cuerpo dormido (un apartamento, una zona de evento); se quita cuando se detiene el recurso que lo añadió.
PlayerLoaded()ClienteDespierta al personaje cuando el modo de despertar es "export".
SetHidden(reason, hidden)ClienteOculta todos los cuerpos dormidos en este cliente mientras se mantenga algún motivo (interiores, shells).
SetCarryBlocked(reason, blocked)ClienteOculta la opción de cargar mientras se mantenga algún motivo.

ai-appearance

Exports de cliente, tipados AiAppearanceClientExports; los scripts usan appearance de la lib.

ExportQué
ApplyAppearance(ped: number, appearance: unknown): booleanPone un aspecto de ai-appearance en un ped de su modelo.
GetPedAppearance(ped: number): unknownEl aspecto del jugador local, null para otros peds.

ai-radialmenu

Exports de cliente propios (tipados AiRadialClientExports): AddItem(item) (onSelect se acepta como onPressed), RemoveItem(id, parent?), Refresh(). Los scripts usan radial de la lib.

Hace provide de las API de otras ruedas:

  • qb-radialmenu: AddOption(data, id?) devuelve el id, RemoveOption(id).
  • tgiann-radialmenu-target: AddMenuItem(item | items, parentId?), RemoveMenuItem(id, parentId?), ClearMenuItems(), RegisterSubMenu({ id, items }), RefreshMenu(), DisableMenu(state), IsMenuDisabled(), OpenMenu(), CloseMenu(), IsMenuOpen(), HasMenuItem(id), SetMenuItemHidden(id, state), IsMenuItemHidden(id), UpdateMenuItem(id, { label?, icon? }), ResetMenuItem(id).

ai-target

Responde a la API de cliente de ox_target bajo ai-target y ox_target: addSphereZone, addBoxZone, addPolyZone, removeZone, zoneExists, addModel, removeModel, addEntity, removeEntity, addLocalEntity, removeLocalEntity, addGlobalPed / Vehicle / Object / Player y sus removeGlobal*, disableTargeting, isActive. addGlobalOption no se ofrece (registra un aviso). Los scripts usan Points de la lib, que elige prompt o target según el ajuste del dueño.

ai-voice

Sustituye a pma-voice 7.x (hace provide de pma-voice, mumble-voip, tokovoip, toko-voip, tokovoip_script).

  • Servidor, nombres de pma-voice: setPlayerRadio, setPlayerCall, getPlayersInRadioChannel / GetPlayersInRadioChannel, addChannelCheck, overrideRadioNameGetter, isValidPlayer.
  • Servidor, propios: getBackend, setPlayerProximityMode(source, index), setPlayerRange(source, metres | null), getPlayerProximity(source), toggleMute(source, seconds?), addProximityCheck(fn(source, index, distance)) (false rechaza), addPlayerRadioListen / removePlayerRadioListen / setPlayerRadioActive(source, channel), getPlayerRadioChannels(source) ({ active, channels }), addCallCheck(fn(source, callId)) (true permite), setPlayerCallSpeaker(source, on) / getPlayerCallSpeaker(source), setPlayerSubmix(source, name | null).
  • Cliente: los exports de cliente de pma-voice (setRadioChannel, setCallChannel, setRadioVolume, setCallVolume, setVoiceProperty, overrideProximityRange, toggleMutePlayer, toggleRadioAnim...) más addRadioDisableBit / removeRadioDisableBit, registerCustomSubmix, setEffectSubmix; propios addRadioChannel / removeRadioChannel / setActiveRadioChannel / getRadioChannels, setCallSpeaker / getCallSpeaker, setRadioAnimDisabled, createSubmix(name, spec) / getSubmix / editSubmix / listSubmixes, cycleProximity, getBackend, isRadioTalking.
  • Eventos locales: cliente pma-voice:setTalkingMode, pma-voice:radioActive, pma-voice:toggleRadioAnim; servidor pma-voice:playerMuted.

ai-weathersync

Exports bajo ai-weathersync y qb-weathersync (todo su contrato): setWeather, setTime, setBlackout, setTimeFreeze, setDynamicWeather, nextWeatherStage, getWeatherState, getTime, getBlackoutState, getTimeFreezeState, getDynamicWeather. Los scripts usan GetWeather / SetWeather... de ai-core (world de la lib), que funcionan con cualquier script de clima.

ai-chat

Sustituye al recurso chat de FiveM.

  • Cliente: exports addMessage(message), addSuggestion(name, help, params); eventos chat:addMessage, chatMessage (author, color, text), chat:addSuggestion(s), chat:removeSuggestion, chat:addMode / chat:removeMode, chat:clear.
  • Servidor: exports addMessage(target, message), registerMessageHook(fn), registerMode(data); evento chatMessage (source, author, text) antes de la entrega (cancélalo para descartar el mensaje).

ai-mysql

Sustituye a oxmysql: exports bajo ai-mysql y oxmysql: query, single, scalar, insert, update, prepare, rawExecute, transaction, startTransaction, store, isReady, awaitConnection, execute, fetch, cada uno también como <name>_async / <name>Sync. También los nombres de ghmattimysql (execute, scalar, transaction, store) y mysql-async (mysql_execute, mysql_insert, mysql_fetch_all, mysql_fetch_scalar, mysql_transaction, mysql_store); eventos oxmysql:error, oxmysql:transaction-error. Ver Base de datos.

En esta página