[英]TypeError: client.commands.get(…).execute is not a function (discord.js 12)
[英]Keep getting error for undefined reading execute on client.commands.get in discord.js bot
我剛剛開始使用 visualstudio 和 discord.js 進行編碼(我想制作一個 discord 機器人),所以我決定學習有關它的教程。 我正在學習分配,但我的知識太少無法解決這個問題,我到處搜索但我找不到明確的答案。
這是我的代碼(或教程代碼;p):
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'ping'){
client.commands.get('ping').execute(message, args);
} else if (command === 'group'){
client.commands.get('group').execute(message, args);
}
});
這是 ping.js 文件代碼:
module.export = {
name: 'ping',
description: "This is a ping command!",
execute(message, args){
if(command === 'ping'){
message.channel.send('pong!')
}
}
}
這是我不斷收到的錯誤:
C:\Users\User\DiscordBot\index.js:33
client.commands.get('ping').execute(message, args);
^
TypeError: Cannot read properties of undefined (reading 'execute')
有誰知道如何解決這個問題? 我又是新手,所以如果答案很明顯,我提前致歉...感謝閱讀!
似乎您從未將命令添加到client.commands
,所以我建議添加一個命令處理程序。
在這個答案中,我已經解釋了如何實現命令處理程序。 看看它,它應該可以解決您當前的問題,也許還有更多的問題:)
如果 URL 在某個時間點不再可用,我也會在此處粘貼答案
在我向您展示我的命令處理程序之前,讓我們看一下您的文件夾結構應該如何:
commands
│
├──admin-commands
│ ban.js
│ kick.js
│
├──fun-commands
│ ping.js
│ meme.js
│
└──misc
test.js
(文件名只是例子)
現在您已經像這樣構造了命令文件夾,您可以將其用作命令處理程序:
const fs = require('fs');
const path = require('path');
const rootDir = path.dirname(require.main.filename);
module.exports = (client) => {
const fileArray = [];
function readCommands(dir) {
const __dirname = rootDir;
// Read out all command files
const files = fs.readdirSync(path.join(__dirname, dir));
// Loop through all the files in ./commands
for (const file of files) {
// Get the status of 'file' (is it a file or directory?)
const stat = fs.lstatSync(path.join(__dirname, dir, file));
// If the 'file' is a directory, call the 'readCommands' function
// again with the path of the subdirectory
if (stat.isDirectory()) {
readCommands(path.join(dir, file));
}
else {
const fileDir = dir.replace('\\', '/');
fileArray.push(fileDir + '/' + file);
// fs.readdirSync(dir).filter(cmdFile => cmdFile.endsWith('.js'));
}
}
}
};
我認為評論很好地解釋了這個過程。 但讓我們繼續前進!
將其粘貼到項目中后,您仍然需要調用readCommands()
function...
readCommands('commands');
for(const file of fileArray) {
const command = require(`../${file}`);
if(command.name) {
client.commands.set(command.name, command);
}
}
參數commands
是您的根命令文件夾的名稱。 因此,如果您決定給它另一個名稱,例如“commandFolder”,您需要將該名稱作為參數傳遞!
在命令處理程序代碼中,在module.exports
的正下方,我正在創建一個名為fileArray
的數組。 這將存儲上面的代碼找到的所有命令文件。 現在我們遍歷這個數組,導入命令並檢查它是否為空。
如果它不為空,我們會將此命令設置為client.commands
,這樣當您需要執行它時,您可以稍后在代碼中獲取它。
...您可以將其粘貼到與命令處理程序的“主要代碼”相同的文件中,以便兩個代碼片段都在同一個文件中。 還要確保將其粘貼到module.exports
塊的內部,而不是外部;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.