AI Core

Stored characters

Read and change any character, loaded or not - find it, read it, move its money, jobs, gangs, metadata and name, save it, delete it.

The exports on Characters answer about a player who is connected with a loaded character. The ones here answer about any character, connected or not: ai-core reads a loaded character from memory and a stored one from the database, and a write reaches the live character when it is loaded and the row when it is not.

Three things to know before you use them:

  • A character is addressed by its character id (charId, a number - CharacterInfo.id). A citizenid is text and belongs to the framework bridges; turn one into the other with GetCharIdByCitizenId, never by converting the value yourself.
  • These exports answer through a callback (done), because a stored character needs a database read and no promise crosses a resource boundary. In TypeScript the lib's characters module gives you a Promise instead; in Lua aiLib.characters waits for you inside a thread.
  • A write answers ActionResult: { ok: true }, or { ok: false, error: "LANG_KEY" } with one of ai-core's own lang keys (locales/en.json), so you can show it with callAction or translate it yourself.

Never read or write ai-core's tables (ai_core_characters, ai_core_accounts, ai_core_character_jobs...) with your own queries. Characters live in memory and are written on ai-core's schedule, so a direct SELECT can be stale and the columns are internal.

GetCharIdByCitizenId

The character id behind a citizenid, loaded or not. A loaded character answers from memory, a stored one with one indexed read.

Side: Server · Waits: no (the answer arrives in done) · Lib: characters.idOf

Signature
GetCharIdByCitizenId(citizenid: string, done: (charId: number | null) => void): void
Lua
exports['ai-core']:GetCharIdByCitizenId(citizenid, function(charId) end)

Parameters

Prop

Type

Returns

Nothing. The answer arrives in done.

Example

import { characters } from "@aicore8/lib/server";

// The lib wraps the callback in a Promise.
export async function fine(citizenid: string, amount: number): Promise<boolean> {
  const charId = await characters.idOf(citizenid);
  if (charId === null) return false;
  const result = await characters.removeMoney(charId, "bank", amount, "Speeding fine");
  return result.ok;
}

GetOfflineCharacter

Everything ai-core keeps about one character: name and birth date, money per account, jobs, gangs, metadata, stored position, last save, and the server id when it is loaded.

Side: Server · Waits: no (the answer arrives in done) · Lib: characters.get

Signature
GetOfflineCharacter(charId: number, done: (character: OfflineCharacter | null) => void): void
Lua
exports['ai-core']:GetOfflineCharacter(charId, function(character) end)

Parameters

Returns

Nothing. done gets an OfflineCharacter or null. A loaded character answers from memory, so its money and memberships are the live ones and source is the player.

Example

import { characters } from "@aicore8/lib/server";

export async function describe(charId: number): Promise<string> {
  const c = await characters.get(charId);
  if (!c) return "unknown character";
  const where = c.source === null ? "offline" : `online as ${c.source}`;
  return `${c.info.firstname} ${c.info.lastname} (${where}), bank ${c.money.bank ?? 0}`;
}

SearchCharacters

Characters by a typed text, loaded or not: first or last name prefixes ("jane doe" works too), citizenid, fivem / license / discord id. 25 a page, newest character first.

Side: Server · Waits: no (the answer arrives in done) · Lib: characters.search

Signature
SearchCharacters(text: string, done: (page: CharacterSearchPage) => void, cursor?: number): void
Lua
exports['ai-core']:SearchCharacters(text, function(page) end, cursor)

Parameters

Prop

Type

Returns

Nothing. done gets a CharacterSearchPage: up to 25 matches and the next cursor (null on the last page). An empty text answers the newest characters, so a browse screen works without a term.

Example

import { characters, onClientCallback } from "@aicore8/lib/server";
import { oneArg, readText } from "@aicore8/lib/shared";

onClientCallback(
  "myscript:searchPeople",
  { args: oneArg((v) => readText(v, 64)), rate: { count: 10, windowMs: 10_000 } },
  async (_source, text) => {
    const page = await characters.search(text);
    return { ok: true, people: page.characters, next: page.next };
  },
);

GetCharactersOfUser

Every character of one account, by slot. Use it for a screen that shows a player all their characters, or for an admin tool that works on an account.

Side: Server · Waits: no (the answer arrives in done) · Lib: characters.ofUser

Signature
GetCharactersOfUser(user: number | string, done: (characters: StoredCharacter[]) => void): void
Lua
exports['ai-core']:GetCharactersOfUser(user, function(characters) end)

Parameters

Prop

Type

Returns

