简体   繁体   English

我的 Discord 机器人的提及帮助命令不起作用。 有人可以帮忙吗? (Discord.js,JavaScript)

[英]My Discord bot's mention help command is not working. Can someone help out? (Discord.js, JavaScript)

When my bot is mentioned, I want it to execute a particular command.当提到我的机器人时,我希望它执行特定的命令。 However, when it is mentioned, it throws an error which I will paste below, after my code.但是,当它被提及时,它会引发一个错误,我将在我的代码之后粘贴该错误。

PS: I use a command handler. PS:我使用命令处理程序。 PS 2: This bot is hosted on repl.it PS 2:这个机器人托管在 repl.it

My index.js code:我的 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);

My help.js code (This is the command that I want my bot to execute when it is mentioned):我的 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 });
},
};

Path to help.js file: help.js 文件的路径:

./commands/utility/help.js

Error I recieved in console when bot is mentioned on Discord:当 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)
execute(message, args) {

I needed to pass in execute and args this way in the if function in index.js:我需要在 index.js 中的 if function 中以这种方式传递执行和参数:

if (message.content === "<@833376214609690674>" || message.content === "<@!833376214609690674>") {
  const mCommand = client.commands.get('help')
  mCommand.execute(**message, args**)
}

Compare your command handler and your own code to activate on mention比较您的命令处理程序和您自己的代码以在提及时激活

your mention function你提到 function

mCommand.execute()

the original command handler原始命令处理程序

command.execute(message, args);

As you see the difference between these two is your pass message, args in the command handler function but not in mCommand.execute()如您所见,这两者之间的区别是您的传递message, argsmCommand.execute()中没有

as your have no parameters passed you cant get anything from the function in help.js由于您没有传递任何参数,因此您无法从 help.js 中的help.js获得任何信息

But your trying to access them execute(message, args) {但是您尝试访问它们execute(message, args) {

and as nothing is passed message is undefined (args is also undefined)并且由于没有传递任何message ,因此未定义(args 也未定义)

Simple fix would be below简单的修复将在下面

mCommand.execute() => mCommand.execute(message, args) mCommand.execute() => mCommand.execute(message, args)

ps: your should learn javascript, its gonna help your in future ps:你应该学习javascript,它会帮助你的未来

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM