leet.events

This is where a script subscribes to what happens in the client: calls into the browser, admins nearby, the drawing frame. Outgoing remote calls to the server are intercepted by leet.packets.on('callRemote'). It is also where a script gets its Stop button, through onUnload.

Every on... function returns an off() function that removes exactly that subscription. Stop does not remove browser, admin or drawing subscriptions for you: call their off() in onUnload. Stop removes leet.packets subscriptions by itself.

FunctionCalls you
onUnloadwhen the user presses Stop on your script
onAdminNearbywhen an admin enters or leaves a radius around you
onDrawcontinuously, to draw on screen with leet.ui
onBrowserExecute / onBrowserCallfor every client-to-browser (CEF) call, before the page receives it

Packets use only leet.packets.

leet.events.crypt

TypeScript
leet.events.crypt(name: string): string | null

Returns the name a client event goes out under on GTA5RP. Pass it to mp.events.callRemote.

The first call for a name returns null. That call asks the server for the name; a few seconds later crypt returns it, and from then on at once. It works for any name, whether or not the event has been seen in the logger. So ask for every name your script sends when it starts, and send an event only once its name is there:

JavaScript
// At start: ask for every name the script sends.
const names = ["s:voiceChat:update", "s:phone:open"];
names.forEach((name) => leet.events.crypt(name));

// Later, when sending: null means the name has not arrived yet.
const wire = leet.events.crypt("s:voiceChat:update");
if (wire !== null) mp.events.callRemote(wire, 12, -1);

Keep in mind

  • Do not fall back to the readable name (crypt(name) ?? name): the event then goes out under its readable name.
  • A reconnect forgets the names: ask again.
  • Returns null on other servers, for an empty name and for a name GTA5RP does not encode.

Errors: leet: name must be a string (name is not a string).

leet.events.callRemote

TypeScript
leet.events.callRemote(name: string, ...args: any[]): void
leet.events.callRemoteUnreliable(name: string, ...args: any[]): void
leet.events.callRemoteProc(name: string, ...args: any[]): Promise<any>
leet.events.call(name: string, ...args: any[]): void

The same as mp.events.callRemote, callRemoteUnreliable, callRemoteProc and call, but unseen. Use them in a script you publish on the marketplace, so its buyers cannot read what it sends.

  • The event logger, leet.packets.on('callRemote') and the outgoing packet subscriptions of leet.packets do not see these calls, and cannot block them.
  • Another script cannot wrap them: they call mp.events as it was before any script of the session ran, so a wrapper another script put on mp.events.callRemote never sees the call.
  • call runs on this client: the handlers added for the event with mp.events.add still receive it, whoever added them.
JavaScript
const wire = leet.events.crypt("s:voiceChat:update");
if (wire !== null) leet.events.callRemote(wire, 12, -1);

Keep in mind

  • Pass the values straight in. A value your code first passes through a shared built-in (JSON.stringify, an array or string method) can be read by a script that replaced that built-in.
  • Keep your leet to yourself: do not put it, or these functions, on globalThis.
  • The answer of callRemoteProc comes back as an incoming packet, which leet.packets still shows.
  • Nothing hides a call from the server, or from tools outside the game.

