Skip to content

Commit

Permalink
feat(stats): shard stats
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-737 committed Nov 19, 2023
1 parent bb1fc12 commit db42bda
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 42 deletions.
31 changes: 17 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ This repo contains the source code for the InterChat Discord bot. InterChat is a
3. [MongoDB](https://www.mongodb.com/try/download/community)
4. [NPM](https://www.npmjs.com/get-npm) or [Yarn](https://yarnpkg.com/getting-started/install) (we are using npm in this guide)
5. [An Imgur API Key](https://api.imgur.com/oauth2/addclient) (optional, for setting hub icon and banner)
6. [Python 3.8+](https://www.python.org/downloads/) & [Visual Studio Build Tools (Windows Only)](https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019) (optional, for the API)
* > [!NOTE]
> If you are on Windows, you will need to delete the `api/package-lock.json` before installing dependencies. And if that doesn't work, run `npm i` in a terminal with admin privileges. And if you're getting errors related to node-gyp, install `node-gyp` globally using `npm i -g node-gyp`. Or follow the [Installation Instructions](https://github.com/nodejs/node-gyp?tab=readme-ov-file#on-windows). Honestly, why are you on Windows? Anyway, you can also re-install Node.js and tick the "Automatically install the necessary tools" option, which should do all the stuff mentioned above for you.
### Setting up the bot

Expand Down Expand Up @@ -89,11 +92,11 @@ public async handleComponents(interaction: MessageComponentInteraction) {

## Other information

- Events are located in `src/InterChat.ts`.
- Commands are loaded automatically by calling the `loadCommandFiles` method from `src/managers/CommandManager.ts` during the bot startup.
- The `src/commands/BaseCommand.ts` file contains all the methods/properties that can be used in a command.
- We use the `interactionCreate` event for handling **all** interactions instead of using collectors.
- If you are using your own bot for testing, make sure to change the CLIENT_ID in `src/utils/Constants.ts` like so:
* Events are located in `src/InterChat.ts`.
* Commands are loaded automatically by calling the `loadCommandFiles` method from `src/managers/CommandManager.ts` during the bot startup.
* The `src/commands/BaseCommand.ts` file contains all the methods/properties that can be used in a command.
* We use the `interactionCreate` event for handling **all** interactions instead of using collectors.
* If you are using your own bot for testing, make sure to change the CLIENT_ID in `src/utils/Constants.ts` like so:

```ts
export const CLIENT_ID = isDevBuild ? '<new_client_id_here>' : '769921109209907241';
Expand All @@ -120,19 +123,19 @@ Use semantic commit messages in your commit messages as it will make auto-releas

[Examples](https://gist.github.com/joshbuchea/6f47e86d2510bce28f8e7f42ae84c716):

- `feat`: (new feature for the user, not a new feature for build script)
* `feat`: (new feature for the user, not a new feature for build script)

- `fix`: (bug fix for the user, not a fix to a build script)
* `fix`: (bug fix for the user, not a fix to a build script)

- `docs`: (changes to the documentation)
* `docs`: (changes to the documentation)

- `style`: (formatting, missing semi colons, etc; no production code change)
* `style`: (formatting, missing semi colons, etc; no production code change)

- `refactor`: (refactoring production code, eg. renaming a variable)
* `refactor`: (refactoring production code, eg. renaming a variable)

- `test`: (adding missing tests, refactoring tests; no production code change)
* `test`: (adding missing tests, refactoring tests; no production code change)

- `chore`: (updating grunt tasks etc; no production code change)
* `chore`: (updating grunt tasks etc; no production code change)

To make our lives easier by not having to remember the commit messages at all times, this repository is [commitizen](https://www.npmjs.com/package/commitizen) friendly! Commitizen is a commandline tool that guides you through the process of choosing your desired commit type.

Expand All @@ -145,6 +148,6 @@ Run `git cz` or `cz commit` to commit using commitizen.

## Achievements & Goals

- [x] 1000 servers using InterChat 🎉
* [x] 1000 servers using InterChat 🎉

- [ ] 101 votes on topgg in a month
* [ ] 101 votes on topgg in a month
16 changes: 9 additions & 7 deletions src/SuperClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import 'dotenv/config';
export default abstract class SuperClient extends Client {
readonly logger = Logger;

readonly description = 'The only cross-server communication bot you\'ll ever need.';
readonly description = 'The only cross-server chatting bot you\'ll ever need.';
readonly version = process.env.npm_package_version ?? 'Unknown';
readonly commands = commandsMap;
readonly interactions = interactionsMap;
Expand Down Expand Up @@ -57,7 +57,7 @@ export default abstract class SuperClient extends Client {
...Options.DefaultSweeperSettings,
messages: {
interval: 3600, // Every hour...
lifetime: 1800, // Remove messages older than 30 minutes.
lifetime: 1800, // Remove messages older than 30 minutes.
},
reactions: {
interval: 3600, // Every hour...
Expand All @@ -74,11 +74,13 @@ export default abstract class SuperClient extends Client {
],
presence: {
status: 'idle',
activities: [{
state: 'Watching over 400+ networks | /hub browse',
name: 'custom',
type: ActivityType.Custom,
}],
activities: [
{
state: 'Watching over 400+ networks | /hub browse',
name: 'custom',
type: ActivityType.Custom,
},
],
},
});
}
Expand Down
74 changes: 55 additions & 19 deletions src/commands/slash/Information/stats.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
ActionRowBuilder,
ButtonBuilder,
ButtonInteraction,
ButtonStyle,
ChatInputCommandInteraction,
EmbedBuilder,
Expand All @@ -9,9 +10,11 @@ import {
import db from '../../../utils/Db.js';
import BaseCommand from '../../BaseCommand.js';
import { cpus, totalmem } from 'os';
import { LINKS, colors, isDevBuild } from '../../../utils/Constants.js';
import { LINKS, colors, emojis, isDevBuild } from '../../../utils/Constants.js';
import { msToReadable } from '../../../utils/Utils.js';
import { stripIndents } from 'common-tags';
import { CustomID } from '../../../utils/CustomID.js';
import { RegisterInteractionHandler } from '../../../decorators/Interaction.js';

export default class Stats extends BaseCommand {
readonly data = {
Expand All @@ -27,9 +30,7 @@ export default class Stats extends BaseCommand {
const totalHubs = await hubs?.count();
const totalNetworkMessages = await messageData.count();

const count = (await interaction.client.cluster.fetchClientValues(
'guilds.cache.size',
)) as number[];
const count: number[] = await interaction.client.cluster.fetchClientValues('guilds.cache.size');
const guildCount = count.reduce((p, n) => p + n, 0);

const uptime = msToReadable(interaction.client.uptime);
Expand Down Expand Up @@ -64,14 +65,6 @@ export default class Stats extends BaseCommand {
inline: true,
},
{ name: '\u200B', value: '\u200B', inline: true },
{
name: 'Shard Stats',
value: stripIndents`
- ID: 1
- State: ${interaction.guild ? Status[interaction.guild.shard.status] : 'Disconnected'}
- Ping: \`${interaction.guild?.shard.ping}ms\``,
inline: true,
},
{
name: 'Hub Stats',
value: stripIndents`
Expand All @@ -85,22 +78,65 @@ export default class Stats extends BaseCommand {
]);

const linksRow = new ActionRowBuilder<ButtonBuilder>().addComponents(
new ButtonBuilder().setLabel('Guide').setStyle(ButtonStyle.Link).setURL(docsLink),
new ButtonBuilder()
.setLabel('Support Server')
.setLabel('Guide')
.setStyle(ButtonStyle.Link)
.setURL(LINKS.SUPPORT_INVITE),
.setEmoji(emojis.docs_icon)
.setURL(docsLink),
new ButtonBuilder()
.setLabel('Support')
.setStyle(ButtonStyle.Link)
.setLabel('Vote!')
.setEmoji('🗳️')
.setURL('https://top.gg/bot/769921109209907241/vote'),
.setEmoji(emojis.code_icon)
.setURL(LINKS.SUPPORT_INVITE),
new ButtonBuilder()
.setLabel('Invite')
.setStyle(ButtonStyle.Link)
.setEmoji(emojis.add_icon)
.setURL(`https://discord.com/application-directory/${interaction.client.user?.id}`),
);
const otherBtns = new ActionRowBuilder<ButtonBuilder>().addComponents(
new ButtonBuilder()
.setLabel('Shard Stats')
.setStyle(ButtonStyle.Secondary)
.setEmoji(emojis.crystal)
.setCustomId(new CustomID().setIdentifier('stats', 'shardStats').toString()),
);

await interaction.editReply({ embeds: [embed], components: [linksRow, otherBtns] });
}

@RegisterInteractionHandler('stats')
async handleComponents(interaction: ButtonInteraction) {
const customId = CustomID.parseCustomId(interaction.customId);

if (customId.postfix === 'shardStats') {
const embed = new EmbedBuilder()
.setColor(colors.invisible)
.setDescription(
stripIndents`
### Shard Stats
**Total Shards:** ${interaction.client.cluster.info.TOTAL_SHARDS}
`,
)
.setFields(
interaction.client.ws.shards.map((shard) => ({
name: `Shard #${shard.id}`,
value: stripIndents`
\`\`\`elm
Status: ${Status[shard.status]}
Uptime: ${msToReadable(shard.manager.client.uptime || 0)}
Ping: ${shard.ping}ms
\`\`\`
`,
inline: true,
})),
)
.setFooter({
text: `InterChat v${interaction.client.version}${isDevBuild ? '+dev' : ''}`,
iconURL: interaction.client.user.displayAvatarURL(),
});

await interaction.editReply({ embeds: [embed], components: [linksRow] });
await interaction.reply({ embeds: [embed], ephemeral: true });
}
}
}
2 changes: 1 addition & 1 deletion src/decorators/Interaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export type InteractionFunction = (
/** Decorator function to call a specified method when an interaction is created (ie. interactionCreate event) */
export function RegisterInteractionHandler(customId: string): MethodDecorator {
return function(
targetClass: Record<string, any>,
targetClass,
propertyKey: string | symbol,
descriptor: PropertyDescriptor,
) {
Expand Down
3 changes: 2 additions & 1 deletion src/utils/JSON/emojis.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
"link": "<:link:1032318209879179295>",
"timeout": "<:timeout:1088474245908152461>",
"wave_anim": "<a:wave_anim:1175380399950667858>",
"crystal": "<:crystal:1175819837281403040>",

"star": "<:ic_star:1166196600666857472>",
"star_empty": "<:ic_star_tr:1166196596887793704>",
Expand All @@ -79,7 +80,7 @@
"guide_icon": "<:ic_guide:1175389757900075159>",
"rules_icon": "<:ic_rules:1175390753028046931> ",
"code_icon": "<:ic_code:1175391599539269673> ",
"add_icon": "<:ic_add:1175392519589212280> "
"add_icon": "<:ic_add:1175392519589212280>"
},

"mascot": {
Expand Down

0 comments on commit db42bda

Please sign in to comment.