Skip to content

Commit

Permalink
refactor: Refactor the method to get bot info
Browse files Browse the repository at this point in the history
  • Loading branch information
hmes98318 committed Oct 14, 2024
1 parent 6668858 commit c5cab1b
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 85 deletions.
132 changes: 61 additions & 71 deletions src/commands/status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,42 +19,8 @@ export const options = [];

export const execute = async (bot: Bot, client: Client, message: Message) => {
const botPing = `${Date.now() - message.createdTimestamp}ms`;

const [sysloadResult, pingListResult, guildsCountResult, guildsCacheResult, playerCountResult] = await Promise.allSettled([
sysusage.cpu(),
client.lavashark.nodesPing(),
client.shard?.fetchClientValues('guilds.cache.size').catch(() => [-1]),
client.shard?.fetchClientValues('guilds.cache').catch(() => [[]]),
client.shard?.fetchClientValues('lavashark.players.size').catch(() => [-1])
]);

const sysload = sysloadResult.status === 'fulfilled' ? sysloadResult.value : { percent: '0%', detail: '[0.00, 0.00, 0.00]' };
const pingList = pingListResult.status === 'fulfilled' ? pingListResult.value : [];
const totalGuildsCount = guildsCountResult.status === 'fulfilled' ?
(guildsCountResult.value as number[]).reduce((total: number, count: number) => total + count, 0) : 0;
const totalMembersCount = guildsCacheResult.status === 'fulfilled' ?
(guildsCacheResult.value as []).flat().reduce((acc, guild) => acc + (guild ? (guild as any).memberCount : 0), 0) : 0;
const totalPlayerCount = playerCountResult.status === 'fulfilled' ?
(playerCountResult.value as number[]).reduce((total: number, count: number) => total + count, 0) : 0;

console.log('guilds count: ' + totalGuildsCount, guildsCountResult.status === 'fulfilled' ? guildsCountResult.value : []);
console.log('members count: ' + totalMembersCount, guildsCacheResult.status === 'fulfilled' ? (guildsCacheResult.value as unknown as []).map((guilds: any) => guilds.reduce((acc: any, guild: any) => acc + (guild ? (guild as any).memberCount : 0), 0)) : []);
console.log('lavashark player: ' + totalPlayerCount, playerCountResult.status === 'fulfilled' ? playerCountResult.value : []);


const systemStatus: SystemStatus = {
load: sysload,
memory: sysusage.ram(),
heap: sysusage.heap(),
uptime: uptime(bot.sysInfo.startupTime),
ping: {
bot: botPing,
api: client.ws.ping
},
serverCount: totalGuildsCount,
totalMembers: totalMembersCount,
playing: totalPlayerCount
};
const sysload = await sysusage.cpu();
const pingList = await client.lavashark.nodesPing();

const nodes = client.lavashark.nodes;
const nodesStatus = [];
Expand All @@ -72,44 +38,22 @@ export const execute = async (bot: Bot, client: Client, message: Message) => {
nodesStatus.push({ name: `✅ ${node.identifier}`, value: `ping: **${ping}ms**` });
}
}
bot.logger.emit('log', bot.shardId, 'nodesStatus: ' + JSON.stringify(nodesStatus));

const nodeHealth = healthValue === 0 ? 'All nodes are active' : `⚠️ There are ${healthValue} nodes disconnected`;


return message.reply({
embeds: [
embeds.botStatus(bot.config, bot.sysInfo, systemStatus),
embeds.nodesStatus(bot.config.embedsColor, nodeHealth, nodesStatus)
],
allowedMentions: { repliedUser: false }
const results = await client.shard!.broadcastEval(async (client) => {
return {
serverCount: client.guilds.cache.size,
totalMembers: client.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0),
playing: client.lavashark.players.size
};
});
};

export const slashExecute = async (bot: Bot, client: Client, interaction: ChatInputCommandInteraction) => {
const botPing = `${Date.now() - interaction.createdTimestamp}ms`;

const [sysloadResult, pingListResult, guildsCountResult, guildsCacheResult, playerCountResult] = await Promise.allSettled([
sysusage.cpu(),
client.lavashark.nodesPing(),
client.shard?.fetchClientValues('guilds.cache.size').catch(() => [-1]),
client.shard?.fetchClientValues('guilds.cache').catch(() => [[]]),
client.shard?.fetchClientValues('lavashark.players.size').catch(() => [-1])
]);

const sysload = sysloadResult.status === 'fulfilled' ? sysloadResult.value : { percent: '0%', detail: '[0.00, 0.00, 0.00]' };
const pingList = pingListResult.status === 'fulfilled' ? pingListResult.value : [];
const totalGuildsCount = guildsCountResult.status === 'fulfilled' ?
(guildsCountResult.value as number[]).reduce((total: number, count: number) => total + count, 0) : 0;
const totalMembersCount = guildsCacheResult.status === 'fulfilled' ?
(guildsCacheResult.value as []).flat().reduce((acc, guild) => acc + (guild ? (guild as any).memberCount : 0), 0) : 0;
const totalPlayerCount = playerCountResult.status === 'fulfilled' ?
(playerCountResult.value as number[]).reduce((total: number, count: number) => total + count, 0) : 0;

console.log('guilds count: ' + totalGuildsCount, guildsCountResult.status === 'fulfilled' ? guildsCountResult.value : []);
console.log('members count: ' + totalMembersCount, guildsCacheResult.status === 'fulfilled' ? (guildsCacheResult.value as unknown as []).map((guilds: any) => guilds.reduce((acc: any, guild: any) => acc + (guild ? (guild as any).memberCount : 0), 0)) : []);
console.log('lavashark player: ' + totalPlayerCount, playerCountResult.status === 'fulfilled' ? playerCountResult.value : []);

const totalServerCount = results.reduce((acc, shard) => acc + shard.serverCount, 0);
const totalMemberCount = results.reduce((acc, shard) => acc + shard.totalMembers, 0);
const totalPlaying = results.reduce((acc, shard) => acc + shard.playing, 0);

const systemStatus: SystemStatus = {
load: sysload,
Expand All @@ -120,11 +64,28 @@ export const slashExecute = async (bot: Bot, client: Client, interaction: ChatIn
bot: botPing,
api: client.ws.ping
},
serverCount: totalGuildsCount,
totalMembers: totalMembersCount,
playing: totalPlayerCount
serverCount: totalServerCount,
totalMembers: totalMemberCount,
playing: totalPlaying
};


bot.logger.emit('log', bot.shardId, 'nodesStatus: ' + JSON.stringify(nodesStatus));

return message.reply({
embeds: [
embeds.botStatus(bot.config, bot.sysInfo, systemStatus),
embeds.nodesStatus(bot.config.embedsColor, nodeHealth, nodesStatus)
],
allowedMentions: { repliedUser: false }
});
};

