@discord-interactions/core

中文文档
0.3.23发布于 2024/09/14TypeScriptES Module近 30 天下载 3414

A full command framework for Discord interactions.

原始使用文档
文档目录3 节
  1. Install
  2. Namespacing
  3. State

@discord-interactions/core

Discord server npm version npm downloads Tests status

Core framework for Bots using Discord Interactions - Typedocs

Getting Started

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

Install

npm install @discord-interactions/core

Receiving Interactions

Our framework 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] = await app.handleInteraction(
      request.rawBody,
      timestamp,
      signature
    );

    onResponse.then((response) => {
      reply.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 and differs from the provided data, 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");
  })
);

Command Sync

By default, the framework's sync mode is SyncMode.Enabled. This means that as you register commands, the framework will check them against your commands on Discord's side and create/update them as necessary.

Two other modes are available:

  • SyncMode.Strict: This will also check for deleted commands and delete them from Discord.

  • SyncMode.Disabled: This disables all automatic syncing.


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:

type ButtonState = {
  word: string;
};

export class Ping implements ISlashCommand {
  builder = new SlashCommandBuilder("ping", "Simple ping command.");

  handler = async (ctx: SlashCommandContext): Promise<void> => {
    return ctx.reply(
      new MessageBuilder("Press the button to see a surprise...").addComponents(
        new ActionRowBuilder([await ctx.createComponent("example", { word: "Surprise!" })])
      )
    );
  };

  components = [
    new Button(
      "example",
      new ButtonBuilder(ButtonStyle.Primary, "Example Button"),
      async (ctx: ButtonContext<ButtonState>) => {
        return ctx.reply(ctx.state.word);
      }
    )
  ];
}

Namespacing

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

If you don't want to use namespacing, you can use context.createGlobalComponent() and register your components with app.components.register().

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 or Cloudflare's KV 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)
  }
});
// CACHE being a Cloudflare KV namespace

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

  cache: {
    get: (key) => CACHE.get(key),
    set: (key, ttl, value) => CACHE.put(key, value, { expirationTtl: ttl })
  }
});

版本与发布记录

@discord-interactions/core 共发布 32 个版本,首次发布于 2022/07/09;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.3.23latest2024/09/142 年前
0.3.222024/09/042 年前
0.3.212024/08/292 年前
0.3.202024/08/162 年前
0.3.192024/03/132 年前
0.3.182024/03/132 年前

关于 @discord-interactions/core 的常见问题

@discord-interactions/core 是什么?

A full command framework for Discord interactions.

如何安装 @discord-interactions/core?

在项目目录运行 npm install @discord-interactions/core,或使用 pnpm add / yarn add / bun add。

@discord-interactions/core 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@discord-interactions/core 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@discord-interactions/core 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=16。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@discord-interactions/core 可以商用吗?

@discord-interactions/core 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@discord-interactions/core 的下载量有多少?

根据 npm 官方下载统计,@discord-interactions/core 在 2026/10/13 – 2026/11/11 这 30 天内被下载 3,414 次,日均约 114 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@discord-interactions/core 还在维护吗?

最新版本 0.3.23 发布于 2024/09/14(2 年前);至今共发布 32 个版本,其中过去 12 个月发布了 0 个;首次发布于 2022/07/09。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。