slo*_*ful 4 javascript node.js discord.js
我已经开始使用 Discord.js 库在 Node.js 中创建一个 Discord 机器人。但是,所有代码都包含在单个索引文件中。
如何将命令和事件分别组织到单独的文件中,并在需要时运行它们?
slo*_*ful 11
为您的机器人组织代码的一种极好的、干净的方法是使用事件和命令处理程序。
您从一个小的索引文件开始,以初始化客户端和其余代码。事件处理程序保存每个事件的文件,并在事件发出时调用它们。然后,在您的客户message事件中,您可以通过运行预期命令文件中的代码来避免长if链和switch/case完全避免。
您需要了解的基本 Node.js 结构是一个module.
[模块是]您希望包含在应用程序中的一组函数。
因此,可以将模块视为包含代码片段的整齐贴合的盒子。你可以把包裹带到某个地方,打开它,然后拆开碎片。在 JavaScript 术语中,您可以在程序中的其他地方使用该模块,并使用其中包含的代码。模块可以包含您需要在代码的不同位置使用的变量、类、函数等。
现在您知道模块是什么,您必须了解如何使用它们。
出于处理程序的目的,您将只使用对象的exports属性module。通过require()用于模块,module.exports返回。考虑以下设置。
Question.js
class Question {
constructor(author, details) {
this.author = author;
this.details = details;
this.answers = [];
}
}
module.exports = Question;
Run Code Online (Sandbox Code Playgroud)
newQuestion.js
const Question = require('./Question.js');
const myQuestion = new Question('me', 'How to code event/command handlers?');
Run Code Online (Sandbox Code Playgroud)
在 中Question.js,创建了一个新类 Question 并将其分配给module.exports。然后,whenQuestion.js需要 in newQuestion.js,Question被声明为导出的类。它可以像往常一样使用。
现在,例如,如果您需要导出多个类...
Posts.js
class Question {...}
class Answer {...}
module.exports = { Question, Answer };
// Alternatively...
// module.exports.Question = Question;
// module.exports.Answer = Answer;
Run Code Online (Sandbox Code Playgroud)
newQuestion.js
const { Question } = require('./Posts.js');
const myQuestion = new Question(...);
Run Code Online (Sandbox Code Playgroud)
这样,module.exports被定义为一个对象,包含创建的类。这意味着require()它将返回一个对象,因此您可以从对象中解构所需的类。
您应该首先为您的活动创建一个文件夹,然后为每个活动创建一个文件。根据事件名称命名文件。例如,对于您客户的message事件,文件应命名为message.js.
实现您现在对模块的了解,您可以对事件文件进行编码。例如...
message.js
module.exports = (client, message) => {
// This code will be executed when
// the 'message' event is emitted.
};
Run Code Online (Sandbox Code Playgroud)
要制作实际的处理程序,您可以将以下代码放在一个函数中以加载事件...
const requireAll = require('require-all'); // Don't forget to install!
const files = requireAll({ // Require all the files within your
dirname: `${__dirname}/events`, // event directory which have a name
filter: /^(?!-)(.+)\.js$/ // ending in '.js' NOT starting
}); // with '-' (a way to disable files).
client.removeAllListeners(); // Prevent duplicate listeners on reload.
// CAUTION: THIS REMOVES LISTENERS
// ATTACHED BY DISCORD.JS!
for (const name in files) { // Iterate through the files object
const event = files[name]; // and attach listeners to each
// event, passing 'client' as the
client.on(name, event.bind(null, client)); // first parameter, and the rest
// of the expected parameters
console.log(`Event loaded: ${name}`); // afterwards. Then, log the
} // successful load to the console.
Run Code Online (Sandbox Code Playgroud)
现在,当您的客户端发出您拥有文件的事件之一时,其中的代码就会运行。
就像事件处理程序一样,您应该首先为您的命令创建一个单独的文件夹,然后为每个单独的命令创建文件。
您可以导出一个“运行”函数和一个配置对象,而不是只导出一个函数。
help.js
module.exports.run = async (client, message, args) => {
// This code will be executed to
// run the 'help' command.
};
module.exports.config = {
name: 'help',
aliases: ['h'] // Even if you don't want an alias, leave this as an array.
};
Run Code Online (Sandbox Code Playgroud)
就像事件处理程序一样,将此代码放在一个函数中以加载命令......
const requireAll = require('require-all'); // Using the same npm module...
const files = requireAll({ // Require all the files within your
dirname: `${__dirname}/commands`, // command directory which have a name
filter: /^(?!-)(.+)\.js$/ // ending in '.js' NOT starting
}); // with '-' (a way to disable files).
client.commands = new Map(); // Create new Maps for the corresponding
client.aliases = new Map(); // command names/commands, and aliases.
for (const name in files) { // Iterate through the files object
const cmd = files[name]; // and set up the 'commands' and
// 'aliases' Maps. Then, log the
client.commands.set(cmd.config.name, cmd); // successful load to the console.
for (const a of cmd.config.aliases) client.aliases.set(a, cmd.config.name);
console.log(`Command loaded: ${cmd.config.name}`);
}
Run Code Online (Sandbox Code Playgroud)
在客户的message事件中,您可以使用以下代码来运行命令...
const prefix = '!'; // Example
const [cmd, ...args] = message.content.trim().slice(prefix.length).split(/\s+/g);
const command = client.commands.get(cmd) || client.commands.get(client.aliases.get(cmd));
if (command) {
command.run(client, message, args);
console.log(`Executing ${command.config.name} command for ${message.author.tag}.`);
}
Run Code Online (Sandbox Code Playgroud)
如果我有一个与数据库相关的变量或其他需要传递事件/命令的变量怎么办?
对于事件,您可以在 中传递变量event.on(...),如下所示client。然后在您的实际事件中,您的函数必须在client.
对于命令,您可以在message事件中调用它时将变量传递给 run 函数。同样,在您的函数中,您需要包含正确放置的参数。
如果我想在子文件夹中包含命令/事件怎么办?
查看此答案以递归搜索。
如何将这些处理程序用于重新加载命令?
如果将它们的代码放在函数内,则可以设置调用这些函数的“重新加载”命令,再次加载事件和命令。
client.removeAllListeners()将删除附加到客户端的所有侦听器,包括那些源自客户端实例化的侦听器。这可能会导致语音连接相关的错误,特别Voice connection not established within 15 seconds是被抛出。为防止出现此问题,请跟踪每个侦听器函数并使用client.removeListener(listener).| 归档时间: |
|
| 查看次数: |
8804 次 |
| 最近记录: |