Nothing. done gets an array of StoredCharacter.

Example

import { characters, resourceExport } from "@aicore8/lib/server";

const core = resourceExport("ai-core");

export async function slotsOf(source: number): Promise<number[]> {
  const userId = core.GetUserId(source);
  if (userId === null) return [];
  return (await characters.ofUser(userId)).map((c) => c.slot);
}

GetJobMembers and GetGangMembers

Everyone who holds a job (or is in a gang), loaded or not, a page at a time with their grade. This is the roster a management screen needs: the lib's online mirror only knows the players who are connected.

Side: Server · Waits: no (the answer arrives in done) · Lib: characters.jobMembers

Signature
GetJobMembers(job: string, done: (page: MembersPage) => void, after?: number, limit?: number): void
GetGangMembers(gang: string, done: (page: MembersPage) => void, after?: number, limit?: number): void
Lua
exports['ai-core']:GetJobMembers(job, function(page) end, after, limit)
exports['ai-core']:GetGangMembers(gang, function(page) end, after, limit)

Parameters

Prop

Type

Returns

Nothing. done gets a MembersPage: the members and the after of the next page (null on the last one). Each member carries source, so the connected ones are the entries whose source is not null.

Example

import { characters } from "@aicore8/lib/server";

/** Every member of a job, page by page. */
export async function roster(job: string) {
  const all = [];
  let after: number | undefined;
  do {
    const page = await characters.jobMembers(job, after);
    all.push(...page.members);
    after = page.next ?? undefined;
  } while (after !== undefined);
  return all;
}

Only asking "does anyone hold this job?" reads one row: lib characters.hasJobMember, which calls this export with limit = 1.

AddOfflineMoney, RemoveOfflineMoney and SetOfflineMoney

Money of a character, loaded or not. A loaded character goes through its live wallet (so the player sees it at once), a stored one is written in the database with the same rules and the same ledger row.

Side: Server · Waits: no (the answer arrives in done) · Lib: characters.addMoney

Signature
AddOfflineMoney(charId: number, account: string, amount: number, reason?: string, done?: (result: CharacterResult) => void): void
RemoveOfflineMoney(charId: number, account: string, amount: number, reason?: string, done?: (result: CharacterResult) => void): void
SetOfflineMoney(charId: number, account: string, amount: number, reason?: string, done?: (result: CharacterResult) => void): void
Lua
exports['ai-core']:AddOfflineMoney(charId, account, amount, reason, function(result) end)
exports['ai-core']:RemoveOfflineMoney(charId, account, amount, reason, function(result) end)
exports['ai-core']:SetOfflineMoney(charId, account, amount, reason, function(result) end)

Parameters

Prop

Type

Returns

Nothing. done gets { ok: true }, or { ok: false, error } with a lang key: an unknown character, an account the server does not have, a fractional or negative amount, or - for RemoveOfflineMoney - a balance that cannot pay (unless the account type allows going below zero).

Example

import { characters } from "@aicore8/lib/server";

/** Pays out a sale whether the seller is online or not. */
export async function payOut(charId: number, amount: number): Promise<boolean> {
  const result = await characters.addMoney(charId, "bank", amount, "Vehicle sold");
  if (!result.ok) console.log(`payout refused: ${result.error}`);
  return result.ok;
}

SetOfflineJob and RemoveOfflineJob

Hires, regrades or fires a character whether they are connected or not. The panel's job rules apply (how many jobs a character may hold, whether a second job is allowed), and the unemployed job is never stored: removing the last job is what makes a character unemployed.

Side: Server · Waits: no (the answer arrives in done) · Lib: characters.setJob

Signature
SetOfflineJob(charId: number, job: string, grade: number, done?: (result: CharacterResult) => void): void
RemoveOfflineJob(charId: number, job: string, done?: (result: CharacterResult) => void): void
Lua
exports['ai-core']:SetOfflineJob(charId, job, grade, function(result) end)
exports['ai-core']:RemoveOfflineJob(charId, job, function(result) end)

Parameters

Prop

Type

Returns

Nothing. done gets { ok: true }, or { ok: false, error } with a lang key: unknown character, unknown job, a grade that does not exist, or the panel's job limit.

Example

import { characters } from "@aicore8/lib/server";

/** Fires a member from a job, online or not. */
export async function fire(charId: number, job: string): Promise<boolean> {
  return (await characters.removeJob(charId, job)).ok;
}

SetOfflineGang and RemoveOfflineGang

The same for gangs. A character may be in several gangs but acts for one at a time (SetActiveGang picks that one for a connected player).

