ßri*_*ant 4 node.js discord.js
我正在尝试创建一个同时为不同机器人(使用不同令牌)提供服务的项目。我的猜测是,您必须记住“client.login(token)”两次。我正忙着测试这个,尚未完成,但一旦完成就会回来。
有人对在同一个项目中的同一个文件中运行多个 NodeJS 机器人实例有一些建议吗?这可能吗?非常感谢您的帮助。
我也尝试过想象这会是什么样子:
const {Client} = require('discord.js');
const bot1 = new Client();
const bot2 = new Client();
//bot1 does something
//bot2 does something
bot1.login('token1');
bot2.login('token2');
Run Code Online (Sandbox Code Playgroud)
谢谢你,有一个美好的一天。
小智 7
我可以确认这有效。这是我的代码:
const Discord = require('discord.js');
const client1 = new Discord.Client();
const client2 = new Discord.Client();
const CONFIG = require('./config.json');
client1.once('ready', () => {
console.log('Bot 1 ready.');
});
client2.once('ready', () => {
console.log('Bot 2 ready.');
});
client1.on('message', message => {
if (message.content === 'Hello!') {
message.channel.send('Hello');
console.log('Bot 1 said hello.');
}
});
client2.on('message', message => {
if (message.content === 'Hello!') {
message.channel.send('world!');
console.log('Bot 2 said hello.');
}
});
client1.login(CONFIG.token1);
client2.login(CONFIG.token2);
Run Code Online (Sandbox Code Playgroud)
这是控制台日志:
Bot 2 ready.
Bot 1 ready.
Bot 1 said hello.
Bot 2 said hello.
Run Code Online (Sandbox Code Playgroud)
有趣的是,机器人 1 还是机器人 2 首先响应有所不同,因此您可能需要考虑这一点。
事实上,这甚至适用于 3 个机器人,而且应该适用于任意数量的机器人!
const Discord = require('discord.js');
const client1 = new Discord.Client();
const client2 = new Discord.Client();
const client3 = new Discord.Client();
const CONFIG = require('./config.json');
client1.once('ready', () => {
console.log('Bot 1 ready.');
});
client2.once('ready', () => {
console.log('Bot 2 ready.');
});
client3.once('ready', () => {
console.log('Bot 3 ready.');
});
client1.on('message', message => {
if (message.content === 'Hello!') {
message.channel.send('Hello1');
console.log('Bot 1 said hello.');
}
});
client2.on('message', message => {
if (message.content === 'Hello!') {
message.channel.send('Hello2');
console.log('Bot 2 said hello.');
}
});
client3.on('message', message => {
if (message.content === 'Hello!') {
message.channel.send('Hello3');
console.log('Bot 3 said hello.');
}
});
client1.login(CONFIG.token1);
client2.login(CONFIG.token2);
client3.login(CONFIG.token3);
Run Code Online (Sandbox Code Playgroud)
这是控制台日志:
Bot 1 ready.
Bot 3 ready.
Bot 2 ready.
Bot 2 said hello.
Bot 3 said hello.
Bot 1 said hello.
Run Code Online (Sandbox Code Playgroud)
然而,对于更深入的项目,我建议(对于命令等)为两个机器人使用不同的文件,因为我认为即使您使用相同的 index.js 文件,代码也会变得混乱且难以快速阅读。
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
2834 次 |
| 最近记录: |