|
| 1 | +/** |
| 2 | + * @script fetch-discord-announcements |
| 3 | + * @type automation |
| 4 | + * @concern content |
| 5 | + * @niche data/fetching |
| 6 | + * @purpose infrastructure:data-feeds |
| 7 | + * @description Fetches announcements from Discord channels via bot token. Writes per-product |
| 8 | + * JSX data files from config.products[].discord and per-channel JSX files from |
| 9 | + * config.globals.discord[]. Each entry produces a specific output file. |
| 10 | + * @mode generate |
| 11 | + * @pipeline config → Discord API → snippets/automations/{product}/discordData.jsx |
| 12 | + * → snippets/automations/discord/discordAnnouncementsData.jsx |
| 13 | + * @scope .github/scripts, snippets/automations/ |
| 14 | + * @usage node .github/scripts/fetch-discord-announcements.js |
| 15 | + * @policy Announcements channel only. No general chat. Requires DISCORD_BOT_TOKEN. |
| 16 | + */ |
| 17 | +const https = require("https"); |
| 18 | +const fs = require("fs"); |
| 19 | +const path = require("path"); |
| 20 | +const { escapeForJsx } = require(path.resolve(__dirname, "../../operations/scripts/config/mdx-sanitise")); |
| 21 | + |
| 22 | +const DISCORD_BOT_TOKEN = process.env.DISCORD_BOT_TOKEN; |
| 23 | +const CONFIG_PATH = |
| 24 | + process.env.CONFIG_PATH || "operations/scripts/config/product-social-config.json"; |
| 25 | +const LIMIT = parseInt(process.env.LIMIT || "10", 10); |
| 26 | + |
| 27 | +function discordGet(endpoint) { |
| 28 | + return new Promise((resolve, reject) => { |
| 29 | + const options = { |
| 30 | + hostname: "discord.com", |
| 31 | + path: `/api/v10${endpoint}`, |
| 32 | + method: "GET", |
| 33 | + headers: { |
| 34 | + Authorization: `Bot ${DISCORD_BOT_TOKEN}`, |
| 35 | + "Content-Type": "application/json", |
| 36 | + }, |
| 37 | + }; |
| 38 | + const req = https.request(options, (res) => { |
| 39 | + let data = ""; |
| 40 | + res.on("data", (chunk) => (data += chunk)); |
| 41 | + res.on("end", () => { |
| 42 | + try { |
| 43 | + resolve(JSON.parse(data)); |
| 44 | + } catch (e) { |
| 45 | + reject(new Error(`Discord API parse error: ${data.substring(0, 200)}`)); |
| 46 | + } |
| 47 | + }); |
| 48 | + }); |
| 49 | + req.on("error", reject); |
| 50 | + req.end(); |
| 51 | + }); |
| 52 | +} |
| 53 | + |
| 54 | +const escapeForJSX = (str) => escapeForJsx(str); |
| 55 | + |
| 56 | +/** |
| 57 | + * Convert Discord markdown to HTML before JSX escaping. |
| 58 | + * Handles: bold, italic, underline, strikethrough, links, mentions, code blocks, line breaks. |
| 59 | + */ |
| 60 | +function discordMarkdownToHTML(text) { |
| 61 | + if (!text) return ""; |
| 62 | + let result = text |
| 63 | + // Strip @everyone / @here mentions |
| 64 | + .replace(/@(everyone|here)/g, "") |
| 65 | + // Code blocks (```lang\n...\n```) |
| 66 | + .replace(/```\w*\n?([\s\S]*?)```/g, "<pre><code>$1</code></pre>") |
| 67 | + // Inline code |
| 68 | + .replace(/`([^`]+)`/g, "<code>$1</code>") |
| 69 | + // Bold + italic (***text***) |
| 70 | + .replace(/\*\*\*(.+?)\*\*\*/g, "<strong><em>$1</em></strong>") |
| 71 | + // Bold (**text**) |
| 72 | + .replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>") |
| 73 | + // Italic (*text*) |
| 74 | + .replace(/\*(.+?)\*/g, "<em>$1</em>") |
| 75 | + // Underline (__text__) |
| 76 | + .replace(/__(.+?)__/g, "<u>$1</u>") |
| 77 | + // Strikethrough (~~text~~) |
| 78 | + .replace(/~~(.+?)~~/g, "<s>$1</s>") |
| 79 | + // Links [text](url) |
| 80 | + .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>') |
| 81 | + // Bare URLs (not already in an href) |
| 82 | + .replace(/(?<!href="|>)(https?:\/\/[^\s<]+)/g, '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>') |
| 83 | + // Discord list items (- item or • item) — must run BEFORE \n → <br /> |
| 84 | + .replace(/^[-•]\s+(.+)$/gm, "<li>$1</li>"); |
| 85 | + |
| 86 | + // Wrap consecutive <li> in <ul> — strip \n between list items |
| 87 | + result = result.replace(/(<li>[\s\S]*?<\/li>[\n]*)+/g, (match) => { |
| 88 | + const cleaned = match.replace(/\n/g, ""); |
| 89 | + return "<ul>" + cleaned + "</ul>"; |
| 90 | + }); |
| 91 | + |
| 92 | + // Now convert remaining \n to <br /> (not inside lists) |
| 93 | + result = result.replace(/\n/g, "<br />"); |
| 94 | + |
| 95 | + return result; |
| 96 | +} |
| 97 | + |
| 98 | +function formatTimestamp(isoStr) { |
| 99 | + return new Date(isoStr).toISOString(); |
| 100 | +} |
| 101 | + |
| 102 | +async function fetchForProduct(productKey, discordConfig) { |
| 103 | + const { serverId, announcementsChannelId } = discordConfig; |
| 104 | + |
| 105 | + if (!serverId || !announcementsChannelId) { |
| 106 | + console.log( |
| 107 | + ` Skipping ${productKey}: missing serverId or announcementsChannelId` |
| 108 | + ); |
| 109 | + return null; |
| 110 | + } |
| 111 | + |
| 112 | + console.log( |
| 113 | + ` Fetching from channel ${announcementsChannelId} in server ${serverId}...` |
| 114 | + ); |
| 115 | + |
| 116 | + const messages = await discordGet( |
| 117 | + `/channels/${announcementsChannelId}/messages?limit=${LIMIT}` |
| 118 | + ); |
| 119 | + |
| 120 | + if (!Array.isArray(messages) || messages.length === 0) { |
| 121 | + console.log(` No messages found (or access denied)`); |
| 122 | + return []; |
| 123 | + } |
| 124 | + |
| 125 | + return messages.map((msg) => { |
| 126 | + // Build content: prefer message content, then message_snapshots (forwarded messages), then embeds |
| 127 | + let rawContent = msg.content || ""; |
| 128 | + let snapshotEmbeds = []; |
| 129 | + let snapshotAttachments = []; |
| 130 | + // Forwarded messages (flags 16384) have content in message_snapshots |
| 131 | + if (!rawContent && msg.message_snapshots && msg.message_snapshots.length > 0) { |
| 132 | + const snapshot = msg.message_snapshots[0].message; |
| 133 | + rawContent = snapshot?.content || ""; |
| 134 | + snapshotEmbeds = snapshot?.embeds || []; |
| 135 | + snapshotAttachments = snapshot?.attachments || []; |
| 136 | + } |
| 137 | + // Fall back to message-level embeds |
| 138 | + if (!rawContent && msg.embeds && msg.embeds.length > 0) { |
| 139 | + snapshotEmbeds = msg.embeds; |
| 140 | + } |
| 141 | + // Fall back to attachment filenames if still empty |
| 142 | + if (!rawContent && !snapshotEmbeds.length && msg.attachments && msg.attachments.length > 0) { |
| 143 | + rawContent = msg.attachments.map((a) => `[${a.filename}](${a.url})`).join(", "); |
| 144 | + } |
| 145 | + |
| 146 | + // Convert Discord markdown to HTML |
| 147 | + let htmlContent = discordMarkdownToHTML(rawContent); |
| 148 | + |
| 149 | + // Append embed cards (title + description + image) |
| 150 | + for (const embed of snapshotEmbeds) { |
| 151 | + const parts = []; |
| 152 | + if (embed.title && embed.url) { |
| 153 | + parts.push(`<a href="${embed.url}" target="_blank" rel="noopener noreferrer"><strong>${embed.title}</strong></a>`); |
| 154 | + } else if (embed.title) { |
| 155 | + parts.push(`<strong>${embed.title}</strong>`); |
| 156 | + } |
| 157 | + if (embed.description) { |
| 158 | + parts.push(`<p>${discordMarkdownToHTML(embed.description)}</p>`); |
| 159 | + } |
| 160 | + if (embed.image?.url) { |
| 161 | + parts.push(`<img src="${embed.image.url}" alt="${embed.title || ''}" style="max-width:100%;border-radius:8px;margin-top:8px" />`); |
| 162 | + } else if (embed.thumbnail?.url) { |
| 163 | + parts.push(`<img src="${embed.thumbnail.url}" alt="${embed.title || ''}" style="max-width:300px;border-radius:8px;margin-top:8px" />`); |
| 164 | + } |
| 165 | + if (parts.length) { |
| 166 | + htmlContent += '<div style="border-left:3px solid var(--accent);padding:8px 12px;margin-top:12px;border-radius:4px">' + parts.join("") + "</div>"; |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + // Append attachments (images and videos from snapshot) |
| 171 | + for (const att of snapshotAttachments) { |
| 172 | + const ext = (att.filename || "").split(".").pop().toLowerCase(); |
| 173 | + if (["mp4", "webm", "mov"].includes(ext)) { |
| 174 | + htmlContent += `<video src="${att.url}" controls width="100%" height="auto" style="border-radius:8px;margin-top:12px"></video>`; |
| 175 | + } else if (["png", "jpg", "jpeg", "gif", "webp"].includes(ext)) { |
| 176 | + htmlContent += `<img src="${att.url}" alt="${att.filename}" width="100%" height="auto" style="border-radius:8px;margin-top:12px" />`; |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | + return { |
| 181 | + id: msg.id, |
| 182 | + content: escapeForJSX(htmlContent), |
| 183 | + author: msg.author?.username || "Unknown", |
| 184 | + timestamp: formatTimestamp(msg.timestamp), |
| 185 | + url: `https://discord.com/channels/${serverId}/${announcementsChannelId}/${msg.id}`, |
| 186 | + }; |
| 187 | + }).filter((msg) => msg.content.length > 0); |
| 188 | +} |
| 189 | + |
| 190 | +function writeJSX(exportName, announcements, outPath) { |
| 191 | + let jsx = `export const ${exportName} = [\n`; |
| 192 | + announcements.forEach((item, idx) => { |
| 193 | + jsx += ` {\n`; |
| 194 | + jsx += ` id: "${item.id}",\n`; |
| 195 | + jsx += ` content: "${item.content}",\n`; |
| 196 | + jsx += ` author: "${escapeForJSX(item.author)}",\n`; |
| 197 | + jsx += ` timestamp: "${item.timestamp}",\n`; |
| 198 | + jsx += ` url: "${item.url}"\n`; |
| 199 | + jsx += ` }${idx < announcements.length - 1 ? "," : ""}\n`; |
| 200 | + }); |
| 201 | + jsx += `];\n`; |
| 202 | + fs.mkdirSync(path.dirname(outPath), { recursive: true }); |
| 203 | + fs.writeFileSync(outPath, jsx); |
| 204 | + console.log(` Written to ${outPath}`); |
| 205 | +} |
| 206 | + |
| 207 | +async function main() { |
| 208 | + if (!DISCORD_BOT_TOKEN) { |
| 209 | + throw new Error( |
| 210 | + "DISCORD_BOT_TOKEN environment variable is not set." |
| 211 | + ); |
| 212 | + } |
| 213 | + |
| 214 | + const config = JSON.parse(fs.readFileSync(CONFIG_PATH, "utf8")); |
| 215 | + |
| 216 | + // Per-product feeds |
| 217 | + const products = config.products || {}; |
| 218 | + for (const [productKey, productConfig] of Object.entries(products)) { |
| 219 | + const discord = productConfig.discord; |
| 220 | + if (!discord) { |
| 221 | + console.log(`${productKey}: no discord config, skipping`); |
| 222 | + continue; |
| 223 | + } |
| 224 | + |
| 225 | + console.log(`Processing ${productKey}...`); |
| 226 | + const announcements = await fetchForProduct(productKey, discord); |
| 227 | + if (announcements === null) continue; |
| 228 | + |
| 229 | + const exportName = `${productKey.replace(/-/g, "")}DiscordData`; |
| 230 | + const outPath = path.join(`snippets/automations/solutions/${productKey}`, "discordData.jsx"); |
| 231 | + writeJSX(exportName, announcements, outPath); |
| 232 | + } |
| 233 | + |
| 234 | + // Global channel feeds (explicit outputPath + exportName per entry) |
| 235 | + const globalChannels = config.globals?.discord || []; |
| 236 | + for (const channel of globalChannels) { |
| 237 | + const { key, serverId, announcementsChannelId, outputPath, exportName } = channel; |
| 238 | + if (!serverId || !announcementsChannelId || !outputPath || !exportName) { |
| 239 | + console.log(`globals.discord[${key}]: missing required fields, skipping`); |
| 240 | + continue; |
| 241 | + } |
| 242 | + |
| 243 | + console.log(`Processing global channel ${key}...`); |
| 244 | + const announcements = await fetchForProduct(key, { serverId, announcementsChannelId }); |
| 245 | + if (announcements === null) continue; |
| 246 | + |
| 247 | + writeJSX(exportName, announcements, outputPath); |
| 248 | + } |
| 249 | +} |
| 250 | + |
| 251 | +main().catch((err) => { |
| 252 | + console.error("Error:", err); |
| 253 | + process.exit(1); |
| 254 | +}); |
0 commit comments