The Simplest of Bots

An exceedingly simple example with one command

So let's go with your very simplest bot you could create. Here's the simplest bot ever created with Detritus. Bear with me for the explanation below!

const { CommandClient } = require('detritus-client');

const token = '';
const commandClient = new CommandClient(token, {
  prefix: '..',
});

commandClient.add({
  name: 'ping',
  run: (context, args) => {
    return context.reply('pong!');
  },
});

(async () => {
  const client = await commandClient.run();
  console.log(`Client has loaded with a shard count of ${client.shardCount}`);
})();

Unwrapping the example

So, let's go through pretty much every line here for those of you that might be a little confused on a few things. Explanations under each piece of code

const { CommandClient } = require('detritus-client');

This obviously imports the client directly from the detritus-client. There are actually four different clients you can use, and we'll explore them with time - but this one is the simplest and it'll get you started the fastest because it includes a command handlers.

const token = '';
const commandClient = new CommandClient(token, {
  prefix: '..',
});

This defines a token and then defines the command client - that is to say, the "wrapper" where you'll create all your commands. So basically it's literally the Command Handler itself, not the bot client which we create later. We have a prefix by default here, .. , which of course you can customize to your needs.

commandClient.add({
  name: 'ping',
  run: (context, args) => {
    return context.reply('pong!');
  },
});

Here we create our first command, the "ping" command. There are better ways to define commands, but this gets you started, at least! As the code makes pretty clear, we're just answering pong! to anyone that says ..ping (remember we defined our prefix in the previous block!). Not too excited but hey, it's something! You gotta start somewhere :)

(async () => {
  const client = await commandClient.run();
  console.log(`Client has loaded with a shard count of ${client.shardCount}`);
})();

This block seems a little complicated, but in reality it's just an asyncronous function that runs itself (an async IIFE , or Immediately Invoked Function Expression). If you didn't want to know when the client was ready, using just commandClient.run(); would be perfectly valid, really. In this case, we're making sure we have a confirmation that the client is connected and ready to work.

There's a few alternative ways to do this, actually. Here's one that I like because it's a bit cleaner (and also has error handling):

commandClient.run().then(client => {
  console.log(`Client has loaded with a shard count of ${client.shardCount}`);
}).catch(err => {
  console.error(err);
});

Last updated