meshcore.js
Guides

Answer a command

A command that answers in a DM or on a channel, in a few lines.

Someone sends /heard to the bot. The bot answers with the nodes it heard in the last hour.

commands/heard.ts
export default new CommandBuilder()
  .setName('heard')
  .setDescription('Nodes heard in the last hour')
  .setHandler((ctx) => {
    const since = Date.now() - 3_600_000;
    const heard = ctx.client.contacts.cache.filter((contact) => contact.lastSeen.getTime() > since);
    return ctx.reply(
      new MessageBuilder()
        .setTitle(`📡 ${heard.size} heard`)
        .addLines(heard.toArray().map((contact) => contact.name))
        .setOverflow('truncate'),
    );
  });
main.ts
import { Client, SerialTransport } from '@meshcorejs/client';

const client = new Client({
  transport: new SerialTransport({ path: '/dev/ttyACM0' }),
  load: import.meta.dirname,
});

await client.login();

What happens

The file is picked up at login because it sits in commands/ and exports the builder. A missing name or handler stops the bot at startup with a clear message instead of failing later on the air.

In a DM the trigger is /heard. On a channel it is @ClubBot heard, with the name the radio advertises. This rule is the same for every bot and cannot be changed.

ctx.reply() answers where the command came from. The MessageBuilder keeps the answer under the 160-byte limit of a radio message and cuts the list when it is too long.

Go further

On this page