Discord bot 不上线?

时间:2020-12-22 17:11:59

标签: javascript node.js discord

我最近制作了一个不和谐的机器人,但它不会上线,没有错误也知道为什么这是我的代码。

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

2 个答案:

答案 0 :(得分:1)

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

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

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

所以它应该是这样的。

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

client.login(MyBotsToken);

答案 1 :(得分:0)

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

之外