67 lines
1.8 KiB
JavaScript
67 lines
1.8 KiB
JavaScript
const { Client, GatewayIntentBits, Partials } = require('discord.js');
|
|
require('./bigint-compat');
|
|
|
|
var bots = new Map();
|
|
var getBot = function (configNode) {
|
|
var promise = new Promise(function (resolve, reject) {
|
|
var bot = undefined;
|
|
if (bots.get(configNode) === undefined) {
|
|
bot = new Client({
|
|
shards: 'auto',
|
|
intents: [
|
|
GatewayIntentBits.Guilds,
|
|
GatewayIntentBits.GuildMembers,
|
|
GatewayIntentBits.GuildMessages,
|
|
GatewayIntentBits.GuildMessageReactions,
|
|
GatewayIntentBits.DirectMessages,
|
|
GatewayIntentBits.DirectMessageReactions,
|
|
GatewayIntentBits.MessageContent
|
|
],
|
|
partials: [
|
|
Partials.Channel,
|
|
Partials.User,
|
|
Partials.Message
|
|
]
|
|
});
|
|
bots.set(configNode, bot);
|
|
bot.token = configNode.token
|
|
bot.numReferences = (bot.numReferences || 0) + 1;
|
|
bot.login(configNode.token)
|
|
.then(() => {
|
|
return bot.application.fetch(); // Fetch the application to get the ID
|
|
})
|
|
.then((app) => {
|
|
bot.id = app.id; // Set the application ID as a property on the bot object
|
|
resolve(bot);
|
|
})
|
|
.catch((err) => {
|
|
reject(err);
|
|
});
|
|
} else {
|
|
bot = bots.get(configNode);
|
|
bot.numReferences = (bot.numReferences || 0) + 1;
|
|
resolve(bot);
|
|
}
|
|
});
|
|
return promise;
|
|
};
|
|
var closeBot = function (bot) {
|
|
bot.numReferences -= 1;
|
|
setTimeout(function () {
|
|
if (bot.numReferences === 0) {
|
|
try {
|
|
bot.destroy(); // if a bot is not connected, destroy() won't work, so let's just wrap it in a try-catch..
|
|
} catch (e) {}
|
|
for (var i of bots.entries()) {
|
|
if (i[1] === bot) {
|
|
bots.delete(i[0]);
|
|
}
|
|
}
|
|
}
|
|
}, 1000);
|
|
};
|
|
module.exports = {
|
|
getBot: getBot,
|
|
closeBot: closeBot
|
|
}
|