我正在嘗試在 discord 機器人(使用 discord.js)上執行命令處理程式,但是當我啟動機器人時出現錯誤:
參考錯誤:命令未定義
這是我得到的錯誤
const discord = require('discord.js');
const intents = new discord.Intents();
const client = new discord.Client({ intents: 32767 });
const fs = require('fs');
const { readdirSync } = require('fs');
client.commands = new discord.Collection();
const commandFiles = fs.readdirSync('./comandos').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./comandos/${file}`);
client.commands.set(command.name, command);
}
let cmd = client.commands.find((c) => c.name === command || c.alias && c.alias.includes(command));
if(!cmd){
cmd.execute(client, message, args);
} else {
if(!cmd){
return;
}
}
const config = require('./config.js');
const prefix = config.prefix;
client.login(config.token);
uj5u.com熱心網友回復:
那一定是在一個messageCreate事件中:
client.on("messageCreate", message => {
const [ command, ...args ] = message.content.split(/ /g);
let cmd = client.commands.get(command) || client.commands.find((c) => c.alias?.includes(command));
if (cmd) { //you also made a mistake here, remove the "!"
cmd.execute(client, message, args);
}
})
uj5u.com熱心網友回復:
問題是您正在使用const來定義command回圈內部。你需要用 var 替換它,它應該可以正常作業:
const discord = require('discord.js');
const intents = new discord.Intents();
const client = new discord.Client({ intents: 32767 });
const fs = require('fs');
const { readdirSync } = require('fs');
client.commands = new discord.Collection();
const commandFiles = fs.readdirSync('./comandos').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
var command = require(`./comandos/${file}`);
client.commands.set(command.name, command);
}
let cmd = client.commands.find((c) => c.name === command || c.alias && c.alias.includes(command));
if(!cmd){
cmd.execute(client, message, args);
} else {
if(!cmd){
return;
}
}
const config = require('./config.js');
const prefix = config.prefix;
client.login(config.token);
(使用“let”也不起作用,因為它不在全域范圍內)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/371268.html
