Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

- Automatic code block detection and reformatting feature
- Full interaction handler system with file-based routing
- New `man` command for viewing Unix/Linux manual pages directly from Discord

### Changed

Expand Down
55 changes: 55 additions & 0 deletions src/commands/docs/man.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import {
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
EmbedBuilder,
} from "discord.js";
import type { CommandCallbackOpts } from "../../types/command.ts";
import { man } from "../../utils/man.ts";

export default {
name: "man",
description: "Search man pages",
aliases: ["manual"],
usage: "man <term>",
react: "📖",
async callback({ message, args }: CommandCallbackOpts) {
try {
// returns return {
// title,
// section,
// url,
// raw,
// sections,
// };
const page = await man(args.join(" "));
if (!page) {
return message.reply({
embeds: [
new EmbedBuilder()
.setTitle("Man Page Not Found")
.setDescription(
`No man page found for the term "${args.join(" ")}".`,
)
.setColor(0xff0000),
],
});
}

const embed = new EmbedBuilder()
.setTitle(`${page.title}`)
.setDescription(page.description || "No description available.")
.setColor(0x7289da);

const button = new ButtonBuilder()
.setLabel("Read Full Man Page")
.setStyle(ButtonStyle.Link)
.setURL(page.url);
const row = new ActionRowBuilder().addComponents(button);
return message.reply({ embeds: [embed], components: [row.toJSON()] });
} catch (err) {
console.error(err);
return message.reply("Failed to fetch man page.");
}
},
};
35 changes: 1 addition & 34 deletions src/commands/meta/changelog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,43 +7,10 @@ import path from "path";
import { fileURLToPath } from "url";
import type { CommandCallbackOpts } from "../../types/command.ts";
import { readFile } from "../../utils/fileOps.ts";
import { parseChangelog } from "../../utils/parseChangelog.ts";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

interface VersionSection {
title: string;
content: string;
}

