一、OpenClaw Discord 是什么

OpenClaw Discord 是一套面向 Discord 平台的机器人接入与自动化框架,它把 Discord 的 Gateway 事件流、REST API 调用和命令注册封装成统一的编程接口,让开发者可以用较少的样板代码构建功能完整的社区机器人。相比直接使用 Discord 官方 SDK,OpenClaw Discord 更强调模块化的事件处理、可插拔的命令系统和开箱即用的部署能力。

本文将从环境准备开始,逐步演示如何接入 OpenClaw Discord、注册斜杠命令、处理消息事件、构建自动化工作流,并给出可直接运行的代码示例。

阅读前提:了解 Node.js 基础语法,拥有一个 Discord 开发者账号,并已创建测试服务器。

二、核心概念与架构

在动手写代码之前,先理解 OpenClaw Discord 的几个核心概念,能显著降低后续调试成本。

概念说明典型用途
Client机器人主实例,负责维持与 Discord Gateway 的长连接全局单例,启动时创建
Command可注册的斜杠命令,包含名称、描述、参数和执行函数用户交互入口
Event Handler监听消息、成员变动、频道更新等事件自动化响应
Middleware命令执行前后的拦截层,用于鉴权、限流、日志统一治理
Adapter对接外部服务(数据库、HTTP 接口、消息队列)业务集成

整体数据流可以概括为:Discord Gateway 推送事件 → Client 分发 → Event Handler 或 Command 执行 → Adapter 调用外部服务 → 通过 REST API 回写结果。

flowchart TD
    A[Discord Gateway] --> B[OpenClaw Client]
    B --> C{事件类型}
    C -->|交互事件| D[Command 执行]
    C -->|消息事件| E[Event Handler]
    D --> F[Middleware 鉴权/限流]
    E --> F
    F --> G[Adapter 外部服务]
    G --> H[Discord REST API]
    H --> A

三、环境准备与项目初始化

首先创建项目并安装依赖。OpenClaw Discord 以 npm 包形式发布,同时需要 Discord 官方的 API 类型定义。

mkdir openclaw-discord-demo
cd openclaw-discord-demo
npm init -y
npm install openclaw-discord discord.js dotenv
npm install -D typescript ts-node @types/node

接着在 Discord 开发者门户创建应用,获取 Bot Token,并在 OAuth2 页面勾选 bot 与 applications.commands 两个作用域,把机器人邀请到测试服务器。

创建 .env 文件保存敏感配置,注意不要提交到版本库:

DISCORD_BOT_TOKEN=your_bot_token_here
DISCORD_CLIENT_ID=your_client_id_here
DISCORD_GUILD_ID=your_test_guild_id_here
LOG_LEVEL=info

再补充一个 .gitignore,避免密钥泄露:

node_modules/
dist/
.env
*.log

四、创建第一个机器人实例

下面是最小可运行的入口文件,完成 Client 初始化、事件绑定和登录流程。

import 'dotenv/config';
import { OpenClawClient } from 'openclaw-discord';

const client = new OpenClawClient({
  token: process.env.DISCORD_BOT_TOKEN!,
  intents: ['GUILDS', 'GUILD_MESSAGES', 'MESSAGE_CONTENT'],
  logLevel: (process.env.LOG_LEVEL as 'info') ?? 'info',
});

client.on('ready', (info) => {
  console.log(`机器人已上线:${info.user.tag}`);
  console.log(`已加入 ${info.guildCount} 个服务器`);
});

client.on('error', (err) => {
  console.error('客户端异常:', err.message);
});

async function bootstrap() {
  try {
    await client.login();
  } catch (err) {
    console.error('登录失败,请检查 Token 与网络:', err);
    process.exit(1);
  }
}

bootstrap();

运行 npx ts-node src/index.ts,控制台出现机器人标签即表示连接成功。若提示 Used disallowed intents,需要回到开发者门户开启 MESSAGE CONTENT INTENT。

五、注册斜杠命令

斜杠命令是用户与机器人交互的主要入口。OpenClaw Discord 提供了声明式注册方式,命令定义与执行逻辑分离,便于维护。

import { SlashCommandBuilder } from 'openclaw-discord';

export const pingCommand = new SlashCommandBuilder()
  .setName('ping')
  .setDescription('检查机器人是否在线')
  .toJSON();

export const echoCommand = new SlashCommandBuilder()
  .setName('echo')
  .setDescription('原样返回你输入的内容')
  .addStringOption((opt) =>
    opt.setName('text').setDescription('要回显的文本').setRequired(true)
  )
  .toJSON();

export const commands = [pingCommand, echoCommand];

注册命令时区分全局命令与服务器命令。开发阶段建议使用服务器命令,因为全局命令同步最长需要一小时。

import { OpenClawClient } from 'openclaw-discord';
import { commands } from './commands';

const client = new OpenClawClient({ token: process.env.DISCORD_BOT_TOKEN! });

async function registerCommands() {
  const guildId = process.env.DISCORD_GUILD_ID!;
  const result = await client.commands.register(commands, { guildId });
  console.log(`已注册 ${result.count} 条命令到服务器 ${guildId}`);
}

registerCommands();

六、处理命令与消息事件

命令执行函数会收到一个上下文对象,包含交互信息、参数解析结果和回复方法。下面的示例演示了带参数的命令与延迟回复。

import { OpenClawClient } from 'openclaw-discord';

const client = new OpenClawClient({ token: process.env.DISCORD_BOT_TOKEN! });

client.commands.on('ping', async (ctx) => {
  const latency = ctx.client.ping;
  await ctx.reply(`Pong!当前网关延迟约 ${latency} ms`);
});

