javascript - 有人可以解释如何在本地单独的文件中包含一些命令,然后是 Discord.js 的主要 index.js 吗?
问题描述
我已经看到人们能够拥有一个 index.js 和其他定义命令的文件。一个例子:
索引.js
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '!'
//Discord Bot Token
const token = 'token here'
client.login(token);
//Checks if the bot is online
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
然后是一个单独的本地文档“commands.js”
client.on('message', msg => {
//Makes sure that the bot does not read it's own messages
if(msg.author.bot) {return;}
if(msg.content.toLowerCase() === prefix + 'test'){ //Sends the IP
msg.author.send("test!");
msg.delete();
}});
希望有人可以帮助我了解如何做到这一点。
解决方案
您可以使用模块来导入和导出文件。由于您已经在使用require
(Node 这样做的方式,因为ES 模块仍处于实验阶段)来导入 Discord.js,您可以像这样导入和导出:
module1.js
module.exports = {
a: 'Hello, world!',
b: 3
};
module2.js
const module1 = require('./module1');
console.log(module1.a); // Hello, world!
console.log(module1.b); // 3
// You can also use destructuring:
const {a, b} = require('./module1');
有关 Node.js 模块的更多信息,您可以阅读文档。
在您的情况下,我建议阅读本指南以设置命令处理程序(命令存储在单独的文件中)。一个基本的例子:
index.js
const {readdirSync} = require('fs');
const {Client, Collection} = require('discord.js');
const prefix = '!';
const client = new Client();
// Create a Collection for the commands
client.commands = new Collection(
// Get the files in the commands folder
readdirSync('./commands')
// Only keep JS files
.filter(file => file.endsWith('js')
.map(file => {
// Import the command
const command = require(`./commands/${file}`);
// When creating a collection, you can pass in an iterable (e.g. an array)
// of [key, value]
// The commands will be keyed by the command name
return [command.name, command];
})
);
client.on('message', message => {
// Exit if it was sent by a bot
if (message.author.bot) return;
// Get the arguments and command name
const args = message.content.slice(prefix.length).trim().split(/\s+/);
const command = args.shift();
// Exit if there isn't a command
if (!client.commands.has(command)) return;
// Execute the command
client.commands.get(command).execute(message, args);
});
const token = 'token here';
client.login(token);
commands/test.js
module.exports = {
name: 'test',
execute(message) {
// '!test' -> 'test'
message.channel.send('test');
}
};
commands/args.js
module.exports = {
name: 'args',
execute(message, args) {
// '!args abc 123' -> 'Arguments: abc, 123'
message.channel.send(`Arguments: ${args.join(', ')}`);
}
};
推荐阅读
- django - 权限类装饰器被忽略。“未提供身份验证凭据”响应
- sql - PostgreSQL group_concat 行作为 json
- ios - FaceID动画完成后如何准确回调?
- python-3.x - 从网页中提取 URL 链接
- java - Java getter setter 无法存储值
- amazon-cloudfront - 使用 aws cli 在 extsting 云端分发中添加额外的来源和行为
- mongodb - 快速查询MongoDB的数据结构设计
- swift - 任何人都可以帮助我如何从给定的示例中获得价值,因为我是 swift 新手
- python - pygame屏幕自动翻倍
- python - 如何在熊猫中没有 to_datetime 函数的列中格式化日期时间值?