generated from nhcarrigan/template
feat: announce on Discourse support forum (#17)
## Summary - Adds `announceOnDiscourse` module to post announcements to the NHCarrigan Discourse support forum (category 16), tagged by announcement type - Adds `chunkContent` utility to split long announcements at paragraph/line boundaries for Discord (2000 chars), Reddit (40,000 chars), and Discourse (32,000 chars); Reddit overflows chain as nested replies, Discord as sequential messages, Discourse as sequential replies - Refactors the announcement route to run all platforms concurrently via `Promise.allSettled`, ensuring a failure on any one platform never blocks the others, with all results reported back - Fixes generation failure response from incorrect `201` to `500` ✨ This PR was created with love from Hikari~ 🌸 Reviewed-on: #17 Co-authored-by: Hikari <hikari@nhcarrigan.com> Co-committed-by: Hikari <hikari@nhcarrigan.com>
This commit was merged in pull request #17.
This commit is contained in:
@@ -4,9 +4,15 @@
|
||||
* @author Naomi Carrigan
|
||||
*/
|
||||
/* eslint-disable @typescript-eslint/naming-convention -- we are making raw API calls. */
|
||||
/* eslint-disable max-lines-per-function -- Chunked sending requires more logic. */
|
||||
/* eslint-disable max-statements -- Chunked sending requires more statements. */
|
||||
/* eslint-disable no-await-in-loop -- Sequential chunk posting requires awaiting each request. */
|
||||
|
||||
import { chunkContent } from "../utils/chunkContent.js";
|
||||
import type { AnnouncementType } from "../interfaces/announcementType.js";
|
||||
|
||||
const discordLimit = 2000;
|
||||
|
||||
const channelIds: Record<AnnouncementType, string> = {
|
||||
community: "1386105484313886820",
|
||||
company: "1422472775695728661",
|
||||
@@ -25,6 +31,7 @@ const getAnnouncementPing = (type: AnnouncementType): string => {
|
||||
|
||||
/**
|
||||
* Forwards an announcement to our Discord server.
|
||||
* Sends content in sequential messages if it exceeds the 2000 character limit.
|
||||
* @param title - The title of the announcement.
|
||||
* @param content - The main body of the announcement.
|
||||
* @param type - Whether the announcement is for a product or community.
|
||||
@@ -35,12 +42,23 @@ export const announceOnDiscord = async(
|
||||
content: string,
|
||||
type: AnnouncementType,
|
||||
): Promise<string> => {
|
||||
const channelId = channelIds[type];
|
||||
const ping = getAnnouncementPing(type);
|
||||
const firstMessagePrefix = `# ${title}\n\n`;
|
||||
const firstMessageSuffix = `\n-# ${ping}`;
|
||||
const firstChunkLimit
|
||||
= discordLimit - firstMessagePrefix.length - firstMessageSuffix.length;
|
||||
|
||||
const chunks = chunkContent(content, firstChunkLimit);
|
||||
const firstChunk = chunks[0] ?? "";
|
||||
const remainingChunks = chunks.slice(1);
|
||||
|
||||
const messageRequest = await fetch(
|
||||
`https://discord.com/api/v10/channels/${channelIds[type]}/messages`,
|
||||
`https://discord.com/api/v10/channels/${channelId}/messages`,
|
||||
{
|
||||
body: JSON.stringify({
|
||||
allowed_mentions: { parse: [ "users", "roles" ] },
|
||||
content: `# ${title}\n\n${content}\n-# ${getAnnouncementPing(type)}`,
|
||||
content: `${firstMessagePrefix}${firstChunk}${firstMessageSuffix}`,
|
||||
}),
|
||||
headers: {
|
||||
"Authorization": `Bot ${process.env.DISCORD_TOKEN ?? ""}`,
|
||||
@@ -49,16 +67,19 @@ export const announceOnDiscord = async(
|
||||
method: "POST",
|
||||
},
|
||||
);
|
||||
|
||||
if (messageRequest.status !== 200) {
|
||||
return `Failed to send message to Discord. Status: ${messageRequest.status.toString()} ${messageRequest.statusText}`;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- fetch does not accept generics.
|
||||
const message = await messageRequest.json() as { id?: string };
|
||||
if (message.id === undefined) {
|
||||
return `Failed to parse message ID, cannot crosspost. ${JSON.stringify(message)}`;
|
||||
}
|
||||
|
||||
const crosspostRequest = await fetch(
|
||||
`https://discord.com/api/v10/channels/${channelIds[type]}/messages/${message.id}/crosspost`,
|
||||
`https://discord.com/api/v10/channels/${channelId}/messages/${message.id}/crosspost`,
|
||||
{
|
||||
headers: {
|
||||
"Authorization": `Bot ${process.env.DISCORD_TOKEN ?? ""}`,
|
||||
@@ -67,8 +88,30 @@ export const announceOnDiscord = async(
|
||||
method: "POST",
|
||||
},
|
||||
);
|
||||
|
||||
if (!crosspostRequest.ok) {
|
||||
return `Failed to crosspost message to Discord. Status: ${crosspostRequest.status.toString()} ${crosspostRequest.statusText}`;
|
||||
}
|
||||
|
||||
for (const chunk of remainingChunks) {
|
||||
const chunkRequest = await fetch(
|
||||
`https://discord.com/api/v10/channels/${channelId}/messages`,
|
||||
{
|
||||
body: JSON.stringify({
|
||||
content: chunk,
|
||||
}),
|
||||
headers: {
|
||||
"Authorization": `Bot ${process.env.DISCORD_TOKEN ?? ""}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: "POST",
|
||||
},
|
||||
);
|
||||
|
||||
if (!chunkRequest.ok) {
|
||||
return `Failed to send continuation chunk to Discord. Status: ${chunkRequest.status.toString()} ${chunkRequest.statusText}`;
|
||||
}
|
||||
}
|
||||
|
||||
return "Successfully sent and published message to Discord.";
|
||||
};
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* @copyright nhcarrigan
|
||||
* @license Naomi's Public License
|
||||
* @author Naomi Carrigan
|
||||
*/
|
||||
/* eslint-disable @typescript-eslint/naming-convention -- we are making raw API calls. */
|
||||
/* eslint-disable no-await-in-loop -- Sequential chunk posting requires awaiting each request. */
|
||||
/* eslint-disable max-lines-per-function -- Chunked posting requires more logic. */
|
||||
|
||||
import { chunkContent } from "../utils/chunkContent.js";
|
||||
import type { AnnouncementType } from "../interfaces/announcementType.js";
|
||||
|
||||
const announcementCategoryId = 16;
|
||||
const discourseLimit = 32_000;
|
||||
|
||||
const tags: Record<AnnouncementType, string> = {
|
||||
community: "Community",
|
||||
company: "Company",
|
||||
products: "Products",
|
||||
};
|
||||
|
||||
/**
|
||||
* Posts an announcement to the NHCarrigan Discourse support forum.
|
||||
* Sends overflow content as sequential replies if it exceeds the 32,000 character limit.
|
||||
* @param title - The title of the announcement.
|
||||
* @param content - The main body of the announcement in markdown.
|
||||
* @param type - Whether the announcement is for a product, community, or company.
|
||||
* @returns A message indicating the success or failure of the operation.
|
||||
*/
|
||||
export const announceOnDiscourse = async(
|
||||
title: string,
|
||||
content: string,
|
||||
type: AnnouncementType,
|
||||
): Promise<string> => {
|
||||
if (process.env.FORUM_API_KEY === undefined) {
|
||||
return "Discourse API key is not set.";
|
||||
}
|
||||
|
||||
const chunks = chunkContent(content, discourseLimit);
|
||||
const firstChunk = chunks[0] ?? "";
|
||||
const remainingChunks = chunks.slice(1);
|
||||
|
||||
const response = await fetch("https://support.nhcarrigan.com/posts.json", {
|
||||
body: JSON.stringify({
|
||||
category: announcementCategoryId,
|
||||
raw: firstChunk,
|
||||
tags: [ tags[type] ],
|
||||
title: title,
|
||||
}),
|
||||
headers: {
|
||||
"Api-Key": process.env.FORUM_API_KEY,
|
||||
"Api-Username": "hikari",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return `Failed to post to Discourse. Status: ${response.status.toString()} ${response.statusText}`;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Fetch does not accept generic.
|
||||
const data = (await response.json()) as { topic_id?: number };
|
||||
|
||||
for (const chunk of remainingChunks) {
|
||||
if (data.topic_id === undefined) {
|
||||
return "Failed to retrieve Discourse topic ID for continuation posts.";
|
||||
}
|
||||
|
||||
const replyResponse = await fetch(
|
||||
"https://support.nhcarrigan.com/posts.json",
|
||||
{
|
||||
body: JSON.stringify({
|
||||
raw: chunk,
|
||||
topic_id: data.topic_id,
|
||||
}),
|
||||
headers: {
|
||||
"Api-Key": process.env.FORUM_API_KEY,
|
||||
"Api-Username": "hikari",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: "POST",
|
||||
},
|
||||
);
|
||||
|
||||
if (!replyResponse.ok) {
|
||||
return `Failed to post continuation chunk to Discourse. Status: ${replyResponse.status.toString()} ${replyResponse.statusText}`;
|
||||
}
|
||||
}
|
||||
|
||||
return "Successfully posted announcement to Discourse~! ✨";
|
||||
};
|
||||
@@ -5,9 +5,15 @@
|
||||
*/
|
||||
/* eslint-disable @typescript-eslint/naming-convention -- we are making raw API calls. */
|
||||
/* eslint-disable max-lines-per-function -- Big logic here. */
|
||||
/* eslint-disable max-statements -- Complex Reddit posting flow with many steps. */
|
||||
/* eslint-disable complexity -- Chunked reply chaining requires multiple branches. */
|
||||
/* eslint-disable no-await-in-loop -- Sequential chunk posting requires awaiting each request. */
|
||||
|
||||
import { chunkContent } from "../utils/chunkContent.js";
|
||||
import type { AnnouncementType } from "../interfaces/announcementType.js";
|
||||
|
||||
const redditLimit = 40_000;
|
||||
|
||||
const flairIds: Record<AnnouncementType, string> = {
|
||||
community: "7a01a5a6-0f29-11ef-a0c4-c6fb085f7c8f",
|
||||
company: "dd8057c0-9e30-11f0-b321-d683551dcb2b",
|
||||
@@ -16,6 +22,7 @@ const flairIds: Record<AnnouncementType, string> = {
|
||||
|
||||
/**
|
||||
* Posts an announcement to a specific subreddit as a self-post.
|
||||
* Sends overflow content as nested replies if it exceeds the 40,000 character limit.
|
||||
* @param title - The title of the announcement.
|
||||
* @param content - The main body of the announcement.
|
||||
* @param type - Whether the announcement is for a product or community.
|
||||
@@ -34,6 +41,11 @@ export const announceOnReddit = async(
|
||||
) {
|
||||
return "Reddit credentials are not set.";
|
||||
}
|
||||
|
||||
const chunks = chunkContent(content, redditLimit);
|
||||
const firstChunk = chunks[0] ?? "";
|
||||
const remainingChunks = chunks.slice(1);
|
||||
|
||||
const tokenResponse = await fetch(
|
||||
"https://www.reddit.com/api/v1/access_token",
|
||||
{
|
||||
@@ -71,7 +83,7 @@ export const announceOnReddit = async(
|
||||
flair_text: type,
|
||||
kind: "self",
|
||||
sr: "nhcarrigan",
|
||||
text: content,
|
||||
text: firstChunk,
|
||||
title: title,
|
||||
}),
|
||||
headers: {
|
||||
@@ -85,6 +97,7 @@ export const announceOnReddit = async(
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Fetch does not accept generic.
|
||||
const redditData = (await redditPost.json()) as {
|
||||
json: {
|
||||
data?: { name?: string };
|
||||
errors: Array<unknown>;
|
||||
};
|
||||
};
|
||||
@@ -95,5 +108,44 @@ export const announceOnReddit = async(
|
||||
)}`;
|
||||
}
|
||||
|
||||
let parentName = redditData.json.data?.name;
|
||||
|
||||
for (const chunk of remainingChunks) {
|
||||
if (parentName === undefined) {
|
||||
return "Failed to get Reddit post fullname for chaining replies.";
|
||||
}
|
||||
|
||||
const commentResponse = await fetch(
|
||||
"https://oauth.reddit.com/api/comment",
|
||||
{
|
||||
body: new URLSearchParams({
|
||||
api_type: "json",
|
||||
text: chunk,
|
||||
thing_id: parentName,
|
||||
}),
|
||||
headers: {
|
||||
"Authorization": `bearer ${tokenData.access_token}`,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"User-Agent": "HikariBot/1.0 by nhcarrigan",
|
||||
},
|
||||
method: "POST",
|
||||
},
|
||||
);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Fetch does not accept generic.
|
||||
const commentData = (await commentResponse.json()) as {
|
||||
json: {
|
||||
data?: { things?: Array<{ data?: { name?: string } }> };
|
||||
errors: Array<unknown>;
|
||||
};
|
||||
};
|
||||
|
||||
if (commentData.json.errors.length > 0) {
|
||||
return `Failed to post reply chunk to Reddit: ${JSON.stringify(commentData.json.errors)}`;
|
||||
}
|
||||
|
||||
parentName = commentData.json.data?.things?.[0]?.data?.name;
|
||||
}
|
||||
|
||||
return "Successfully posted announcement to Reddit~! ✨";
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user