export const slashExecute = async (bot: Bot, client: Client, interaction: ChatInputCommandInteraction) => {
const botPing = `${Date.now() - interaction.createdTimestamp}ms`;
const sysload = await sysusage.cpu();
const pingList = await client.lavashark.nodesPing();

const nodes = client.lavashark.nodes;
const nodesStatus = [];
let healthValue = 0;
Expand All @@ -141,11 +102,40 @@ export const slashExecute = async (bot: Bot, client: Client, interaction: ChatIn
nodesStatus.push({ name: `✅ ${node.identifier}`, value: `ping: **${ping}ms**` });
}
}
bot.logger.emit('log', bot.shardId, 'nodesStatus: ' + JSON.stringify(nodesStatus));

const nodeHealth = healthValue === 0 ? 'All nodes are active' : `⚠️ There are ${healthValue} nodes disconnected`;


const results = await client.shard!.broadcastEval(async (client) => {
return {
serverCount: client.guilds.cache.size,
totalMembers: client.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0),
playing: client.lavashark.players.size
};
});


const totalServerCount = results.reduce((acc, shard) => acc + shard.serverCount, 0);
const totalMemberCount = results.reduce((acc, shard) => acc + shard.totalMembers, 0);
const totalPlaying = results.reduce((acc, shard) => acc + shard.playing, 0);

const systemStatus: SystemStatus = {
load: sysload,
memory: sysusage.ram(),
heap: sysusage.heap(),
uptime: uptime(bot.sysInfo.startupTime),
ping: {
bot: botPing,
api: client.ws.ping
},
serverCount: totalServerCount,
totalMembers: totalMemberCount,
playing: totalPlaying
};


bot.logger.emit('log', bot.shardId, 'nodesStatus: ' + JSON.stringify(nodesStatus));

return interaction.editReply({
embeds: [
embeds.botStatus(bot.config, bot.sysInfo, systemStatus),
Expand Down
40 changes: 26 additions & 14 deletions src/lib/api/express.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,23 +260,35 @@ const registerExpressEvents = (bot: Bot, shardManager: ShardingManager, localNod
app.get('/api/info', verifyLogin, async (req, res) => {
// bot.logger.emit('api', '[GET] /api/info ' + req.ip);

const [guildsCountResult, guildsCacheResult] = await Promise.allSettled([
shardManager.fetchClientValues('guilds.cache.size').catch(() => [-1]),
shardManager.fetchClientValues('guilds.cache').catch(() => [[]]),
]);
try {
const results = await shardManager.broadcastEval(async (client) => {
return {
serverCount: client.guilds.cache.size,
totalMembers: client.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0)
};
});

const totalServerCount = results.reduce((acc, shard) => acc + shard.serverCount, 0);
const totalMemberCount = results.reduce((acc, shard) => acc + shard.totalMembers, 0);

const totalGuildsCount = guildsCountResult.status === 'fulfilled' ?
(guildsCountResult.value as number[]).reduce((total: number, count: number) => total + count, 0) : 0;
const totalMembersCount = guildsCacheResult.status === 'fulfilled' ?
(guildsCacheResult.value as []).flat().reduce((acc, guild) => acc + (guild ? (guild as any).memberCount : 0), 0) : 0;
const info = {
...bot.sysInfo,
serverCount: `${totalServerCount} [${results.map(shard => shard.serverCount).join(', ')}]`,
totalMembers: `${totalMemberCount} [${results.map(shard => shard.totalMembers).join(', ')}]`
};

res.json(info);
} catch (error) {
bot.logger.emit('api', `[${bot.shardId}] Failed to get shard info: ${error}`);

const info = {
...bot.sysInfo,
serverCount: `${totalGuildsCount} ${JSON.stringify(guildsCountResult.status === 'fulfilled' ? guildsCountResult.value : [])}`,
totalMembers: `${totalMembersCount} ${JSON.stringify(guildsCacheResult.status === 'fulfilled' ? (guildsCacheResult.value as unknown as []).map((guilds: any) => guilds.reduce((acc: any, guild: any) => acc + (guild ? (guild as any).memberCount : 0), 0)) : [])}`
};
res.json(info);
const info = {
...bot.sysInfo,
serverCount: 'error',
totalMembers: 'error'
};

res.json(info);
}
});

app.get('/api/status', verifyLogin, async (req, res) => {
Expand Down

0 comments on commit c5cab1b

Please sign in to comment.