Objetos
inventory: dar, quitar y contar objetos, almacenes, tiendas y objetos usables a través del inventario que use el servidor.
import { inventory } from "@aicore-fivem/lib/server";inventory envía cada llamada de objetos a través de la capa de inventario de ai-core: responde el inventario que usa el servidor (ai-inventory, u otro que el dueño elija en el panel de ai-core). Tu script nunca llama a los exports propios de un inventario, así que sigue funcionando cuando el dueño cambia de inventario.
El argumento de inventario (inv, tipo InventoryRef) es el id de servidor de un jugador (un número) o el id de otro inventario (un string: el nombre de un almacén, una matrícula).
Las cantidades son números enteros de 1 o más; una fracción se redondea hacia abajo, y 0 o una cantidad negativa hace que la llamada falle.
Mientras no haya inventario en marcha, las llamadas fallan en silencio: false, 0, una lista vacía o null. Los equivalentes en Lua en aiLib.inventory tienen los mismos nombres y el mismo orden de argumentos.
inventory.addItem
Da objetos a un inventario.
Lado: Servidor · Espera: no
inventory.addItem(inv: InventoryRef, item: string, count?: number, metadata?: ItemMetadata, slot?: number): booleanlocal ok = aiLib.inventory.addItem(inv, item, count, metadata, slot)Parámetros
Prop
Type
Devuelve
boolean: true cuando se dieron. false cuando no caben, el objeto no existe, un argumento es incorrecto o no hay inventario en marcha.
Ejemplo
import { inventory } from "@aicore-fivem/lib/server";
import { fail } from "@aicore-fivem/lib/shared";
if (!inventory.addItem(source, "phone", 1, { number: "555-0101" })) return fail("INVENTORY_FULL");Comprueba primero canCarryItem cuando quitas algo a cambio (dinero, otro objeto): quítalo solo después de que addItem respondiera true, o devuélvelo.
inventory.removeItem
Quita objetos de un inventario.
Lado: Servidor · Espera: no
inventory.removeItem(inv: InventoryRef, item: string, count?: number, metadata?: ItemMetadata, slot?: number): booleanlocal ok = aiLib.inventory.removeItem(inv, item, count, metadata, slot)Parámetros
Prop
Type
Devuelve
boolean: true cuando se quitaron. false cuando no hay suficientes, un argumento es incorrecto o no hay inventario en marcha.
Ejemplo
if (!inventory.removeItem(source, "lockpick")) return fail("NO_LOCKPICK");inventory.getItemCount
Cuántas unidades de un objeto tiene un inventario.
Lado: Servidor · Espera: no
inventory.getItemCount(inv: InventoryRef, item: string, metadata?: ItemMetadata): numberlocal count = aiLib.inventory.getItemCount(inv, item, metadata)Prop
Type
Devuelve
number: el total de todas las pilas, 0 cuando no hay ninguna o no hay inventario en marcha.
Ejemplo
const bags = inventory.getItemCount(source, "weed_bag");
notify(source, `You have ${bags} bags`);inventory.hasItem
Si un inventario tiene al menos count unidades de un objeto.
Lado: Servidor · Espera: no
inventory.hasItem(inv: InventoryRef, item: string, count?: number): booleanlocal has = aiLib.inventory.hasItem(inv, item, count)Prop
Type
Devuelve
boolean.
Ejemplo
if (!inventory.hasItem(source, "scrap_metal", 10)) return fail("NEED_10_SCRAP");hasItem es una comprobación, no una reserva: entre hasItem y removeItem (con un await en medio) el objeto puede irse. Actúa según la respuesta de removeItem.
inventory.canCarryItem
Si los objetos cabrían (peso y espacio libre).
Lado: Servidor · Espera: no
inventory.canCarryItem(inv: InventoryRef, item: string, count?: number, metadata?: ItemMetadata): booleanlocal fits = aiLib.inventory.canCarryItem(inv, item, count, metadata)Prop
Type
Devuelve
boolean: true cuando caben.
Ejemplo
if (!inventory.canCarryItem(source, "fish", 5)) return fail("TOO_HEAVY");
inventory.addItem(source, "fish", 5);inventory.getItems
Todas las pilas de un inventario.
Lado: Servidor · Espera: no
inventory.getItems(inv: InventoryRef): InventoryStack[]local stacks = aiLib.inventory.getItems(inv)Devuelve
InventoryStack[]: un { name, label, count, slot, metadata } por pila. Vacío cuando el inventario está vacío, es desconocido o no hay inventario en marcha.
Ejemplo
const weapons = inventory.getItems(source).filter((stack) => stack.name.startsWith("weapon_"));inventory.clearInventory
Vacía un inventario.
Lado: Servidor · Espera: no
inventory.clearInventory(inv: InventoryRef): voidaiLib.inventory.clearInventory(inv)Devuelve
void.
Ejemplo
inventory.clearInventory("evidence_locker_12");inventory.registerStash
Registra un almacén (una caja de almacenamiento, una taquilla). ai-core lo recuerda y lo registra de nuevo en cualquier inventario que arranque más tarde, así que llámalo una vez cuando tu script arranque.
Lado: Servidor · Espera: no
inventory.registerStash(name: string, label: string, slots: number, maxWeight: number, jobs?: string[]): voidaiLib.inventory.registerStash(name, label, slots, maxWeight, jobs)Parámetros
Prop
Type
Devuelve
void.
Ejemplo
inventory.registerStash("police_armory", "Armory", 50, 200_000, ["police"]);inventory.openInventory
Abre un almacén o el inventario de otro jugador en la pantalla de un jugador.
Lado: Servidor · Espera: no
inventory.openInventory(source: number, inv: InventoryRef): booleanlocal ok = aiLib.inventory.openInventory(source, inv)Prop
Type
Devuelve
boolean: true cuando el inventario lo abrió.
Ejemplo
import { onClientCallback, near, online, inventory } from "@aicore-fivem/lib/server";
import { fail } from "@aicore-fivem/lib/shared";
const ARMORY = { x: 452.3, y: -980.0, z: 30.7 };
onClientCallback(
"my-police:armory",
(source) => {
if (!online.onDutyIn(source, ["police"])) return fail("NOT_ON_DUTY");
return { ok: inventory.openInventory(source, "police_armory") };
},
{ guards: [near(ARMORY, 3)] },
);Aquí no se comprueba ni la distancia ni el acceso: comprueba la distancia, el trabajo y la propiedad antes de llamarlo.
inventory.registerUsableItem
Ejecuta tu handler cuando un jugador usa un objeto. ai-core guarda el handler para los inventarios que arranquen más tarde y a través de los reinicios del inventario, así que regístralo una vez cuando tu script arranque.
Lado: Servidor · Espera: no
inventory.registerUsableItem(name: string, handler: UsableItemHandler): voidaiLib.inventory.registerUsableItem(name, handler) -- handler(source, item)Parámetros
Prop
Type
La pila usada es un UsedItem.
Los inventarios que quitan ellos mismos un objeto usado (ai-inventory) lo quitan en cuanto el handler devuelve cualquier cosa que no sea false. Cuando tu handler espera (una barra de progreso) y quita el objeto por sí mismo, devuelve false enseguida, o el objeto se quita dos veces.
Devuelve
void.
Ejemplo
import { inventory, progressFor, medical, createLocale } from "@aicore-fivem/lib/server";
const Locale = createLocale();
async function bandage(source: number) {
const done = await progressFor(source, { label: Locale("BANDAGING"), duration: 4000, canCancel: true });
if (done && inventory.removeItem(source, "bandage")) medical.heal(source);
}
inventory.registerUsableItem("bandage", (source) => {
void bandage(source);
return false; // conservar el objeto ahora: bandage() lo quita después de la barra
});inventory.getItemDefinition
La etiqueta, el peso y los indicadores de un objeto.
Lado: Servidor · Espera: no
inventory.getItemDefinition(name: string): ItemDefinition | nulllocal def = aiLib.inventory.getItemDefinition(name)Devuelve
ItemDefinition (name, label, weight, unique, close, description, image?), o null cuando el inventario no conoce el objeto.
Ejemplo
const label = inventory.getItemDefinition("water")?.label ?? "water";
notify(source, `You bought ${label}`, "success");inventory.registerShop
Registra una tienda que el servidor abre para un jugador (no tiene un lugar propio). ai-core la registra de nuevo en cualquier inventario que arranque más tarde; llámalo una vez al arrancar.
Lado: Servidor · Espera: no
inventory.registerShop(name: string, label: string, items: ShopProduct[]): voidaiLib.inventory.registerShop(name, label, items)Prop
Type
Devuelve
void.
Ejemplo
inventory.registerShop("police_shop", "Police supplies", [
{ name: "handcuffs", price: 0 },
{ name: "radio", price: 50 },
]);inventory.openShop
Abre una tienda registrada en la pantalla de un jugador.
Lado: Servidor · Espera: no
inventory.openShop(source: number, name: string): booleanlocal ok = aiLib.inventory.openShop(source, name)Devuelve
boolean: true cuando se abrió.
Ejemplo
onClientCallback("my-police:shop", (source) => {
if (!online.onDutyIn(source, ["police"])) return fail("NOT_ON_DUTY");
return { ok: inventory.openShop(source, "police_shop") };
});Aquí no se comprueba ni la distancia ni el acceso: compruébalos antes de llamarlo.
Jugadores y personajes
online, onCharacter, notify, jugadores cercanos, posiciones y almacenes por jugador: PlayerMap, Cooldowns, KeyedCooldowns, SourceLock, RateLimit, KeyWatchers.
Vehículos
spawnVehicle, vehicleType, randomPlate, vehículos más cercanos, entidades a partir de net ids del cliente, vehicleKeys, combustible y garajes.