function parseChangelog(content: string): VersionSection[] {
if (!content?.trim()) return [];

const parts = content.split(/^## /m);
const versions: VersionSection[] = [];

for (let i = 1; i < parts.length; i++) {
const section = parts[i]?.trim();
if (!section) continue;

const firstNewline = section.indexOf("\n");
const title = (
firstNewline === -1 ? section : section.slice(0, firstNewline)
).trim();
const body = (
firstNewline === -1 ? "" : section.slice(firstNewline)
).trim();

if (title) {
versions.push({
title,
content: `## ${title}\n\n${body}`,
});
}
}

return versions;
}

export default {
name: "changelog",
description: "See the latest changes made to the bot.",
Expand Down
36 changes: 1 addition & 35 deletions src/interactions/changelog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,44 +7,10 @@ import {
import path from "path";
import { fileURLToPath } from "url";
import { readFile } from "../utils/fileOps.ts";
import { parseChangelog } from "../utils/parseChangelog.ts";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

interface VersionSection {
title: string;
content: string;
}

function parseChangelog(content: string): VersionSection[] {
if (!content?.trim()) return [];

// Split on "## " headings (standard Keep a Changelog / conventional format)
const parts = content.split(/^## /m);
const versions: VersionSection[] = [];

for (let i = 1; i < parts.length; i++) {
const section = parts[i]?.trim();
if (!section) continue;

const firstNewline = section.indexOf("\n");
const title = (
firstNewline === -1 ? section : section.slice(0, firstNewline)
).trim();
const body = (
firstNewline === -1 ? "" : section.slice(firstNewline)
).trim();

if (title) {
versions.push({
title,
content: `## ${title}\n\n${body}`,
});
}
}

return versions;
}

export default {
id: "changelog_select",
async callback({
Expand Down
94 changes: 94 additions & 0 deletions src/utils/man.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
export interface ManPage {
title: string;
url: string;
raw: string;
description: string;
}

export async function man(term: string): Promise<ManPage | null> {
term = term.trim();

if (!/^[a-zA-Z0-9._+-]+$/.test(term)) {
throw new Error("Invalid man page.");
}

const url = `https://man.archlinux.org/man/${encodeURIComponent(term)}.txt`;

const res = await fetch(url);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fetch call has no timeout or error handling, which can cause the Discord bot to hang indefinitely if the archlinux.org server is slow or unresponsive. This could lead to resource exhaustion and bot unresponsiveness.

Confidence: 5/5

Suggested Fix
Suggested change
const res = await fetch(url);
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
try {
const res = await fetch(url, { signal: controller.signal });
clearTimeout(timeoutId);
if (!res.ok) return null;
} catch (error) {
clearTimeout(timeoutId);
if (error.name === 'AbortError') {
throw new Error("Man page request timed out.");
}
throw new Error("Failed to fetch man page.");
}

Add a 5-second timeout using AbortController to prevent indefinite hangs. Wrap the fetch in try-catch to handle network errors gracefully. This prevents the bot from becoming unresponsive when the external API is slow or down.

Prompt for AI

Copy this prompt to your AI IDE to fix this issue locally:

In src/utils/man.ts around line 17, the fetch call has no timeout or error handling which can cause the Discord bot to hang indefinitely if archlinux.org is slow or unresponsive; add an AbortController with a 5-second timeout and wrap the fetch in a try-catch block to handle network errors and timeouts gracefully, throwing appropriate error messages for timeout and fetch failures.


if (!res.ok) return null;

const raw = (await res.text()).replace(/\r\n/g, "\n").trim();

if (!raw) return null;

const firstLine = raw.split("\n")[0]?.trim();

const match = firstLine?.match(/^([^(]+)\(([^)]+)\)$/);

const sections: Record<string, string> = {};

const headings = [
"NAME",
"SYNOPSIS",
"DESCRIPTION",
"OPTIONS",
"COMMANDS",
"ARGUMENTS",
"OPERANDS",
"EXIT STATUS",
"RETURN VALUE",
"ERRORS",
"ENVIRONMENT",
"FILES",
"ATTRIBUTES",
"VERSIONS",
"STANDARDS",
"NOTES",
"BUGS",
"EXAMPLES",
"AUTHORS",
"AUTHOR",
"COPYRIGHT",
"SEE ALSO",
"HISTORY",
"DIAGNOSTICS",
"CAVEATS",
"SECURITY",
];

const lines = raw.split("\n");

let current: string | null = null;

for (const line of lines) {
const trimmed = line.trim();

if (headings.includes(trimmed)) {
current = trimmed;
sections[current] = "";
continue;
}

if (current) {
sections[current] += line + "\n";
}
}

for (const key of Object.keys(sections)) {
sections[key] = sections[key]?.trimEnd() || "";
}

const title = match?.[1]?.trim()?.toLowerCase() ?? term;
const section = match?.[2] ?? "?";
const description =
sections["DESCRIPTION"]?.split("\n\n")[0]?.replace(/\s+/g, " ").trim() ||
"";

return {
title,
description,
url,
raw,
};
}
33 changes: 33 additions & 0 deletions src/utils/parseChangelog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
interface VersionSection {
title: string;
content: string;
}

export function parseChangelog(content: string): VersionSection[] {
if (!content?.trim()) return [];

const parts = content.split(/^## /m);
const versions: VersionSection[] = [];

for (let i = 1; i < parts.length; i++) {
const section = parts[i]?.trim();
if (!section) continue;

const firstNewline = section.indexOf("\n");
const title = (
firstNewline === -1 ? section : section.slice(0, firstNewline)
).trim();
const body = (firstNewline === -1 ? "" : section.slice(firstNewline))
.trim()
.replace(/\r?\n\r?\n/g, "\n");

if (title) {
versions.push({
title,
content: `## ${title}\n\n${body}`,
});
}
}

return versions;
}
Loading