Discord机器人没有上线



我最近制作了一个discord bot,但它不会上线,没有任何错误,也解释了为什么这是我的代码。

const TOKEN = "MyBotsToken";
const fs = require('fs')
const Discord = require('discord.js');
const Client = require('./client/Client');
const {
prefix,
token,
} = require('./config.json');
const client = new 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);
}
console.log(client.commands);
client.once('ready', () => {
console.log('Ready!');
});
client.once('reconnecting', () => {
console.log('Reconnecting!');
});
client.once('disconnect', () => {
console.log('Disconnect!');
});
client.on('message', async message => {
const args = message.content.slice(prefix.length).split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName);
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
try {
if(commandName == "ban" || commandName == "userinfo") {
command.execute(message, client);
} else {
command.execute(message);
}
} catch (error) {
console.error(error);
message.reply('There was an error trying to execute that command!');
}
console.log("bot is ready for use")
bot.login(MyBotsToken);
});

我的机器人也在使用node.js和javascript。我还尝试过cmd中的node index.js。没有别的没有别的没有别的没有别的没有别的没有别的没有别的没有别的没有别的没有别的没有别的没有别的没有别的没有别的没有其他

谢谢Extremepro999

这里的问题是login操作在onMessage事件中。

这意味着它只会在你的机器人检测到消息时使用。由于它不会上线,它无法检测到消息等等…

好消息是,只需将bot.login(MyBotsToken);放在onReady事件之外,就可以解决此问题。您还需要在客户端对象上使用.login()

所以它应该是这样的。

client.on('message', message => {
// your code
})
client.login(MyBotsToken);

bot.login(MyBotsToken)应在client.on('message', async message => {});之外