TomerRon / cordless

🤖 Declarative Discord bot framework. Build your first bot in 5 minutes with 3 lines of code!
ISC License
57 stars 2 forks source link

feat(commands): Allow commands to receive subcommands #33

Closed TomerRon closed 2 years ago

TomerRon commented 2 years ago

This PR implements passing a list of subcommands to commands. A command can now either be a BotCommandWithHandler (as before) or a BotCommandWithSubcommands (new).

A BotCommandWithSubcommands must have an array of subcommands: BotCommandWithHandler[].

In other words, subcommands cannot be nested more than one level deep (according to the Discord API requirements).

See: https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups


Basic example

This adds a /define commands with two subcommands, dictionary and urban. Usage: /define dictionary <input> or /define urban <input>.

const dictionary: BotCommand = {
  name: "dictionary",
  description: "Get the dictionary definition of a word.",
  options: [
    {
      type: "STRING",
      name: "input",
      required: true,
    },
  ],
  handler: async ({ interaction }) => {
    const input = interaction.options.getString("input", true);

    const result = await (
      await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${input}`)
    ).json();

    interaction.reply(result[0].meanings[0].definitions[0].definition);
  },
};

const urban: BotCommand = {
  name: "urban",
  description: "Get the urbandictionary definition of a word.",
  options: [
    {
      type: "STRING",
      name: "input",
      required: true,
    },
  ],
  handler: async ({ interaction }) => {
    const input = interaction.options.getString("input", true);

    const result = await (
      await fetch(`https://api.urbandictionary.com/v0/define?term=${input}`)
    ).json();

    interaction.reply(result.list[0].definition);
  },
};

const define: BotCommand = {
  name: "define",
  subcommands: [dictionary, urban],
};

init({
  commands: [define],
  functions: [],
  token: process.env.BOT_TOKEN!,
});
TomerRon commented 2 years ago

:tada: This PR is included in version 3.0.0-beta.4 :tada:

The release is available on:

Your semantic-release bot :package::rocket:

TomerRon commented 2 years ago

:tada: This PR is included in version 3.0.0 :tada:

The release is available on:

Your semantic-release bot :package::rocket: