【问题标题】:Send message with command handler discord.js使用命令处理程序 discord.js 发送消息
【发布时间】:2021-06-01 14:40:18
【问题描述】:

所以我正在使用这个命令处理程序来使我的不和谐机器人更加坚固,但我完全不知道如何使用外部命令发送消息;特别定义味精。这是我的命令处理程序代码:

const Discord = require('discord.js');
const prefix = "%"
const fs = require('fs');

const client = new Discord.Client();
client.commands = new Discord.Collection();
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.on("ready", () => {
    console.log("Bot connected!")
    client.user.setPresence({
        status: 'online',
        activity: {
            name: 'Online',
            type: 'PLAYING',
            url: 'https://www.google.com/'
        }
    })
})

client.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();

    if (!client.commands.has(command)) return;

    try {
        client.commands.get(command).execute(message, args);
    } catch (error) {
        console.error(error);
        message.reply('there was an error trying to execute that command!');
    }
});

client.login("<insert my token here>")

而且我没有任何“ping.js”代码,因为我想尝试并在网上找到的所有东西都没有奏效。感谢您的帮助!

【问题讨论】:

  • 看起来您的index.js 文件已根据Discord.js 指南正确设置。您的客户端on message 事件处理程序查看每条消息并检查消息前缀,在您的情况下为%。然后代码拆分消息并检查命令名称是否与集合匹配。如果找到匹配项,则将该消息转发给相应的命令。您能否提供有关错误的更多信息或更新您的问题以包含您尝试调用的命令文件?
  • 对不起,我没有很好地说明我的问题。在“ping.js”中,味精是未定义的,我不知道如何定义它。我可以用 u 函数定义它吗?任何帮助都会得到帮助,谢谢!

标签: node.js discord discord.js


【解决方案1】:

我个人是这样做的

fs.readdir("./commands/", (err, files) => {
  if(err) console.error(error)
  let jsfiles = files.filter(f => f.split(".").pop() === "js")
  if (jsfiles.length <= 0) {
    return console.log("No commands to log in FOLDER NAME")
  }
  console.log(`Loading ${jsfiles.length} commands from FOLDER NAME...`)
  jsfiles.forEach((f,i) => {
    let props = require(`./commands/${f}`)
    console.log(`${i + 1}: ${f} loaded!`)
    client.commands.set(f, props)
  })
})

然后在client.on message

let cmd = client.commands.get(command+".js")
    if (cmd) cmd.run(bot, message, args, prefix)

ping.js 试试这个

const Discord = require("discord.js");
const client = new Discord.Client();
module.exports.run = async (client, message, args, prefix) => {
  // command code here
};
module.exports.help = {
  name: "command name",
  usage: "command usage",
};

【讨论】:

  • 感谢您的帮助,但这并不能帮助我在处理程序之外发送消息。 Ping.js 里面没有定义 msg,我也不知道怎么定义 msg。
  • 试试我添加的新位 :)
猜你喜欢
  • 2021-11-04
  • 2021-11-02
  • 2020-06-09
  • 2021-08-01
  • 2020-08-04
  • 2021-05-17
  • 2020-06-17
  • 2021-02-05
相关资源
最近更新 更多