generated from nhcarrigan/template
Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
1fa793935f
|
|||
|
f3197245db
|
|||
|
2ebeddd890
|
|||
|
c6de6c9591
|
|||
|
d6ad6375b2
|
|||
|
10a2f3dcd5
|
|||
|
f25163096b
|
|||
|
4437047543
|
|||
| 46b285fd97 | |||
| 8e0fa8755c | |||
| 01c138ffda | |||
| beefa832a1 | |||
| 3d39b8cb21 | |||
| cce24e2d9e | |||
| 71bda44fd7 | |||
| 00e0f09647 | |||
| 3add1c2177 | |||
| 06bfc16d06 | |||
| 80aefd0482 | |||
| 75b53ec7de | |||
| 98322a9881 |
@@ -1,25 +0,0 @@
|
|||||||
# Package Manager Configuration
|
|
||||||
# Force pnpm usage - breaks npm/yarn intentionally
|
|
||||||
node-linker=pnpm
|
|
||||||
|
|
||||||
# Security: Disable all lifecycle scripts
|
|
||||||
ignore-scripts=true
|
|
||||||
enable-pre-post-scripts=false
|
|
||||||
|
|
||||||
# Security: Require packages to be 10+ days old before installation
|
|
||||||
minimum-release-age=14400
|
|
||||||
|
|
||||||
# Security: Verify package integrity hashes
|
|
||||||
verify-store-integrity=true
|
|
||||||
|
|
||||||
# Security: Enforce strict trust policies
|
|
||||||
trust-policy=strict
|
|
||||||
|
|
||||||
# Security: Strict peer dependency resolution
|
|
||||||
strict-peer-dependencies=true
|
|
||||||
|
|
||||||
# Performance: Use symlinks for node_modules
|
|
||||||
symlink=true
|
|
||||||
|
|
||||||
# Lockfile: Ensure lockfile is not modified during install
|
|
||||||
frozen-lockfile=false
|
|
||||||
+16
-11
@@ -7,12 +7,15 @@
|
|||||||
import { DiscordAnalytics } from "@nhcarrigan/discord-analytics";
|
import { DiscordAnalytics } from "@nhcarrigan/discord-analytics";
|
||||||
import { Client, Events, GatewayIntentBits, Partials } from "discord.js";
|
import { Client, Events, GatewayIntentBits, Partials } from "discord.js";
|
||||||
import { chatInputInteractionCreate } from "./events/interactionCreate.js";
|
import { chatInputInteractionCreate } from "./events/interactionCreate.js";
|
||||||
import {
|
|
||||||
guildMessageCreate,
|
|
||||||
directMessageCreate,
|
|
||||||
} from "./events/messageCreate.js";
|
|
||||||
import { logger } from "./utils/logger.js";
|
import { logger } from "./utils/logger.js";
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Import {
|
||||||
|
* guildMessageCreate,
|
||||||
|
* directMessageCreate,
|
||||||
|
* } from "./events/messageCreate.js";
|
||||||
|
*/
|
||||||
|
|
||||||
const hikari = new Client({
|
const hikari = new Client({
|
||||||
intents: [
|
intents: [
|
||||||
GatewayIntentBits.Guilds,
|
GatewayIntentBits.Guilds,
|
||||||
@@ -35,13 +38,15 @@ hikari.once(Events.ClientReady, () => {
|
|||||||
analytics.startCron();
|
analytics.startCron();
|
||||||
});
|
});
|
||||||
|
|
||||||
hikari.on(Events.MessageCreate, (message) => {
|
/*
|
||||||
if (!message.inGuild()) {
|
* Hikari.on(Events.MessageCreate, (message) => {
|
||||||
void directMessageCreate(hikari, message);
|
* if (!message.inGuild()) {
|
||||||
return;
|
* void directMessageCreate(hikari, message);
|
||||||
}
|
* return;
|
||||||
void guildMessageCreate(hikari, message);
|
* }
|
||||||
});
|
* void guildMessageCreate(hikari, message);
|
||||||
|
* });
|
||||||
|
*/
|
||||||
|
|
||||||
hikari.on(Events.InteractionCreate, (interaction) => {
|
hikari.on(Events.InteractionCreate, (interaction) => {
|
||||||
if (interaction.isChatInputCommand()) {
|
if (interaction.isChatInputCommand()) {
|
||||||
|
|||||||
@@ -14,6 +14,9 @@ export default [
|
|||||||
"@typescript-eslint/no-empty-function": "off",
|
"@typescript-eslint/no-empty-function": "off",
|
||||||
"@typescript-eslint/consistent-type-assertions": "off",
|
"@typescript-eslint/consistent-type-assertions": "off",
|
||||||
"@typescript-eslint/no-extraneous-class": "off",
|
"@typescript-eslint/no-extraneous-class": "off",
|
||||||
|
"@typescript-eslint/no-unsafe-call": "off",
|
||||||
|
"@typescript-eslint/no-unsafe-assignment": "off",
|
||||||
|
"@typescript-eslint/no-unsafe-member-access": "off",
|
||||||
"stylistic/no-multi-spaces": "off",
|
"stylistic/no-multi-spaces": "off",
|
||||||
"unicorn/filename-case": "off",
|
"unicorn/filename-case": "off",
|
||||||
"@typescript-eslint/consistent-type-imports": "off",
|
"@typescript-eslint/consistent-type-imports": "off",
|
||||||
|
|||||||
+2
-2
@@ -17,8 +17,8 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@nhcarrigan/eslint-config": "5.2.0",
|
"@nhcarrigan/eslint-config": "5.2.0",
|
||||||
"@nhcarrigan/typescript-config": "4.0.0",
|
"@nhcarrigan/typescript-config": "4.0.0",
|
||||||
"eslint": "10.0.0",
|
"eslint": "9.30.1",
|
||||||
"turbo": "2.5.4",
|
"turbo": "2.8.10",
|
||||||
"typescript": "5.8.3"
|
"typescript": "5.8.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+1105
-1136
File diff suppressed because it is too large
Load Diff
@@ -2,3 +2,25 @@ packages:
|
|||||||
- bot
|
- bot
|
||||||
- client
|
- client
|
||||||
- server
|
- server
|
||||||
|
|
||||||
|
# Security
|
||||||
|
|
||||||
|
# Do not execute any scripts of installed packages (project scripts still run)
|
||||||
|
ignoreDepScripts: true
|
||||||
|
# Do not automatically run pre/post scripts (e.g. preinstall, postbuild)
|
||||||
|
enablePrePostScripts: false
|
||||||
|
# Only allow packages published at least 10 days ago (reduces risk of compromised packages)
|
||||||
|
minimumReleaseAge: 14400
|
||||||
|
# Fail if a package's trust level has decreased compared to previous releases
|
||||||
|
trustPolicy: no-downgrade
|
||||||
|
# Ignore trust policy for packages published more than 1 year ago (predates provenance signing)
|
||||||
|
trustPolicyIgnoreAfter: 525960
|
||||||
|
# Fail if there are missing or invalid peer dependencies
|
||||||
|
strictPeerDependencies: true
|
||||||
|
# Prevent transitive dependencies from using exotic sources (git repos, direct tarball URLs)
|
||||||
|
blockExoticSubdeps: true
|
||||||
|
|
||||||
|
# Lockfile
|
||||||
|
|
||||||
|
# Allow the lockfile to be updated during install (set to true in CI for stricter reproducibility)
|
||||||
|
preferFrozenLockfile: false
|
||||||
|
|||||||
@@ -4,9 +4,15 @@
|
|||||||
* @author Naomi Carrigan
|
* @author Naomi Carrigan
|
||||||
*/
|
*/
|
||||||
/* eslint-disable @typescript-eslint/naming-convention -- we are making raw API calls. */
|
/* 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";
|
import type { AnnouncementType } from "../interfaces/announcementType.js";
|
||||||
|
|
||||||
|
const discordLimit = 2000;
|
||||||
|
|
||||||
const channelIds: Record<AnnouncementType, string> = {
|
const channelIds: Record<AnnouncementType, string> = {
|
||||||
community: "1386105484313886820",
|
community: "1386105484313886820",
|
||||||
company: "1422472775695728661",
|
company: "1422472775695728661",
|
||||||
@@ -25,6 +31,7 @@ const getAnnouncementPing = (type: AnnouncementType): string => {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Forwards an announcement to our Discord server.
|
* 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 title - The title of the announcement.
|
||||||
* @param content - The main body of the announcement.
|
* @param content - The main body of the announcement.
|
||||||
* @param type - Whether the announcement is for a product or community.
|
* @param type - Whether the announcement is for a product or community.
|
||||||
@@ -35,12 +42,23 @@ export const announceOnDiscord = async(
|
|||||||
content: string,
|
content: string,
|
||||||
type: AnnouncementType,
|
type: AnnouncementType,
|
||||||
): Promise<string> => {
|
): 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(
|
const messageRequest = await fetch(
|
||||||
`https://discord.com/api/v10/channels/${channelIds[type]}/messages`,
|
`https://discord.com/api/v10/channels/${channelId}/messages`,
|
||||||
{
|
{
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
allowed_mentions: { parse: [ "users", "roles" ] },
|
allowed_mentions: { parse: [ "users", "roles" ] },
|
||||||
content: `# ${title}\n\n${content}\n-# ${getAnnouncementPing(type)}`,
|
content: `${firstMessagePrefix}${firstChunk}${firstMessageSuffix}`,
|
||||||
}),
|
}),
|
||||||
headers: {
|
headers: {
|
||||||
"Authorization": `Bot ${process.env.DISCORD_TOKEN ?? ""}`,
|
"Authorization": `Bot ${process.env.DISCORD_TOKEN ?? ""}`,
|
||||||
@@ -49,16 +67,19 @@ export const announceOnDiscord = async(
|
|||||||
method: "POST",
|
method: "POST",
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
if (messageRequest.status !== 200) {
|
if (messageRequest.status !== 200) {
|
||||||
return `Failed to send message to Discord. Status: ${messageRequest.status.toString()} ${messageRequest.statusText}`;
|
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.
|
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- fetch does not accept generics.
|
||||||
const message = await messageRequest.json() as { id?: string };
|
const message = await messageRequest.json() as { id?: string };
|
||||||
if (message.id === undefined) {
|
if (message.id === undefined) {
|
||||||
return `Failed to parse message ID, cannot crosspost. ${JSON.stringify(message)}`;
|
return `Failed to parse message ID, cannot crosspost. ${JSON.stringify(message)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const crosspostRequest = await fetch(
|
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: {
|
headers: {
|
||||||
"Authorization": `Bot ${process.env.DISCORD_TOKEN ?? ""}`,
|
"Authorization": `Bot ${process.env.DISCORD_TOKEN ?? ""}`,
|
||||||
@@ -67,8 +88,30 @@ export const announceOnDiscord = async(
|
|||||||
method: "POST",
|
method: "POST",
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!crosspostRequest.ok) {
|
if (!crosspostRequest.ok) {
|
||||||
return `Failed to crosspost message to Discord. Status: ${crosspostRequest.status.toString()} ${crosspostRequest.statusText}`;
|
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.";
|
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 @typescript-eslint/naming-convention -- we are making raw API calls. */
|
||||||
/* eslint-disable max-lines-per-function -- Big logic here. */
|
/* 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";
|
import type { AnnouncementType } from "../interfaces/announcementType.js";
|
||||||
|
|
||||||
|
const redditLimit = 40_000;
|
||||||
|
|
||||||
const flairIds: Record<AnnouncementType, string> = {
|
const flairIds: Record<AnnouncementType, string> = {
|
||||||
community: "7a01a5a6-0f29-11ef-a0c4-c6fb085f7c8f",
|
community: "7a01a5a6-0f29-11ef-a0c4-c6fb085f7c8f",
|
||||||
company: "dd8057c0-9e30-11f0-b321-d683551dcb2b",
|
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.
|
* 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 title - The title of the announcement.
|
||||||
* @param content - The main body of the announcement.
|
* @param content - The main body of the announcement.
|
||||||
* @param type - Whether the announcement is for a product or community.
|
* @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.";
|
return "Reddit credentials are not set.";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const chunks = chunkContent(content, redditLimit);
|
||||||
|
const firstChunk = chunks[0] ?? "";
|
||||||
|
const remainingChunks = chunks.slice(1);
|
||||||
|
|
||||||
const tokenResponse = await fetch(
|
const tokenResponse = await fetch(
|
||||||
"https://www.reddit.com/api/v1/access_token",
|
"https://www.reddit.com/api/v1/access_token",
|
||||||
{
|
{
|
||||||
@@ -71,7 +83,7 @@ export const announceOnReddit = async(
|
|||||||
flair_text: type,
|
flair_text: type,
|
||||||
kind: "self",
|
kind: "self",
|
||||||
sr: "nhcarrigan",
|
sr: "nhcarrigan",
|
||||||
text: content,
|
text: firstChunk,
|
||||||
title: title,
|
title: title,
|
||||||
}),
|
}),
|
||||||
headers: {
|
headers: {
|
||||||
@@ -85,6 +97,7 @@ export const announceOnReddit = async(
|
|||||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Fetch does not accept generic.
|
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Fetch does not accept generic.
|
||||||
const redditData = (await redditPost.json()) as {
|
const redditData = (await redditPost.json()) as {
|
||||||
json: {
|
json: {
|
||||||
|
data?: { name?: string };
|
||||||
errors: Array<unknown>;
|
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~! ✨";
|
return "Successfully posted announcement to Reddit~! ✨";
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { blockedIps } from "../cache/blockedIps.js";
|
|||||||
import { database } from "../db/database.js";
|
import { database } from "../db/database.js";
|
||||||
import { announceOnBluesky } from "../modules/announceOnBluesky.js";
|
import { announceOnBluesky } from "../modules/announceOnBluesky.js";
|
||||||
import { announceOnDiscord } from "../modules/announceOnDiscord.js";
|
import { announceOnDiscord } from "../modules/announceOnDiscord.js";
|
||||||
|
import { announceOnDiscourse } from "../modules/announceOnDiscourse.js";
|
||||||
import { announceOnFacebook } from "../modules/announceOnFacebook.js";
|
import { announceOnFacebook } from "../modules/announceOnFacebook.js";
|
||||||
import { announceOnMastodon } from "../modules/announceOnMastodon.js";
|
import { announceOnMastodon } from "../modules/announceOnMastodon.js";
|
||||||
import { announceOnReddit } from "../modules/announceOnReddit.js";
|
import { announceOnReddit } from "../modules/announceOnReddit.js";
|
||||||
@@ -20,6 +21,12 @@ import type { FastifyPluginAsync } from "fastify";
|
|||||||
|
|
||||||
const oneDay = 24 * 60 * 60 * 1000;
|
const oneDay = 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
const getPlatformResult = (result: PromiseSettledResult<string>): string => {
|
||||||
|
return result.status === "fulfilled"
|
||||||
|
? result.value
|
||||||
|
: `Unexpected error: ${String(result.reason)}`;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mounts the entry routes for the application. These routes
|
* Mounts the entry routes for the application. These routes
|
||||||
* should not require CORS, as they are used by external services
|
* should not require CORS, as they are used by external services
|
||||||
@@ -53,7 +60,6 @@ export const announcementRoutes: FastifyPluginAsync = async(server) => {
|
|||||||
server.post<{ Body: { content: string; type: string } }>(
|
server.post<{ Body: { content: string; type: string } }>(
|
||||||
"/announcement",
|
"/announcement",
|
||||||
|
|
||||||
// eslint-disable-next-line max-statements -- This is a long function.
|
|
||||||
async(request, reply) => {
|
async(request, reply) => {
|
||||||
const token = request.headers.authorization;
|
const token = request.headers.authorization;
|
||||||
if (token === undefined || token !== process.env.ANNOUNCEMENT_TOKEN) {
|
if (token === undefined || token !== process.env.ANNOUNCEMENT_TOKEN) {
|
||||||
@@ -84,8 +90,8 @@ export const announcementRoutes: FastifyPluginAsync = async(server) => {
|
|||||||
const announcement = await generateAnnouncements(content);
|
const announcement = await generateAnnouncements(content);
|
||||||
|
|
||||||
if (announcement === null) {
|
if (announcement === null) {
|
||||||
return await reply.status(201).send({
|
return await reply.status(500).send({
|
||||||
message: `Failed to generate announcements.`,
|
error: `Failed to generate announcements.`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,25 +110,30 @@ export const announcementRoutes: FastifyPluginAsync = async(server) => {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const discordPost = await announceOnDiscord(
|
const [
|
||||||
markdownTitle,
|
discordResult,
|
||||||
markdownContent,
|
redditResult,
|
||||||
type,
|
blueskyResult,
|
||||||
);
|
twitterResult,
|
||||||
const redditPost = await announceOnReddit(
|
facebookResult,
|
||||||
markdownTitle,
|
threadsResult,
|
||||||
markdownContent,
|
mastodonResult,
|
||||||
type,
|
discourseResult,
|
||||||
);
|
] = await Promise.allSettled([
|
||||||
const blueskyPost = await announceOnBluesky(threaded);
|
announceOnDiscord(markdownTitle, markdownContent, type),
|
||||||
const twitterPost = await announceOnTwitter(threaded);
|
announceOnReddit(markdownTitle, markdownContent, type),
|
||||||
const facebookPost = await announceOnFacebook(plaintext);
|
announceOnBluesky(threaded),
|
||||||
const threadsPost = await announceOnThreads(threaded);
|
announceOnTwitter(threaded),
|
||||||
const mastodonPost = await announceOnMastodon(threaded);
|
announceOnFacebook(plaintext),
|
||||||
|
announceOnThreads(threaded),
|
||||||
|
announceOnMastodon(threaded),
|
||||||
|
announceOnDiscourse(markdownTitle, markdownContent, type),
|
||||||
|
]);
|
||||||
|
|
||||||
return await reply.status(201).send({
|
return await reply.status(201).send({
|
||||||
alert: `Please remember to manually post to: LinkedIn, Peerlist, Ko-fi, and Patreon.`,
|
alert: `Please remember to manually post to: LinkedIn, Peerlist, Ko-fi, and Patreon.`,
|
||||||
cost: announcement.cost,
|
cost: announcement.cost,
|
||||||
message: `Announcement processed. Discord: ${discordPost}, Reddit: ${redditPost}, Bluesky: ${blueskyPost}, Twitter: ${twitterPost}, Facebook: ${facebookPost}, Threads: ${threadsPost}, Mastodon: ${mastodonPost}`,
|
message: `Announcement processed. Discord: ${getPlatformResult(discordResult)}, Reddit: ${getPlatformResult(redditResult)}, Bluesky: ${getPlatformResult(blueskyResult)}, Twitter: ${getPlatformResult(twitterResult)}, Facebook: ${getPlatformResult(facebookResult)}, Threads: ${getPlatformResult(threadsResult)}, Mastodon: ${getPlatformResult(mastodonResult)}, Discourse: ${getPlatformResult(discourseResult)}`,
|
||||||
rawPost: announcement.response,
|
rawPost: announcement.response,
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
/**
|
||||||
|
* @copyright nhcarrigan
|
||||||
|
* @license Naomi's Public License
|
||||||
|
* @author Naomi Carrigan
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* eslint-disable max-lines-per-function -- Multi-level split logic requires many lines. */
|
||||||
|
/* eslint-disable max-statements -- Multi-level split logic requires many statements. */
|
||||||
|
/* eslint-disable complexity -- Multi-level split logic has inherent branching complexity. */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Splits content into chunks that do not exceed the given character limit.
|
||||||
|
* Splits preferably at paragraph boundaries, then line boundaries,
|
||||||
|
* then hard-cuts at the limit as a last resort.
|
||||||
|
* @param content - The content to chunk.
|
||||||
|
* @param limit - The maximum character count per chunk.
|
||||||
|
* @returns An array of content chunks.
|
||||||
|
*/
|
||||||
|
export const chunkContent = (content: string, limit: number): Array<string> => {
|
||||||
|
if (content.length <= limit) {
|
||||||
|
return [ content ];
|
||||||
|
}
|
||||||
|
|
||||||
|
const chunks: Array<string> = [];
|
||||||
|
const paragraphs = content.split("\n\n");
|
||||||
|
let current = "";
|
||||||
|
|
||||||
|
for (const paragraph of paragraphs) {
|
||||||
|
const separator = current.length > 0
|
||||||
|
? "\n\n"
|
||||||
|
: "";
|
||||||
|
const combined = `${current}${separator}${paragraph}`;
|
||||||
|
|
||||||
|
if (combined.length <= limit) {
|
||||||
|
current = combined;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (current.length > 0) {
|
||||||
|
chunks.push(current);
|
||||||
|
current = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (paragraph.length <= limit) {
|
||||||
|
current = paragraph;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Paragraph itself exceeds the limit — split by lines
|
||||||
|
const lines = paragraph.split("\n");
|
||||||
|
for (const line of lines) {
|
||||||
|
const lineSeparator = current.length > 0
|
||||||
|
? "\n"
|
||||||
|
: "";
|
||||||
|
const combinedLine = `${current}${lineSeparator}${line}`;
|
||||||
|
|
||||||
|
if (combinedLine.length <= limit) {
|
||||||
|
current = combinedLine;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (current.length > 0) {
|
||||||
|
chunks.push(current);
|
||||||
|
current = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (line.length <= limit) {
|
||||||
|
current = line;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Single line exceeds limit — hard-cut
|
||||||
|
for (let index = 0; index < line.length; index = index + limit) {
|
||||||
|
chunks.push(line.slice(index, index + limit));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (current.length > 0) {
|
||||||
|
chunks.push(current);
|
||||||
|
}
|
||||||
|
|
||||||
|
return chunks;
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user