Files
erika/lib/discord-webhook-settings.ts
T

38 lines
1.1 KiB
TypeScript

const DISCORD_WEBHOOK_HOSTS = new Set([
"discord.com",
"canary.discord.com",
"ptb.discord.com",
]);
export function isValidDiscordWebhookUrl(value: string) {
try {
const url = new URL(value);
return (
url.protocol === "https:" &&
DISCORD_WEBHOOK_HOSTS.has(url.hostname) &&
/^\/api\/webhooks\/[^/]+\/[^/]+\/?$/.test(url.pathname)
);
} catch {
return false;
}
}
export function previewWebhookTemplate(
template: string,
options: { update?: boolean } = {}
) {
const source =
template.trim() ||
(options.update
? "Submission updated by {username} ({id}).\n{update}"
: "New submission from {username} ({id}).");
return source.replace(/\{([^}]+)\}/g, (_match, variable: string) => {
const key = variable.toLowerCase();
if (key === "username" || key === "displayname") return "Example User";
if (key === "id") return "123456789";
if (key === "update") return "Question 1: Previous answer → Example answer";
if (/^\d+$/.test(key)) return `Example answer ${key}`;
return `{${variable}}`;
});
}