1.0.44 • Published 2 years ago

interactions.ts v1.0.44

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Discord Interactions.TS

A lightweight but powerful framework for Discord's Interactions. Designed for scalability and simplicity.

Getting Started

An example bot using the framework is available here. Additional code snippets can be found below.

Install

npm install interactions.ts

Links

Receiving Interactions

Interactions.TS is designed to work with any webserver, with it only taking the raw request body and the X-Signature-Ed25519/X-Signature-Timestamp headers for authorization. The headers are optional, and can be left out if you're handling authorization at an earlier stage.

For this example, we're using Fastify:

const server = fastify();
server.register(rawBody);

server.post("/", async (request, reply) => {
  const signature = request.headers["x-signature-ed25519"];
  const timestamp = request.headers["x-signature-timestamp"];

  try {
    const [onResponse, finished] = app.handleInteraction(
      request.rawBody,
      timestamp,
      signature
    );

    onResponse.then((response) => {
      if ("getHeaders" in response) {
        res.headers(response.getHeaders()).code(200).send(response);
        return;
      }

      res.code(200).send(response);
    });

    await finished;
  } catch (err) {
    console.error(err);
  }
});

Registering a Slash Command

This will create a global /ping command on your application. If one is already registered, it will be overwritten.

const app = new DiscordApplication({
  clientId: process.env.CLIENT_ID,
  token: process.env.TOKEN,
  publicKey: process.env.PUBLIC_KEY,
});

await app.commands.register(
  new SlashCommand(new SlashCommandBuilder("ping", "A simple ping command!"), async (context) => {
    context.reply("Pong!");
  })
);

Command Groups

Command groups, subcommand groups and subcommands are just a little more complex:

await app.register([
  new CommandGroup(
    new CommandGroupBuilder("config", "A simple config command.")
      .addSubcommand(new SubcommandOption("get", "Get a config value."))
      .addSubcommand(new SubcommandOption("set", "Set a config value.")),
    {
      get: {
        handler: async (context) => {
          const value = "x";
          context.reply(new MessageBuilder().setContent(`Config value: ${value}!`));
        }
      },
      set: {
        handler: async (context) => {
          context.reply(new MessageBuilder().setContent("Config value set!"));
        }
      }
    }
  )
]);

Guild Commands

const guild = new CommandManager(app, guildId);

await guild.register(
  new SlashCommand(new SlashCommandBuilder("pingping", "A guild-specific ping command!"), async (context) => {
    context.reply("Pongpong");
  })
);

Components

Components must be registered in a similar fashion with a unique ID, creating a sort of "template" for your components. You can then create an instance using context.createGlobalComponent() which will return a deeply cloned version of your component as a builder, allowing you to further modify it before using it in a response.

Registering a ping command again, this time with a button that reveals a word stored in its state:

app.commands.register(
  new SlashCommand(
    new SlashCommandBuilder("ping", "A simple ping command!"),
    async (context) => {
      context.reply(
        new MessageBuilder("Press the button to see a surprise...").addComponents(
          new ActionRowBuilder().addComponents(await context.createComponent("testButton", { word: "Surprise!" }))
        )
      );
    },
    [
      new Button(
        "example",
        new ButtonBuilder(ButtonStyle.Primary, "Example Button"),
        async (
          ctx: ButtonContext<{
            word: string;
          }>
        ) => {
          return ctx.reply(ctx.state.word);
        }
      )
    ]
  )
);

Namespacing

Command interfaces present an additional components property, allowing you to tie components to a command. This prefixes the component IDs with the command's name (<command>.<component>), and can then only be retrieved within that command using context.createComponent().

State

You can also pass an arbitrary object when creating a component instance, allowing you to store state information inside the component's custom_id property. (Later accessible in context.state).

This state is stored in the custom_id property by default, which will constrain the size of your data. To avoid this, an external cache such as Redis can be configured:

const redisClient = createClient();

await redisClient.connect();

const app = new DiscordApplication({
  clientId: process.env.CLIENT_ID,
  token: process.env.TOKEN,
  publicKey: process.env.PUBLIC_KEY,

  cache: {
    get: (key) => redisClient.get(key),
    set: (key, ttl, value) => redisClient.setEx(key, ttl, value)
  }
});
1.1.0

2 years ago

1.0.39

2 years ago

1.0.38

2 years ago

1.0.40

2 years ago

1.0.44

2 years ago

1.0.43

2 years ago

1.0.42

2 years ago

1.0.41

2 years ago

1.0.29

2 years ago

1.0.28

2 years ago

1.0.27

2 years ago

1.0.33

2 years ago

1.0.32

2 years ago

1.0.31

2 years ago

1.0.30

2 years ago

1.0.37

2 years ago

1.0.36

2 years ago

1.0.35

2 years ago

1.0.34

2 years ago

1.0.22

2 years ago

1.0.21

2 years ago

1.0.20

2 years ago

1.0.26

2 years ago

1.0.25

2 years ago

1.0.24

2 years ago

1.0.23

2 years ago

1.0.19

2 years ago

1.0.18

2 years ago

1.0.17

2 years ago

1.0.16

2 years ago

1.0.15

2 years ago

1.0.14

2 years ago

1.0.13

2 years ago

1.0.12

2 years ago

1.0.11

2 years ago

1.0.10

2 years ago

1.0.9

2 years ago

1.0.8

2 years ago

1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago