繁体   English   中英

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

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

当提到我的机器人时,我希望它执行特定的命令。 但是,当它被提及时,它会引发一个错误,我将在我的代码之后粘贴该错误。

PS:我使用命令处理程序。 PS 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)
execute(message, args) {

我需要在 index.js 中的 if function 中以这种方式传递执行和参数:

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

比较您的命令处理程序和您自己的代码以在提及时激活

你提到 function

mCommand.execute()

原始命令处理程序

command.execute(message, args);

如您所见,这两者之间的区别是您的传递message, argsmCommand.execute()中没有

由于您没有传递任何参数,因此您无法从 help.js 中的help.js获得任何信息

但是您尝试访问它们execute(message, args) {

并且由于没有传递任何message ,因此未定义(args 也未定义)

简单的修复将在下面

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

ps:你应该学习javascript,它会帮助你的未来

暂无
暂无

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

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