You need to enable JavaScript to run this app. Discord.js斜杠命令报错:无法读取undefined的mentions/guild属性如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js斜杠命令报错:无法读取undefined的mentions/guild属性如何解决

报错原因

你配置了slash: 'both',表示命令同时支持普通前缀消息触发和斜杠命令触发。当命令通过斜杠触发时,回调参数里的message对象为undefined,原代码所有直接读取message下属性的逻辑都会报错。

修复方案

你用的命令框架(WOKCommands)在both模式下会自动注入斜杠命令相关的回调参数,你只需要补全参数接收,兼容两种触发场景即可,修改后的代码如下:

const { MessageEmbed } = require('discord.js')
const mongo = require('../mongo')
const warnSchema = require('../schemas/warn-schema')

module.exports = {
  slash: 'both',
  testOnly: true,
  minArgs: 2,
  expectedArgs: '<mention> <reason>',
  // 补充参数类型声明,让框架自动解析提及用户
  expectedArgsTypes: ['USER', 'STRING'],
  description: "warns mentioned user",
  // 补全回调接收的参数:user是框架自动解析的被提及用户,guild是当前服务器对象,interaction是斜杠触发时的交互对象,member是触发命令的用户成员对象
  callback: async ({ message, args, interaction, guild, user: target, member }) => {
    const reason = message ? args.slice(1).join(' ') : interaction.options.getString('reason')

    const guildId = guild.id
    const userId = target.id
    
    const warning = {
      author: member.user.tag,
      timestamp: new Date().getTime(),
      reason,
    }

    const yerz = new MessageEmbed()
      .setTitle('yes')

    await mongo().then(async (mongoose) => {
      try {
        await warnSchema.findOneAndUpdate(
          {
            guildId,
            userId,
          },
          {
            guildId,
            $push: {
              warnings: warning,
            },
          },
          {
            upsert: true,
          }
        )
      } finally {
        mongoose.connection.close()
      }
    })

    return yerz
  },
}

修改说明

  • 新增expectedArgsTypes配置,告诉框架第一个参数是用户类型,会自动解析为用户对象注入到回调的user参数中,不需要手动从消息提及或者交互选项里读取
  • 补全回调参数,直接用框架注入的guild、member、target参数,天然兼容两种触发场景
  • 区分两种触发场景获取reason参数:普通消息触发时从args里截取,斜杠触发时从interaction选项里读取

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 04:06:07