Discord.js v14中client.application.commands.set调用报错求助
问题原因
错误Cannot read properties of null (reading 'commands')的核心原因是client.application为null。在Discord.js v14中,client.application只有当客户端完全登录并触发ready事件后才会被初始化,你当前的代码在调用client.login()之前就执行了加载斜杠命令的逻辑,此时客户端还未完成登录流程,自然无法获取到有效的application对象。
解决方案
需要将加载斜杠命令的操作放到客户端的ready事件中执行,确保客户端已经就绪。
修改步骤
- 调整handler代码,移除提前调用
loadSlashsCommand的逻辑,改为在ready事件中触发。 - 确保
loadSlashsCommand的逻辑在客户端就绪后执行。
修改后的handler代码
// 仅加载事件处理程序 require(`./handler/loadEvents`)(client); // 验证Config.json合法性 const { checkValid } = require('./Functions/Validation/checkValid') checkValid() // 登录客户端 console.log((`${new Date().getHours()}:${new Date().getMinutes()}:${new Date().getSeconds()} -`), chalk.bgBlue('Connexion à l\'API Discord en cours...')) client.login(BotToken)
添加ready事件处理(示例)
假设你的事件文件存放在Events/Client/ready.js,添加以下代码:
const chalk = require("chalk"); const loadSlashCommands = require("../../handler/loadSlashsCommand"); module.exports = { name: "ready", once: true, async execute(client) { console.log(chalk.bgGreen(`Connecté en tant que ${client.user.tag}!`)); // 客户端就绪后加载并注册斜杠命令 await loadSlashCommands(client); }, };
保持loadSlashsCommand代码不变(已适配就绪时机)
const chalk = require("chalk"); const { glob } = require("glob"); const { promisify } = require("util"); const globPromise = promisify(glob); const config = require('../Configuration/config.json') module.exports = async (client) => { const slashCommands = await globPromise(`${process.cwd()}/Commands/*/*.js`); const arrayOfSlashCommands = []; slashCommands.map((value) => { const file = require(value); if (!file?.name) return; client.slashCommands.set(file.name, file); arrayOfSlashCommands.push(file); }); // 此时client.application已初始化,可安全调用 await client.application.commands.set(arrayOfSlashCommands); console.log(chalk.bgGreen(`已注册 ${arrayOfSlashCommands.length} 个斜杠命令`)); };
额外注意事项
- 确保机器人邀请链接包含
scope=bot+applications.commands权限,否则无法注册斜杠命令。 - 全局命令注册后需要等待约1小时生效,若需即时测试,可改用服务器级命令:
client.guilds.cache.get('你的服务器ID').commands.set(arrayOfSlashCommands)。
内容的提问来源于stack exchange,提问作者Aubin PRIEUR
相关产品推荐
相关产品推荐

