node.js - 使用命令处理程序 discord.js 发送消息
问题描述
所以我使用这个命令处理程序来使我的不和谐机器人更加坚固,但我完全不知道如何使用外部命令发送消息;特别定义味精。这是我的命令处理程序代码:
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”代码,因为我想尝试并在网上找到的所有东西都没有奏效。谢谢您的帮助!
解决方案
我个人是这样做的
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",
};