Side: Server · Waits: no (the answer arrives in done) · Lib: characters.setGang

Signature
SetOfflineGang(charId: number, gang: string, grade: number, done?: (result: CharacterResult) => void): void
RemoveOfflineGang(charId: number, gang: string, done?: (result: CharacterResult) => void): void
Lua
exports['ai-core']:SetOfflineGang(charId, gang, grade, function(result) end)
exports['ai-core']:RemoveOfflineGang(charId, gang, function(result) end)

Parameters

Prop

Type

Returns

Nothing. done gets { ok: true } or { ok: false, error }, as with jobs.

SetOfflineMeta

One metadata value of a character, loaded or not. A loaded character gets it as a delta on their own game, so their HUD and UI follow at once.

Side: Server · Waits: no (the answer arrives in done) · Lib: characters.setMeta

Signature
SetOfflineMeta(charId: number, key: string, value: unknown, done?: (result: CharacterResult) => void): void
Lua
exports['ai-core']:SetOfflineMeta(charId, key, value, function(result) end)

Parameters

Prop

Type

Returns

Nothing. done gets { ok: true }, or { ok: false, error } for an unknown character or a value JSON cannot hold.

Example

import { characters } from "@aicore8/lib/server";

await characters.setMeta(12, "myscript_licence", { kind: "drive", since: Date.now() });
await characters.setMeta(12, "myscript_licence", null); // takes it away

For a connected player, GetMeta / SetMeta is the shorter path, and reading metadata is only possible there (this page has no GetOfflineMeta: read the whole character with GetOfflineCharacter and take metadata from it).

SetCharacterInfo

Changes the character's own fields: name, birth date, nationality, sex and height. Every field is checked the way the character creation form checks it, so an admin tool cannot write a name the creator would refuse.

Side: Server · Waits: no (the answer arrives in done) · Lib: characters.setInfo

Signature
SetCharacterInfo(charId: number, patch: CharacterInfoPatch, done?: (result: CharacterResult) => void): void
Lua
exports['ai-core']:SetCharacterInfo(charId, patch, function(result) end)

Parameters

Prop

Type

Returns

Nothing. done gets { ok: true }, or { ok: false, error } with a lang key. sex is refused while the character is loaded, because the ped model follows it; everything else reaches a loaded character as a delta.

Example

import { characters } from "@aicore8/lib/server";

const result = await characters.setInfo(12, { lastname: "Doe-Smith", height: 174 });
if (!result.ok) console.log(`name change refused: ${result.error}`);

DeleteCharacter

Deletes a character. It is a soft delete: the row stays for the logs and the character disappears from every list and every search.

Side: Server · Waits: no (the answer arrives in done) · Lib: characters.remove

Signature
DeleteCharacter(charId: number, by?: number | string, done?: (result: CharacterResult) => void): void
Lua
exports['ai-core']:DeleteCharacter(charId, by, function(result) end)

Parameters

Prop

Type

Returns

Nothing. done gets { ok: true }, or { ok: false, error } for an unknown character or a character that is loaded right now - the player has to go back to the character screen first. On success ai-core fires its characterDeleted event; see Events and state.

GetPlayTime

How long a character has been played, in seconds: the saved total plus the running session.

Side: Server · Waits: no for a connected player · Lib: characters.playTime

Signature
GetPlayTime(target: number | { charId: number }, done?: (seconds: number | null) => void): number | null
Lua
local seconds = exports['ai-core']:GetPlayTime(source) -- a connected player: answers at once
exports['ai-core']:GetPlayTime({ charId = 12 }, function(seconds) end)

Parameters

Prop

Type

Returns

number | null: the seconds, when they are known without a database read (a server id, or a { charId } that is loaded). null means "not here, wait for done" - or, for a server id, that the player has no loaded character.

SavePlayer

Writes a connected player's position and metadata now and waits for their queued writes. Use it before something that must not lose the last minutes: a restart, a handover, an admin action you log.

Side: Server · Waits: no (the answer arrives in done) · Lib: characters.save

Signature
SavePlayer(source: number, done?: (ok: boolean) => void): void
Lua
exports['ai-core']:SavePlayer(source, function(ok) end)

Parameters

Prop

Type

Returns

Nothing. ai-core saves on its own (periodically, on unload and on shutdown), so you only need this when you want the write to have happened before your next step.

A character that is not loaded is already written: there is nothing to flush. To move a stored character's spawn point use characters.setOfflinePosition (SetOfflinePosition).

On this page