問題描述
我想通過將所有較長的內容放在另一個文件中來使我的代碼看起來干凈且易于理解.我有我的主文件(index.js):
I want to keep my code clean looking and easier to understand, by putting all the longer stuff in another file. I have my main file (index.js):
const discord = require('discord.js');
require('dotenv').config()
const token = process.env.botToken;
const prefix = "s!";
const cmds = require("./commands.js");
var client = new discord.Client();
client.on('ready', function(message) {});
client.on('message', function(message) {
if(message.author.equals(client.user) || !message.content.startsWith(prefix)) return;
var args = message.content.substring(prefix.length).split(" ");
switch (args[0].toLowerCase()) {
case "help":
cmds.help;
break;
}
});
client.login(token)
和我的其他文件夾(commands.js):
and my other folder (commands.js):
const discord = require('discord.js');
var client = new discord.Client();
module.exports = {
help: function(message) {
var embed = new discord.RichEmbed()
.addField("spyBot Commands", "If you get issues, dont be afraid to join us: http://discord.gg/3k6zGNF");
message.channel.send(embed);
}
}
我希望它發送嵌入,但是當我輸入命令時,沒有任何反應,也沒有打印任何錯誤.
I would like it to send the embed, but when I put the command in, nothing happens and no errors are printed.
推薦答案
我看到需要修復的兩個主要問題:
1:commands.js中的客戶端
2:主文件中的命令函數
I see two major things that need to be fixed:
1: the client in commands.js
2: the command function in the main file
1 - 在 commands.js 中,您創建了一個新客戶端.如果你只有這個命令,它不會導致任何問題,因為 client
沒有在你的代碼中使用,但是當你需要它時它不會起作用,因為它必須與在主文件中.您有兩種可能的解決方案:將您的客戶端設置為全局或需要主模塊.如果您的機器人不必在公共包中發布,那么您可以保存 global.client = client;
,然后在每個其他文件中作為 client
訪問它.另一種方法是從主模塊 (module.exports = {client};
) 導出客戶端,然后在 commands.js 中請求主文件 (var{client} = require("./index.js");
).
1 - In commands.js, you created a new client. If you have only this command, it won't cause any problem since client
is not used in your code, but when you'll need it that won't work since it has to be the same as in the main file. You have two possible solutions: setting your client as global or requiring the main module. If your bot doesn't have to be published in a public package then you can save global.client = client;
, and then access it as client
in every other file. The alternative is to export the client from the main module (module.exports = {client};
) and then require the main file in commands.js (var {client} = require("./index.js");
).
2 - 在 commands.js 中,您正在導出 help
function,所以當您調用它時index.js 你必須使用括號并將消息作為參數傳遞.試試這樣的:
2 - In commands.js you're exporting a help
function, so when you call it index.js you have to use parenthesis and pass the message as an argument. Try something like this:
//in the switch statement
case "help":
cmds.help(message);
break;
希望對您有所幫助,如果您還有其他問題,請告訴我.
I hope this can help you, let me know if you have any further question.
這篇關于對機器人命令使用不同的文件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!