当提到我的机器人时,我希望它执行特定的命令。 但是,当提到它时,它会抛出一个错误,我将在我的代码之后粘贴该错误。
P.S:我使用命令处理程序。 P.S 2:这个机器人托管在 repl.it
我的 index.js 代码:
const fs = require('fs');
const Discord = require('discord.js');
const hosting = require('./hosting.js');
const client = new Discord.Client();
const token = process.env.botToken;
const {prefix} = require('./config.json');
module.exports = client
client.commands = new Discord.Collection();
const commandFolders = fs.readdirSync('./commands');
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${folder}/${file}`);
client.commands.set(command.name, command);
}
}
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
client.user.setPresence({activity: {name: '!1help', type: 'LISTENING'}, status: 'idle'});
console.log("Bot is running.");
console.log(client.user.username);
});
const escapeRegex = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
client.on('message', message => {
const prefixRegex = new RegExp(`^(<@!?${client.user.id}>|${escapeRegex(prefix)})\\s*`);
if (!prefixRegex.test(message.content)) return;
const [, matchedPrefix] = message.content.match(prefixRegex);
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
if (message.content === "<@833376214609690674>" || message.content === "<@!833376214609690674>") {
const mCommand = client.commands.get('help')
mCommand.execute()
}
if (!client.commands.has(commandName)) return;
const command = client.commands.get(commandName);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('There was an error trying to execute that command.');
}
})
client.login(token);
我的 help.js 代码(这是我希望我的机器人在被提及时执行的命令):
const { prefix } = require('../../config.json');
module.exports = {
name: 'help',
category: "utility",
description: 'Lists all available commands or info about a specific command.',
usage: '[command name]',
execute(message, args) {
const data = [];
const { commands } = message.client
if (!args.length) {
data.push("Here's a list of all my commands:");
data.push(commands.map(command => command.name).join(', '));
data.push("\nYou can use `{prefix}help [command name]` to get info on a specific command!");
return message.author.send(data, { split: true })
.then(() => {
if (message.channel.type === 'dm') return;
message.reply("I've sent you a DM with all my commands!");
})
.catch(error => {
console.error(`Could not send help DM to ${message.author.tag}.\n`, error);
message.reply("It seems like I can't DM you! Do you have DMs disabled? If so, please enable them.");
});
}
const name = args[0].toLowerCase();
const command = commands.get(name) || commands.find(c => c.aliases && c.aliases.includes(name));
if (!command) {
return message.reply("That's not a valid command!");
}
data.push(`**Name:** ${command.name}`);
if (command.aliases) data.push(`**Aliases:** ${command.aliases.join(', ')}`);
if (command.category) data.push(`**category:** ${command.category}`)
if (command.description) data.push(`**Description:** ${command.description}`);
if (command.usage) data.push(`**Usage:** ${prefix}${command.name} ${command.usage}`);
if (command.cooldown === undefined) {
data.push(`**Cooldown:** 0 seconds`)
}
else if (command.cooldown === 1) {
data.push(`**Cooldown:** ${command.cooldown} second`)
}
else {
data.push(`**Cooldown:** ${command.cooldown} seconds`)
}
message.channel.send(data, { split: true });
},
};
help.js 文件的路径:
./commands/utility/help.js
在 Discord 上提到机器人时,我在控制台中收到错误:
node v12.16.1
/home/runner/MultiBot/commands/utility/help.js:10
const { commands } = message.client
^
TypeError: Cannot read property 'client' of undefined
at Object.execute (/home/runner/MultiBot/commands/utility/help.js:10:30)
at Client.<anonymous> (/home/runner/MultiBot/index.js:60:12)
at Client.emit (events.js:314:20)
at Client.EventEmitter.emit (domain.js:483:12)
at MessageCreateAction.handle (/home/runner/MultiBot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/MultiBot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/MultiBot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/home/runner/MultiBot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/home/runner/MultiBot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/home/runner/MultiBot/node_modules/ws/lib/event-target.js:132:16)
答案 0 :(得分:0)
execute(message, args) {
我需要在 index.js 的 if 函数中以这种方式传入 execute 和 args:
if (message.content === "<@833376214609690674>" || message.content === "<@!833376214609690674>") {
const mCommand = client.commands.get('help')
mCommand.execute(**message, args**)
}
答案 1 :(得分:0)
比较您的命令处理程序和您自己的代码以在提及时激活
您的提及功能
mCommand.execute()
原始命令处理程序
command.execute(message, args);
如您所见,这两者之间的区别在于您在命令处理程序函数中的传递 message, args
而不是 mCommand.execute()
由于您没有传递任何参数,因此您无法从 help.js
但是您尝试访问它们 execute(message, args) {
并且没有传递任何内容 message
是未定义的(args 也是未定义的)
简单的修复如下
mCommand.execute()
=> mCommand.execute(message, args)
ps:你应该学习 javascript,它会对你的未来有所帮助