Skip to content

Commit 6fde595

Browse files
authored
Merge pull request #12 from BenjammingKirby/master
Display bot info on bot ping
2 parents 9f9144d + de32f0c commit 6fde595

File tree

8 files changed

+122
-8
lines changed

8 files changed

+122
-8
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ A Discord bot to display documentation
55
## Currently supported docs
66

77
* discord.js (includes main/stable branch, includes djs-voice, djs-builders and djs-collection documentations)
8+
* Javascript ([mdn](https://developer.mozilla.org/))
89

910
## Docker
1011

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "tph_docs_bot",
33
"version": "1.0.0",
4-
"description": "A bot made for TPH (The Programmers Hangout - discord.gg/programming) ",
4+
"description": "A Discord bot to display documentation ",
55
"main": "dist/bot.js",
66
"scripts": {
77
"tsc": "tsc",

src/bot.ts

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,47 @@
11
import "dotenv/config";
2-
import { Client, Collection } from "discord.js";
2+
import { Client, Collection, LimitedCollection } from "discord.js";
33
import { MyContext } from "./interfaces";
44
import { loadCommands, commandHandler } from "./handlers/CommandHandler";
5+
import { messageHandler } from "./handlers/MessageHandler";
56

67
(async function () {
78
const context: MyContext = {
89
client: new Client({
9-
intents: ["GUILDS"],
10+
intents: ["GUILDS", "GUILD_MESSAGES"],
1011
presence: {
11-
activities: [{ type: "WATCHING", name: "Discord.JS channel" }],
12+
activities: [{ type: "PLAYING", name: "Read the docs" }],
1213
status: "online",
1314
},
14-
// For DMs, a partial channel object is received, in order to receive dms, CHANNEL partials must be activated
15+
// For DMs, a partial channel object is received, in order to receive dms, CHANNEL partials must be activated
1516
partials: ["CHANNEL"],
17+
makeCache: (manager) => {
18+
//! Disabling these caches will break djs funcitonality
19+
const unsupportedCaches = [
20+
"GuildManager",
21+
"ChannelManager",
22+
"GuildChannelManager",
23+
"RoleManager",
24+
"PermissionOverwriteManager",
25+
];
26+
if (unsupportedCaches.includes(manager.name)) return new Collection();
27+
// Disable every supported cache
28+
return new LimitedCollection({ maxSize: 0 });
29+
},
1630
}),
1731
commands: new Collection(),
1832
cooldownCounter: new Collection(),
1933
};
2034
const docsBot = context.client;
2135
await loadCommands(context);
36+
2237
docsBot.on("error", console.error);
2338
docsBot.on("warn", console.warn);
24-
docsBot.on("ready", (client) => {
39+
40+
docsBot.once("ready", (client) => {
2541
console.info(`Logged in as ${client.user.tag} (${client.user.id})`);
2642
});
43+
44+
docsBot.on("messageCreate", messageHandler);
2745
docsBot.on("interactionCreate", commandHandler.bind(null, context));
2846

2947
docsBot.login(process.env.TOKEN);

src/commands/docs/djs.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import { Command } from "../../interfaces";
33
import { SlashCommandBuilder } from "@discordjs/builders";
44
import Doc, { sources } from "discord.js-docs";
5-
import { checkEmbedLimits } from "../../utils/embedUtils";
5+
import { checkEmbedLimits } from "../../utils/EmbedUtils";
66

77
const supportedBranches = Object.keys(sources).map(
88
(branch) => [capitalize(branch), branch] as [string, string]

src/handlers/MessageHandler.ts

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { Formatters, MessageEmbed } from "discord.js";
2+
import type { Message } from "discord.js";
3+
import { intervalToDuration, intervalObjToStr } from "../utils/DateUtils";
4+
5+
export async function messageHandler(message: Message<true>) {
6+
try {
7+
const clientUser = message.client.user;
8+
// The regex for the bot's mention
9+
const mentionRegex = new RegExp(`^<@!?${clientUser.id}>$`);
10+
11+
if (message.content.trim().match(mentionRegex)) {
12+
const pkgJSONPath = "../../package.json";
13+
const pkgJSON = await import(pkgJSONPath);
14+
const { version, description, dependencies } = pkgJSON;
15+
16+
const uptime = intervalToDuration(Date.now() - message.client.uptime, Date.now());
17+
const statusEmbed = new MessageEmbed()
18+
.setTitle(`${clientUser.username} (v${version})`)
19+
.setURL("https://github.com/the-programmers-hangout/tph-docs-bot/")
20+
.setColor(0xd250c7)
21+
.setDescription(description)
22+
.setThumbnail(clientUser.displayAvatarURL({ dynamic: true, format: "png", size: 256 }))
23+
.addField(
24+
"Currently Supported Docs",
25+
["discord.js", "Javascript (mdn)"].map((str) => `\`${str}\``).join(", "),
26+
)
27+
.addField("Dependencies", Formatters.codeBlock("json", JSON.stringify(dependencies, undefined, 4)))
28+
.addField("Uptime", `${intervalObjToStr(uptime)}` || "Just turned on")
29+
.addField("Ping", message.client.ws.ping + "ms", true)
30+
.addField("Source", "[Github](https://github.com/the-programmers-hangout/tph-docs-bot/)", true)
31+
.addField(
32+
"Contributors",
33+
"[Link](https://github.com/the-programmers-hangout/tph-docs-bot/graphs/contributors)",
34+
true,
35+
);
36+
37+
await message.reply({ embeds: [statusEmbed] });
38+
}
39+
} catch (e) {
40+
console.error(e);
41+
}
42+
43+
return;
44+
}

src/handlers/RegisterCommands.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ const rest = new REST({ version: "9" }).setToken(token);
3939
? "Resetting"
4040
: "Reloading"
4141
} application (/) commands for ${applicationId} ${
42-
guildId ? `on guild ${guildId}` : ""
42+
["GUILD", "RESET_GUILD"].includes(registerMode) ? `on guild ${guildId}` : ""
4343
}: \n\t${commands
4444
.map((cmd) => cmd.name)
4545
.join("\n\t")}\nOn mode: "${registerMode}"`

src/utils/DateUtils.ts

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
const toSecondsConverterConstant = {
2+
month: 30 * 24 * 60 * 60,
3+
day: 24 * 60 * 60,
4+
hour: 60 * 60,
5+
minute: 60,
6+
second: 1,
7+
};
8+
type formats = keyof typeof toSecondsConverterConstant;
9+
export function intervalToDuration(start: number | Date, end: number | Date = Date.now()) {
10+
const intervalObj = {
11+
month: 0,
12+
day: 0,
13+
hour: 0,
14+
minute: 0,
15+
second: 0,
16+
};
17+
const startDate = new Date(start).getTime() / 1000;
18+
const endDate = new Date(end).getTime() / 1000;
19+
const interval = Math.round(endDate - startDate);
20+
// Months
21+
const remainingDays = intervalToFormat(interval, "month", intervalObj);
22+
// Days
23+
const remainingHours = intervalToFormat(remainingDays, "day", intervalObj);
24+
// Hours
25+
const remainingMinutes = intervalToFormat(remainingHours, "hour", intervalObj);
26+
// Minutes
27+
const remainingSeconds = intervalToFormat(remainingMinutes, "minute", intervalObj);
28+
// Seconds
29+
intervalToFormat(remainingSeconds, "second", intervalObj);
30+
31+
return intervalObj;
32+
}
33+
function intervalToFormat(int: number, format: formats, intervalObj: Record<formats, number>): number {
34+
const value = Math.floor(int / toSecondsConverterConstant[format]);
35+
const remaining = value === 0 ? int : int - value * toSecondsConverterConstant[format];
36+
intervalObj[format] = value;
37+
return remaining;
38+
}
39+
export function intervalObjToStr(int: Record<formats, number> | number | Date) {
40+
if (typeof int === "number" || int instanceof Date) int = intervalToDuration(int);
41+
42+
const formatStr = (format: formats) => {
43+
const amount = int[format];
44+
return amount ? `${amount} ${format}${amount === 1 ? "" : "s"}` : "";
45+
};
46+
return (["month", "day", "hour", "minute", "second"] as formats[]).reduce((acc, format) => {
47+
const formatted = formatStr(format);
48+
if (!acc) return formatted;
49+
return formatted ? acc + ", " + formatted : acc;
50+
}, "");
51+
}

0 commit comments

Comments
 (0)