Errors: leet: not available (the client could not read mp.events at the session's start).

leet.events.onUnload

TypeScript
leet.events.onUnload(callback: () => void): () => void

Registers cleanup code for the current script and gives the script a Stop button in the menu's script list. Returns off(), which removes this handler without calling it. Calling off() again does nothing. If it removes the script's last onUnload handler, the row goes back to Execute.

JavaScript
const tick = setInterval(() => mp.console.logInfo('still running'), 3000);

const offUnload = leet.events.onUnload(() => clearInterval(tick));

// Stop on our own after one minute; the row goes back to Execute.
setTimeout(() => {
    clearInterval(tick);
    offUnload();
}, 60000);

Parameters

  • callback (function): runs with no arguments when the user presses Stop.

Keep in mind

  • While a script has at least one onUnload handler, its row in the script list shows a red Stop button instead of Execute.
  • Pressing Stop calls all of that script's onUnload handlers once, then removes them. The row shows Execute again.
  • An exception thrown by a handler is swallowed: the remaining handlers still run and the row returns to Execute.
  • When the client reconnects to a server, all onUnload handlers are dropped without being called (the server reloads its client scripts on reconnect).
  • onUnload is available only to scripts started from the menu script list (Execute or Auto Exec).

Careful. Apart from leet.packets, the client does nothing for you when you press Stop: Stop itself removes the leet.packets subscriptions. Your handler must undo everything else the script set up:

  • call off() for every leet subscription;
  • call mp.events.remove(...) for every RAGE event handler the script added;
  • call clearInterval / clearTimeout for its timers;
  • restore anything else it changed (game state, settings, created entities, and so on).

Errors: leet: callback must be a function (callback is not a function), leet: too many subscriptions (the script already has 32 onUnload handlers), leet: onUnload needs a script run from the menu (the calling code was not started from the menu script list).

leet.events.onAdminNearby

TypeScript
leet.events.onAdminNearby(callback: (event: AdminNearbyEvent) => void, radius?: number): () => void

Calls callback when a server admin comes within radius meters of the local player, and again when they leave that radius. Returns off(), which removes the subscription; calling off() again does nothing.

JavaScript
const off = leet.events.onAdminNearby((e) => {
    if (e.entered) leet.ui.notify(`Admin ${e.name} nearby`, 'warning');
}, 150);

leet.events.onUnload(off);

Parameters

  • callback (function): receives an event object (below).
  • radius (number, optional): radius in meters, greater than 0 and at most 100000. Default 100.

The event object:

PropertyTypeMeaning
event.remoteIdnumberThe admin's remote id.
event.namestringThe admin's name. For an admin who left the server, the last known name; empty only if their name was never known.
event.distancenumber | nullDistance to the local player in meters. Always 0 for a hidden admin (enter and leave). null when a non-hidden admin is not visible or left the server.
event.dimensionnumberThe admin's dimension. 0 when the admin left the server.
event.hiddenbooleantrue in every event about a hidden admin, including the leave event of an admin who was hidden when last seen inside.
event.enteredbooleantrue when the admin entered the radius, false when they left it.

Keep in mind

  • Admin positions are checked about 4 times per second.
  • An admin who is already inside the radius when you subscribe arrives with entered: true on the first check.
  • Hidden admins (close to you but invisible) always count as inside. See Distance and hidden admins.
  • Every event about a hidden admin, enter or leave, has hidden: true and distance: 0. This includes the leave event of an admin who was hidden when last seen inside, even if they left the server.
  • If an admin leaves the server while inside the radius, a leave event (entered: false) comes with the admin's last known name (empty only if their name was never known), dimension: 0 and distance: null (or hidden: true and distance: 0 if they were hidden).
  • An exception thrown by the callback is swallowed.
  • The subscription lasts until you call its off() or until the client reconnects. Stopping the script does not remove it: remove it in onUnload.
ErrorWhen
leet: callback must be a functioncallback is not a function.
leet: invalid radiusradius is given and is not a number, is NaN / Infinity, is 0 or less, or is greater than 100000.
leet: too many subscriptions32 onAdminNearby subscriptions already exist in the client.

leet.events.onDraw

TypeScript
leet.events.onDraw(callback: () => void): () => void

Registers a drawing handler. Inside it you draw on the game screen with the leet.ui draw calls; see Drawing on screen. Returns off(), which removes this handler; calling off() again does nothing.

JavaScript
const offDraw = leet.events.onDraw(() => {
    leet.ui.drawText('leet', 20, 20, 0xFFFFFFFF, 18);
});

leet.events.onUnload(offDraw);

Parameters

  • callback (function): runs with no arguments. Make your draw calls here.

Keep in mind

  • callback runs continuously while the subscription exists.
  • Everything drawn during one round of onDraw handlers stays on screen until the next round. To move or change something, draw it differently next time. To hide it, stop drawing it.
  • The draw calls of all onDraw handlers of all scripts together form the picture. Later draw calls are drawn over earlier ones.
  • When the last onDraw handler is removed, the drawing disappears.
  • Draw calls work only inside an onDraw handler. Anywhere else they throw leet: draw calls work only inside onDraw.
  • An exception thrown by the callback is swallowed.

Careful. The subscription lasts until you call its off() or until the client reconnects. Stopping the script does not remove it: remove it in onUnload, or your drawing stays on screen.

Errors: leet: callback must be a function (callback is not a function), leet: too many subscriptions (32 onDraw subscriptions already exist in the client).

Browser observers

Two functions show a script the calls the client makes into the game's browser (CEF) pages, and let it rewrite them. The HUD, the chat and every server-made interface go through these calls.

FunctionObserves
leet.events.onBrowserExecutebrowser.execute(code): a piece of JavaScript run inside a page.
leet.events.onBrowserCallbrowser.call(name, ...args): an event sent to a page.

Common to both

  • Synchronous, before the call reaches the page. Your callback runs inside the call, before the page receives it. What you change with setCode / setArgs is what the page gets.
  • Never blocked. There is no block(). To make a call do nothing, replace its payload with a harmless one.
  • Scripts first. Scripts see the real values. The client's own processing (Streamer Mode, the event logger) runs afterwards, so a script's rewrite can never undo it.
  • No recursion. A browser call made while any leet.events callback is running (a packet, draw or unload callback included) is forwarded normally and is not shown again.
  • Errors are swallowed. An exception in a callback does not affect other callbacks or the call.
  • Lifetime. A subscription lasts until you call its off() or until the client reconnects. Stopping the script does not remove it: call off() in onUnload. After off() your callback simply does not run any more.
  • Limit. At most 32 subscriptions of each kind exist at the same time in the whole client.

Careful. HUD pages call the browser several times a second, and a slow callback slows the HUD. Keep callbacks cheap.

leet.events.onBrowserExecute

TypeScript
leet.events.onBrowserExecute(callback: (e: { code: string, setCode(code: string): void }) => void): () => void

Calls callback for every browser.execute made in the client. Returns off(), which removes the subscription; calling off() again does nothing.

JavaScript
const off = leet.events.onBrowserExecute((e) => {
    // The server pushes the displayed cash with a line such as `mainHud.playerCash = 1500;`.
    if (e.code.startsWith('mainHud.playerCash')) {
        e.setCode('mainHud.playerCash = 999999;');      // the page shows this instead
    }
});

leet.events.onUnload(off);

The callback argument

PropertyTypeMeaning
e.codestringThe JavaScript the page is about to run.
e.setCode(code)methodReplaces the code the page runs. code must be a string. The last setCode of the call wins.

Keep in mind

  • setCode must be called while the callback runs. Called later, it throws.
ErrorWhen
leet: callback must be a functioncallback is not a function.
leet: too many subscriptions32 onBrowserExecute subscriptions already exist.
leet: code must be a string(setCode) the argument is not a string.
leet: the call has already finished(setCode) called after the callback returned.

leet.events.onBrowserCall

TypeScript
leet.events.onBrowserCall(callback: (e: { name: any, args: any[], setArgs(args: any[]): void }) => void): () => void

Calls callback for every browser.call made in the client. Returns off(), which removes the subscription; calling off() again does nothing.

JavaScript
const off = leet.events.onBrowserCall((e) => {
    if (typeof e.name === 'string' && e.name.startsWith('chat:push')) {
        mp.console.logInfo(`[chat] ${e.args.join(' ')}`);
    }
});

leet.events.onUnload(off);

The callback argument

PropertyTypeMeaning
e.nameanyThe event name, the first argument of browser.call (normally a string).
e.argsArrayThe remaining arguments, as real JS values.
e.setArgs(array)methodReplaces the arguments after the name. The array must hold exactly as many values as e.args. The last setArgs of the call wins.

Keep in mind

  • The array is read when setArgs is called; changing it later has no effect. The values themselves are not deep-copied.
  • e.args keeps the values the call was made with, while the page receives the replaced ones.
  • setArgs must be called while the callback runs.
ErrorWhen
leet: callback must be a functioncallback is not a function.
leet: too many subscriptions32 onBrowserCall subscriptions already exist.
leet: setArgs needs one value per argument(setArgs) the array is not the same length as e.args.
leet: the call has already finished(setArgs) called after the callback returned.

Recipes: events

Full cleanup in onUnload

A script that watches remote calls, draws the last event name on screen every frame, and prints statistics every 5 seconds. Everything it sets up itself is undone in onUnload.

JavaScript
let lastName = '-';
let total = 0;

// 1. Packet subscription: Stop removes it itself
leet.packets.on('callRemote', (call) => {
    lastName = call.name;
    total++;
});

// 2. RAGE event handler
const onRender = () => {
    mp.game.graphics.drawText(`last remote: ${lastName}`, [0.5, 0.05], {
        font: 4,
        color: [255, 255, 255, 220],
        scale: [0.4, 0.4],
        outline: true,
    });
};
mp.events.add('render', onRender);

// 3. Timer
const timer = setInterval(() => {
    mp.console.logInfo(`[stats] ${total} remote calls so far`);
}, 5000);

// Cleanup: Stop removes the packet subscription; the rest is undone here
leet.events.onUnload(() => {
    mp.events.remove('render', onRender);
    clearInterval(timer);
    mp.console.logInfo('[stats] stopped');
});

Every "start" has its own "stop": Stop removes the packet subscription itself (or off() removes it earlier), mp.events.remove with the same function undoes mp.events.add, clearInterval removes the timer.

Farming bot that pauses while an admin is near

The bot works on an interval with Anti-AFK on. When any admin comes within 150 m, it pauses; when the last one leaves, it resumes.

JavaScript
const prevAntiAfk = leet.features.get('player.anti_afk');
const near = new Set();
let timer = null;

function resume() {
    if (timer) return;
    leet.features.set('player.anti_afk', true);
    timer = setInterval(() => {
        // ... one bot step ...
    }, 1000);
}

function pause() {
    clearInterval(timer);
    timer = null;
    leet.features.set('player.anti_afk', false);
}

resume();

const offAdmins = leet.events.onAdminNearby((e) => {
    if (e.entered) {
        if (near.size === 0) {
            pause();
            leet.ui.notify(`Admin ${e.name} nearby, bot paused`, 'warning');
        }
        near.add(e.remoteId);
    } else {
        near.delete(e.remoteId);
        if (near.size === 0) {
            resume();
            leet.ui.notify('No admins nearby, bot resumed', 'success');
        }
    }
}, 150);

leet.events.onUnload(() => {
    offAdmins();
    clearInterval(timer);
    if (prevAntiAfk !== undefined) leet.features.set('player.anti_afk', prevAntiAfk);
});

Several admins can be near at once, so the script keeps a Set of remoteIds and resumes only when it is empty. On Stop it puts Anti-AFK back the way it was before the script started.

Special reaction to hidden admins

JavaScript
const offAdmins = leet.events.onAdminNearby((e) => {
    if (!e.entered) {
        mp.console.logInfo(`[admins] ${e.name || `#${e.remoteId}`} left the area`);
        return;
    }
    if (e.hidden) {
        leet.ui.notify(`Hidden admin right next to you: ${e.name}`, 'error');
        mp.console.logWarning(`[admins] hidden admin ${e.name} (#${e.remoteId})`);
    } else {
        leet.ui.notify(`Admin ${e.name} at ${Math.round(e.distance)} m`, 'warning');
    }
});

leet.events.onUnload(offAdmins);

A hidden admin's distance is always 0, so the distance is shown only for regular admins. The name can be empty, in which case the log falls back to remoteId.

A crosshair

JavaScript
const COLOR = 0xFF00FF00; // opaque green
const GAP = 4;
const LEN = 10;

const offDraw = leet.events.onDraw(() => {
    const { width, height } = leet.ui.screen();
    if (width === 0) return; // screen size not known yet
    const cx = width / 2;
    const cy = height / 2;

    leet.ui.drawLine(cx - GAP - LEN, cy, cx - GAP, cy, COLOR, 2);
    leet.ui.drawLine(cx + GAP, cy, cx + GAP + LEN, cy, COLOR, 2);
    leet.ui.drawLine(cx, cy - GAP - LEN, cx, cy - GAP, COLOR, 2);
    leet.ui.drawLine(cx, cy + GAP, cx, cy + GAP + LEN, COLOR, 2);
    leet.ui.fillCircle(cx, cy, 1.5, COLOR);
});

leet.events.onUnload(offDraw);

The screen size comes from leet.ui.screen() every frame. While it is not known yet (width === 0), the frame is skipped.

Show admins on screen

The admin list is refreshed once a second with a timer; the handler only draws what was last read. Both are removed in onUnload.

JavaScript
let admins = [];
const refresh = setInterval(() => {
    admins = leet.players.admins();
}, 1000);

const offDraw = leet.events.onDraw(() => {
    if (admins.length === 0) return;
    const x = 20;
    let y = 300;
    leet.ui.fillRect(x - 8, y - 6, 260, 26 + admins.length * 20, 0xA0000000);
    leet.ui.drawText(`Admins online: ${admins.length}`, x, y, 0xFFFFC107, 18);
    for (const a of admins) {
        y += 20;
        const where = a.hidden ? 'HIDDEN' : a.distance === null ? 'far' : `${a.distance.toFixed(0)} m`;
        const color = a.hidden ? 0xFFFF5252 : 0xFFFFFFFF;
        leet.ui.drawText(`${a.name}  ${where}`, x, y, color, 16);
    }
});

leet.events.onUnload(() => {
    clearInterval(refresh);
    offDraw();
});

onDraw runs continuously, so the list is read in the timer and the handler draws what is already there.

Find out what a server sends to its HUD

JavaScript
const seen = new Set();

const off = leet.events.onBrowserExecute((e) => {
    // The first 80 characters are enough to tell calls apart; log each shape once.
    const head = e.code.slice(0, 80);
    if (seen.has(head)) return;
    seen.add(head);
    mp.console.logInfo(`[execute] ${head}`);
});

leet.events.onUnload(off);

The HUD sends the same calls several times a second. The script remembers the start of the code and logs each call shape once.

Hide words in incoming chat

JavaScript
const BAD = /\b(spoiler|badword)\b/gi;
const censor = (a) => (typeof a === 'string' ? a.replace(BAD, '***') : a);

const off = leet.events.onBrowserCall((e) => {
    if (typeof e.name !== 'string' || !e.name.startsWith('chat:push')) return;
    // One value per argument: strings are filtered, everything else is passed through untouched.
    const clean = e.args.map(censor);
    if (clean.some((value, i) => value !== e.args[i])) e.setArgs(clean);
});

leet.events.onUnload(off);

map keeps the array length, which setArgs requires. If nothing was replaced, the script leaves the call alone.

Next: Features