How to Write Chat Commands

The last page talks about installing the default chat resource that comes with alt:V in the resources folder when you download the binaries from the website.

In this section we're going to cover how to write basic chat commands for something like spawning the player, adding a vehicle, etc.

Remember to change the individual files for the chat resource to allow better handling of commands.

Command Syntax

Almost all chat resources have a similar format where they require a callback function to execute your command.

Let's take a look at what that looks like.

chat.registerCmd('test', (player) => {
    console.log('hello world');
});

When a player types /test in-game. Your server console will print hello world. What is happening in the function above is that a player instance is being passed back from

Writing Positions to Chat

A utility that a lot of people usually need is to get the position of the player. Here's how we can do that and print that to chat.

chat.registerCmd('pos', (player) => {
    chat.send(player, `${JSON.stringify(player.pos)}`);
    console.log(player.pos);
});

If you want to print these positions to the local player's console you can add a console.log for messages on client-side.

Writing a Vehicle Spawner

Below is some provided code to spawn a vehicle when you type /vehicle infernus in-game. It will spawn the vehicle model known as infernus in the game and place it right on top of the player.

Sorry if your player dies doing this.

chat.registerCmd('vehicle', (player, modelName) => {
    if (!modelName) {
        chat.send(player, `/vehicle [modelName]`);
        return;
    }

    let vehicle;

    try {
        vehicle = new alt.Vehicle(modelName, player.pos.x, player.pos.y, player.pos.z, 0, 0, 0);
    } catch (err) {
        chat.send(player, `~r~Invalid vehicle model.`);
        return;
    }
});

Spawn the Player with a Command

You can assign a player model or use a default player using this simple command. In most cases servers won't require you to spawn the player so this could be seen as a change model command as well.

chat.registerCmd('spawn', (player, modelName) => {
    if (!modelName) {
        modelName = 'mp_m_freemode_01';
    }

    player.spawn(player.pos.x, player.pos.y, player.pos.z, 0);

    try {
        player.model = modelName;
    } catch (err) {
        player.send(player, 'Invalid Model. Using default.');
        player.model = 'mp_m_freemode_01';
    }
});

Excercises

Try solving these problems based on their vague descriptions to get more familiar with the alt:V API.

  • Only allow spawning 1 vehicle per player.
  • Set player health / armour.
  • Command to respawn the player after death.
  • Teleport the player somewhere else.
  • Teleport the player using arguments from chat.
  • Destroy the vehicle you are inside of.
  • Command to start / stop vehicle engine.

Try these excercises before moving forward.

results matching ""

    No results matching ""