如何在没有消息事件的情况下动态加载和执行命令(discordbot)



我希望它启动我的函数,那么现在发生的事情是,它执行函数,但它无限次地发送执行垃圾。。。data.ref中的数据是一个数字,当它与数字匹配时,它会执行该函数,但它只是偶尔。。

我能做些什么来防止这种情况发生?超时功能不起作用。。它仍然不断地向发送垃圾邮件

for (var i in config.Extra) {
if (myData.ref == config.Extra[i].ref) {

var Alert1Type = config.Extra[i].Alert1; // type of the device show
var Alert1Name = config.Extra[i].name; // Custom name show



console.log('test');
test() //starts the function


}
}
function test(){
client.on('message', message => {
client.commands.get('servertest').run(client, message); 
return 
})
}

servertest.js文件

module.exports.help = {
name: "servertest"
}
module.exports.run = async (client, message, args) => {
MY CODE }

//更新

通常我会在我的main.js中添加(server.js代码(,因为我想保持代码的整洁,所以我使用module.exports.

我完全理解如何处理一件事。。但是,如何在不使用消息事件的情况下运行我的脚本,我想在收到值后直接触发特定的servertest.js。。现在它只有在我使用的情况下才有效!服务器测试。。目标是让机器人在一个通道中通知我,根据它通过socket.on连接获得的值的变化,从我的ANPR和安全系统发送特定的结果。

它会向您的servertest命令发送垃圾邮件,因为我认为您在servertest中发送消息。由于每次发送消息时都会执行servertest,因此会导致servertest永远循环调用自己。

请在此处和此处使用discord.js指南中显示的命令处理程序

index.js(或您的输入文件(中,您应该加载所有命令:

const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
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('message', message => {
// return if the command was sent from a bot to prevent it from replying to itself
if (!message.content.startsWith(prefix) || message.author.bot) return;

// parsing the command
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (!client.commands.has(command)) return;
try {
// Find the command matching the name and execute it
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});

最新更新