# @discord-interactions/core 中文文档

规范地址：https://npmcn.com/package/%40discord-interactions/core/

版本：0\.3\.23
npm 元数据更新时间：2024-09-13T18:27:37.476Z
中文译文更新时间：2026-11-12T12:22:49.862Z
软件包许可：未声明

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40discord-interactions/core
原文对照：https://npmcn.com/package/%40discord-interactions/core/?lang=original

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：193 kB，156 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=16
- 运行依赖：6 个
- 首次发布：2022-07-08T21:58:28.189Z
- 最新版本发布：2024-09-13T18:27:37.281Z
- 近 30 天下载量：3414（2026-10-13 至 2026-11-11，npm 官方下载统计）
- 已发布版本数：32（近 12 个月 0 个）

## 中文简介

Discord 交互的全部命令框架 .

## 安装

```sh
npm install @discord-interactions/core
```

也可以使用：`pnpm add @discord-interactions/core`、`yarn add @discord-interactions/core`、`bun add @discord-interactions/core`

## README

# @ discord-interactions/ core (英语)

[![Discord server](https://img.shields.io/discord/395423304112013334?logo=discord&logoColor=white)](https://discord.gg/BTXJmW4Bh7) [![npm version](https://img.shields.io/npm/v/@discord-interactions/core.svg?maxAge=3600)](https://www.npmjs.com/package/@discord-interactions/core) [![npm downloads](https://img.shields.io/npm/dt/@discord-interactions/core.svg?maxAge=3600)](https://www.npmjs.com/package/@discord-interactions/core) [![Tests status](https://github.com/ssMMiles/discord-interactions/actions/workflows/tests.yml/badge.svg)](https://github.com/ssMMiles/discord-interactions/actions)

_使用 Discord 相互作用的 Bots 核心框架 - [类型文件](https://github.com/ssMMiles/discord-interactions/blob/main/packages/core/docs/typedoc/modules.md)_

# 开始

一个使用框架的机器人实例 [这里](https://github.com/ssMMiles/discord-interactions/blob/main/packages/example-bot)。下面可找到额外的代码片段.

## 安装

`npm install @discord-interactions/core`

# 接收交互

我们的框架旨在与任何网络服务器合作,它只取取原始请求体和 `X-Signature-Ed25519`编号 :`X-Signature-Timestamp` 授权信头。 信头是可选的,如果您在较早的阶段处理授权,也可以被忽略.

举个例子,我们用快活:

```typescript
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);
  }
});
```

# 注册斜线命令

这将建立一个全球 `/ping` 命令。 如果一个数据已经登记,并且与所提供的数据不同,则该数据将被覆盖.

```typescript
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!");
  })
);
```

# 指挥组

指挥组、副指挥组和副指挥更复杂一点:

```typescript
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!"));
        }
      }
    }
  )
]);
```

# 关节命令

```typescript

const guild = new CommandManager(app, guildId);

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

* * *

# 命令同步

默认情况下,框架的同步模式是 `SyncMode.Enabled`。这意味着,当您注册命令时,框架将在Discord的一侧对照您的命令检查这些命令,并在必要时创建/更新这些命令.

还有两种模式:

-   `SyncMode.Strict`: 这将检查删除的命令, 从 Discord 中删除 .
    
-   `SyncMode.Disabled`: 这禁用所有自动同步 .
    

* * *

# 构成部分

组件必须以类似的方式以独特的ID来注册,为您组件创建出某种"模板". 然后可以使用 `context.createGlobalComponent()` 它将返回一个深克隆版本的组件作为构建器,允许您在使用它作为响应之前进一步修改它.

再次注册一个 ping 命令, 这次用一个按钮显示一个存储在其状态中的单词 :

```typescript
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);
      }
    )
  ];
}
```

## 名称间隔

命令接口包括可选 `components` 属性,允许您将组件与特定命令绑定。 此前缀包含命令名称的组件 ID (`<command>.<component ID>`),然后使用 `context.createComponent()`。 。 。 .

如果你不想使用命名间隔,你可以使用 `context.createGlobalComponent()` 并登记您的组件 `app.components.register()`。 。 。 .

## 状态

您可以在创建组件实例时通过任意对象, 允许您在组件中存储状态信息 `custom_id` 属性。 (以后可在 `context.state`) (中文(简体) ).

此状态保存于 `custom_id` 属性,将限制您的数据大小。 为避免这种情况,可以配置一个外部缓存,如Redis或Cloudflare的KV:

```typescript
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)
  }
});
```

```typescript
// 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 是什么？

Discord 交互的全部命令框架 \.

### 如何安装 @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 和提交记录判断。

