add bot status, fetch all users on startup

This commit is contained in:
janderedev 2022-04-09 14:38:27 +02:00
parent 7a7ffcc805
commit 026b81645f
No known key found for this signature in database
GPG key ID: 5D5E18ACB990F57A
3 changed files with 73 additions and 0 deletions

View file

@ -0,0 +1,52 @@
import axios from "axios";
import { client, dbs } from "../..";
import logger from "../logger";
(async () => {
if (!client.user) await new Promise<void>(r => client.once('ready', () => r()));
const interval = process.env['BOT_STATUS_INTERVAL']; // In seconds
const statuses = process.env['BOT_STATUS']
?.split('||')
.map(text => text.trim());
if (statuses?.length && interval) {
let i = 0;
const update = async () => {
try {
const statusText = statuses[i]
.replace('{{servers}}', `${client.servers.size}`)
.replace('{{users}}', `${client.users.size}`)
.replace('{{infractions_total}}', `${await dbs.INFRACTIONS.count({})}`)
.replace('{{ping_ms}}', `${client.websocket.ping ?? -1}`);
await setStatus(statusText, 'Online');
logger.debug(`Bot status updated`);
i++;
if (i >= statuses.length) i = 0;
} catch(e) {
console.error(`Failed to update bot status: ${e}`);
}
}
update();
setInterval(update, parseInt(interval) * 1000);
}
})();
async function setStatus(text: string, presence: 'Online'|'Idle'|'Busy'|'Invisible') {
await axios.patch(
`${client.apiURL}/users/@me`,
{
status: { text, presence }
},
{
headers: {
'x-bot-token': process.env['BOT_TOKEN']!
}
}
);
}
export { setStatus }

View file

@ -0,0 +1,19 @@
import { client } from "../..";
import logger from "../logger";
// Fetch all known users on bot startup.
(async () => {
if (!client.user) await new Promise<void>(r => client.once('ready', () => r()));
logger.info(`Starting to fetch users in ${client.servers.size} servers.`);
const promises: Promise<any>[] = [];
for (const server of client.servers) {
promises.push(server[1].fetchMembers());
}
const res = await Promise.allSettled(promises);
logger.done(`Downloaded all users from ${res.filter(r => r.status == 'fulfilled').length} servers `
+ `with ${res.filter(r => r.status == 'rejected').length} errors. Cache size: ${client.users.size}`);
})();

View file

@ -50,4 +50,6 @@ export { client, dbs }
import('./bot/modules/user_scan'); import('./bot/modules/user_scan');
import('./bot/modules/api_communication'); import('./bot/modules/api_communication');
import('./bot/modules/metrics'); import('./bot/modules/metrics');
import('./bot/modules/bot_status');
import('./bot/modules/fetch_all');
})(); })();