client.commands.on('echo', async (ctx) => {
  const text = ctx.options.getString('text', true);
  await ctx.reply({ content: text, allowedMentions: { parse: [] } });
});

client.on('messageCreate', async (msg) => {
  if (msg.author.bot) return;
  if (msg.content === '!help') {
    await msg.reply('可用命令:/ping、/echo');
  }
});

client.login();

注意 allowedMentions: { parse: [] } 这一行,它可以防止用户输入中的 @everyone 触发大规模提及,是社区机器人必须处理的安全细节。

七、中间件:鉴权、限流与日志

当命令数量增长后,把通用逻辑抽到中间件是必要的。OpenClaw Discord 的中间件按注册顺序执行,任一环节调用 ctx.stop() 即中断后续流程。

import { OpenClawClient } from 'openclaw-discord';

const client = new OpenClawClient({ token: process.env.DISCORD_BOT_TOKEN! });

const buckets = new Map<string, number[]>();

client.commands.use(async (ctx, next) => {
  const key = `${ctx.userId}:${ctx.commandName}`;
  const now = Date.now();
  const history = (buckets.get(key) ?? []).filter((t) => now - t < 60_000);
  if (history.length >= 5) {
    await ctx.replyEphemeral('操作过于频繁,请一分钟后再试。');
    return ctx.stop();
  }
  buckets.set(key, [...history, now]);
  await next();
});

client.commands.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  console.log(`[cmd] ${ctx.commandName} user=${ctx.userId} cost=${Date.now() - start}ms`);
});

client.commands.use(async (ctx, next) => {
  if (ctx.commandName === 'admin' && !ctx.memberPermissions.has('ManageGuild')) {
    await ctx.replyEphemeral('你没有执行该命令的权限。');
    return ctx.stop();
  }
  await next();
});

client.login();

八、实战:构建社区自动化工作流

下面把前面的能力组合成一个真实场景:新成员入群自动发送欢迎语并分配身份组,同时提供命令查询服务器统计信息。

import { OpenClawClient, SlashCommandBuilder } from 'openclaw-discord';

const client = new OpenClawClient({
  token: process.env.DISCORD_BOT_TOKEN!,
  intents: ['GUILDS', 'GUILD_MEMBERS', 'GUILD_MESSAGES'],
});

const statsCommand = new SlashCommandBuilder()
  .setName('stats')
  .setDescription('查看服务器统计信息')
  .toJSON();

client.on('guildMemberAdd', async (member) => {
  const welcomeChannel = member.guild.channels.cache.find(
    (ch) => ch.name === 'welcome' && ch.isTextBased()
  );
  if (welcomeChannel) {
    await welcomeChannel.send(
      `欢迎 ${member.user.username} 加入!请先阅读 #rules 频道。`
    );
  }
  const role = member.guild.roles.cache.find((r) => r.name === 'Member');
  if (role) await member.roles.add(role);
});

client.commands.on('stats', async (ctx) => {
  const guild = ctx.guild;
  const online = guild.members.cache.filter((m) => m.presence?.status !== 'offline').size;
  await ctx.reply(
    `成员总数:${guild.memberCount}\n在线成员:${online}\n频道数量:${guild.channels.cache.size}`
  );
});

client.commands.register([statsCommand], { guildId: process.env.DISCORD_GUILD_ID! });
client.login();

这里需要注意 GUILD_MEMBERS 属于特权意图,需要在开发者门户单独申请。另外 presence 字段依赖 GUILD_PRESENCES 意图,若未开启则在线人数会统计为 0。

九、错误处理与优雅退出

生产环境中,机器人需要处理网络抖动、Token 失效和进程信号。下面的封装可以避免进程在异常时静默退出。

import { OpenClawClient } from 'openclaw-discord';

const client = new OpenClawClient({ token: process.env.DISCORD_BOT_TOKEN! });

client.on('shardDisconnect', (info) => {
  console.warn(`分片 ${info.shardId} 断开,原因:${info.code}`);
});

client.on('shardReconnecting', (info) => {
  console.info(`分片 ${info.shardId} 正在重连`);
});

process.on('unhandledRejection', (reason) => {
  console.error('未处理的 Promise 拒绝:', reason);
});

async function shutdown(signal: string) {
  console.log(`收到 ${signal},开始关闭机器人`);
  await client.destroy();
  process.exit(0);
}

process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGTERM', () => shutdown('SIGTERM'));

client.login();

十、部署与最佳实践

部署时建议使用容器化方案,把 Token 通过环境变量注入,而不是写进镜像。

FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY dist ./dist
ENV NODE_ENV=production
CMD ["node", "dist/index.js"]

结合实践,总结几条值得长期坚持的规范:

  • 命令注册与执行分离:命令定义集中管理,执行逻辑按模块拆分,便于测试。
  • 默认使用临时回复:对错误提示、权限不足等场景使用 replyEphemeral,避免刷屏。
  • 关闭不必要的提及解析:所有回显用户输入的地方都要设置 allowedMentions。
  • 限流前置:把限流放在中间件最前面,避免恶意调用打到业务逻辑。
  • 日志结构化:记录命令名、用户 ID、耗时,便于后续排查与审计。
  • 最小权限原则:只申请实际需要的意图与作用域,降低安全风险。

十一、总结

本文从环境准备出发,依次演示了 OpenClaw Discord 的客户端初始化、斜杠命令注册、事件处理、中间件治理、自动化工作流构建以及部署与错误处理。核心思路是把 Discord 的事件流抽象为可组合的模块,让命令、事件和外部服务集成各自独立演进。

建议读者先跑通最小示例,再逐步引入中间件与自动化逻辑,最后结合真实社区运营需求迭代功能。掌握这套结构后,扩展到投票、审核、数据看板等场景都会非常顺畅。

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