You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Discord机器人的Slash命令改为前缀式消息命令?

实现Discord机器人前缀命令(.im)的步骤

首先,确保你的Discord客户端已经启用了MessageContent intent,否则机器人无法读取用户发送的消息内容。初始化client时,intents配置里要加上GatewayIntentBits.MessageContent。

1. 抽离复用的搜索逻辑

把图片搜索和回复的核心逻辑做成独立函数,让Slash命令和前缀命令共用,避免重复代码:

// 复用的图片搜索与回复函数
async function handleImageSearch(target, query) {
  try {
    const images = await google.search(query);
    const randomIdx = Math.floor(Math.random() * images.length);
    // 根据传入的对象类型调用对应回复方法
    if (target.isCommand?.()) {
      await target.reply(images[randomIdx].url);
    } else {
      await target.reply(images[randomIdx].url);
    }
  } catch (err) {
    console.error('搜索出错:', err);
    await target.reply('搜索失败,请稍后重试');
  }
}

2. 修改原Slash命令代码

让原有的/search命令调用这个复用函数:

client.on('interactionCreate', async interaction => {
  if (!interaction.isCommand()) return;

  const { commandName } = interaction;

  if (commandName === 'search') {
    const query = interaction.options.getString('input');
    await handleImageSearch(interaction, query);
  }
});

3. 添加前缀命令监听

新增messageCreate事件处理,响应.im前缀的命令:

client.on('messageCreate', async message => {
  // 忽略机器人自身发送的消息,避免循环
  if (message.author.bot) return;
  
  const prefix = '.im';
  // 判断消息是否以指定前缀开头
  if (!message.content.startsWith(prefix)) return;

  // 提取查询关键词:去掉前缀并去除首尾空格
  const query = message.content.slice(prefix.length).trim();
  if (!query) {
    return message.reply('请输入要搜索的关键词,格式:.im 关键词');
  }

  // 调用复用函数处理搜索
  await handleImageSearch(message, query);
});

注意事项

  • 必须启用MessageContent intent,否则机器人无法读取消息内容
  • 处理消息时一定要忽略机器人自身的消息,防止出现无限循环回复的问题
  • 加入错误处理可以避免搜索失败导致机器人崩溃

内容的提问来源于stack exchange,提问作者JomSpoons

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 07:43:18