Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(discord): post GitHub issues in the Discord forums
leepokai66a5328dacc9
diff --git a/discord/README.md b/discord/README.mdindex bc87fac1..d962c8fa 100644--- a/discord/README.md+++ b/discord/README.md@@ -21,6 +21,11 @@ the GitHub roles.daily cron sums the installer downloads of every release: `.dmg`, `.exe`, `.AppImage`, `.deb`, `.rpm`,desktop Linux `.tar.gz`; goal `DOWNLOAD_GOAL`). The last milestone posted is kept in KV (`stars:milestone`,`downloads:milestone`), so a count that dips and climbs back doesn't repeat it.+7. Every GitHub issue gets its own post, tagged **GitHub**, in #feature-requests (the `enhancement` label or a+ "[Feature]" title) or #bug-reports (everything else), from the `issues` webhook. Closing on GitHub posts in+ the thread and closes it (with **Fixed** / **Shipped** when completed); reopening reopens it. Replies in+ Discord stay in Discord. KV keeps `issue:<number>` → `{ kind, thread }`, and the daily cron posts any open+ issue that has no post yet (that brought the existing ones over, and it catches a missed webhook).`.github/workflows/contributor.yml` comments the link on a contributor's first merged pull request and firstissue. The onboarding Server Guide has a "Link your GitHub" to-do that leads to the link in #welcome.@@ -30,7 +35,8 @@ issue. The onboarding Server Guide has a "Link your GitHub" to-do that leads to- Discord application **Codync** (Developer Portal): OAuth2 redirect `https://discord.codync.dev/callback`; botnot public. In the server, its role keeps Manage Roles and Create Invite (`guilds.join` needs it), sits aboveContributor and Reporter, and can view and send in #moderator-only and #milestones (read-only for everyone- else), where it may also mention @everyone.+ else), where it may also mention @everyone. On the Support category it may create posts, send in threads and+ manage threads (the moderator-only **GitHub** and **Shipped** tags, closing posts).- GitHub OAuth app **Codync Discord** (leepokai's developer settings): callback`https://discord.codync.dev/github/callback`, no scopes requested.- Repo webhook: `https://discord.codync.dev/webhook`, JSON, events `pull_request`, `issues` and `star`, secret =diff --git a/discord/package.json b/discord/package.jsonindex 052d617e..26836812 100644--- a/discord/package.json+++ b/discord/package.json@@ -8,7 +8,7 @@"scripts": {"deploy": "wrangler deploy","typecheck": "tsc",- "test": "node --experimental-strip-types --no-warnings test/claim.test.ts"+ "test": "node --experimental-strip-types --no-warnings test/claim.test.ts && node --experimental-strip-types --no-warnings test/issues.test.ts"},"devDependencies": {"@cloudflare/workers-types": "^5.20261006.1",diff --git a/discord/src/guild.ts b/discord/src/guild.tsindex ac72731f..9bc3d963 100644--- a/discord/src/guild.ts+++ b/discord/src/guild.ts@@ -19,9 +19,19 @@ export const roles = (env: Env): Role[] => [export const names = (list: Role[]) => list.map((r) => r.name).join(" and ");export const profile = (login: string) => `[${login}](https://github.com/${login})`;-const bot = (env: Env) => ({ Authorization: `Bot ${env.DISCORD_BOT_TOKEN}` });+export const bot = (env: Env) => ({ Authorization: `Bot ${env.DISCORD_BOT_TOKEN}` });export const github = (env: Env) => ({ headers: { Authorization: `Bearer ${env.GITHUB_TOKEN}`, "User-Agent": "codync-discord" } });+/** Every item of a paged GitHub list under the repo (`path` is relative to /repos/<repo>/). */+export async function githubAll<T>(env: Env, path: string): Promise<T[]> {+ const all: T[] = [];+ for (let page = 1; ; page++) {+ const items = await json<T[]>(`https://api.github.com/repos/${env.REPO}/${path}${path.includes("?") ? "&" : "?"}per_page=100&page=${page}`, github(env));+ all.push(...items);+ if (items.length < 100) return all;+ }+}+/** The account's current login; names in connections go stale after a rename, ids don't. */export async function githubLogin(env: Env, githubId: string): Promise<string> {return (await json<{ login: string }>(`https://api.github.com/user/${githubId}`, github(env))).login;diff --git a/discord/src/index.ts b/discord/src/index.tsindex 0c8d8950..d7634391 100644--- a/discord/src/index.ts+++ b/discord/src/index.ts@@ -2,12 +2,14 @@// their GitHub account comes from their Discord connections (verified by Discord) or, when they have none, from// signing in with GitHub, so nobody can claim someone else's. A merged pull request on the repo earns the// Contributor role, an opened issue the Reporter role. The link is remembered, so later ones arrive on their-// own (webhook.ts). Star and download milestones are posted in #milestones (milestones.ts).+// own (webhook.ts). GitHub issues get forum posts (issues.ts); star and download milestones are posted in+// #milestones (milestones.ts).import { DISCORD, earnedRoles, githubLogin, grant, join, names, notify, profile } from "./guild.ts";import { sign, verify } from "./hmac.ts";import { json, page } from "./http.ts";import { mentions } from "./mentions.ts";+import { postOpenIssues } from "./issues.ts";import { celebrate, downloads } from "./milestones.ts";import { webhook } from "./webhook.ts";@@ -27,11 +29,14 @@ export interface Env {REPORTER_ROLE_ID: string;STAFF_CHANNEL_ID: string;MILESTONES_CHANNEL_ID: string;+ BUG_FORUM_ID: string;+ FEATURE_FORUM_ID: string;/** The counts the #milestones posts count toward. */STAR_GOAL: string;DOWNLOAD_GOAL: string;REPO: string;- /** `github:<GitHub user id>` → Discord user id; `<stars|downloads>:milestone` → the last milestone posted. */+ /** `github:<GitHub user id>` → Discord user id; `<stars|downloads>:milestone` → the last milestone posted;+ * `issue:<number>` → its forum post (`{ kind, thread }`). */LINKS: KVNamespace;}@@ -53,9 +58,10 @@ export default {}},- // Daily (wrangler.toml): GitHub has no download event, so the count is polled.+ // Daily (wrangler.toml): GitHub has no download event, so the count is polled; open issues without a forum+ // post get one.async scheduled(_controller: ScheduledController, env: Env): Promise<void> {- await celebrate(env, "downloads", await downloads(env));+ await Promise.all([downloads(env).then((count) => celebrate(env, "downloads", count)), postOpenIssues(env)]);},};diff --git a/discord/src/issues.ts b/discord/src/issues.tsnew file mode 100644index 00000000..30ec1032--- /dev/null+++ b/discord/src/issues.ts@@ -0,0 +1,95 @@+// GitHub issues in the Discord forums: each issue gets its own post, tagged GitHub, in #feature-requests (the+// `enhancement` label or a "[Feature]" title) or #bug-reports (everything else). Closing and reopening on GitHub+// is posted in that thread and closes or reopens it; replies in Discord stay in Discord.++import { DISCORD, bot, githubAll, send } from "./guild.ts";+import { json } from "./http.ts";+import type { Env } from "./index.ts";++export interface Issue {+ number: number;+ title: string;+ body: string | null;+ html_url: string;+ state_reason?: string | null;+ labels: { name: string }[];+ user: { login: string };+ pull_request?: unknown;+}++type Kind = "bug" | "feature";++/** Each forum and the tag a post gets when its issue is closed as completed. */+const forum = (env: Env, kind: Kind) =>+ kind === "feature" ? { id: env.FEATURE_FORUM_ID, done: "Shipped" } : { id: env.BUG_FORUM_ID, done: "Fixed" };++const kindOf = (issue: Issue): Kind =>+ /^\s*\[feature/i.test(issue.title) || issue.labels.some((l) => l.name === "enhancement") ? "feature" : "bug";++const key = (issue: Issue) => `issue:${issue.number}`;+const EXCERPT = 1200;++export async function syncIssue(env: Env, action: string, issue: Issue): Promise<void> {+ if (action === "opened") await post(env, issue);+ if (action === "closed" || action === "reopened") await setState(env, issue, action === "closed");+}++/** Posts every open issue that has no post yet: the first run brings the existing ones over, later runs catch a+ * missed webhook. */+export async function postOpenIssues(env: Env): Promise<void> {+ const open = await githubAll<Issue>(env, `issues?state=open&sort=created&direction=asc`);+ for (const issue of open.filter((i) => !i.pull_request)) await post(env, issue);+}++async function post(env: Env, issue: Issue): Promise<void> {+ if (await env.LINKS.get(key(issue))) return;+ const kind = kindOf(issue);+ const { id } = forum(env, kind);+ const tags = await tagIds(env, id);+ const thread = await json<{ id: string }>(`${DISCORD}/channels/${id}/threads`, {+ method: "POST",+ headers: { ...bot(env), "Content-Type": "application/json" },+ body: JSON.stringify({+ name: `#${issue.number} ${issue.title}`.slice(0, 100),+ applied_tags: [tags.get("GitHub")],+ message: { content: opening(issue), flags: 4, allowed_mentions: { parse: [] } },+ }),+ });+ await env.LINKS.put(key(issue), JSON.stringify({ kind, thread: thread.id }));+ console.log("issue posted", { issue: issue.number, thread: thread.id });+}++async function setState(env: Env, issue: Issue, closed: boolean): Promise<void> {+ const saved = await env.LINKS.get(key(issue));+ if (!saved) return closed ? undefined : post(env, issue);+ const { kind, thread } = JSON.parse(saved) as { kind: Kind; thread: string };+ const how = !closed ? "🔄 Reopened" : issue.state_reason === "not_planned" ? "Closed as not planned" : "✅ Closed as completed";+ // A message in a closed thread reopens it, so it goes first.+ await send(env, thread, `${how} on GitHub: <${issue.html_url}>`);+ const done = (await tagIds(env, forum(env, kind).id)).get(forum(env, kind).done);+ const current = (await json<{ applied_tags: string[] }>(`${DISCORD}/channels/${thread}`, { headers: bot(env) })).applied_tags;+ const completed = closed && issue.state_reason !== "not_planned";+ const tags = current.filter((t) => t !== done).concat(completed && done ? [done] : []);+ await json(`${DISCORD}/channels/${thread}`, {+ method: "PATCH",+ headers: { ...bot(env), "Content-Type": "application/json" },+ body: JSON.stringify({ applied_tags: tags, archived: closed }),+ });+}++/** The forum's tags by name. */+async function tagIds(env: Env, forumId: string): Promise<Map<string, string>> {+ const { available_tags } = await json<{ available_tags: { id: string; name: string }[] }>(`${DISCORD}/channels/${forumId}`, { headers: bot(env) });+ return new Map(available_tags.map((t) => [t.name, t.id]));+}++function opening(issue: Issue): string {+ const body = (issue.body ?? "").replace(/<!--[\s\S]*?-->/g, "").trim();+ const excerpt = body.length > EXCERPT ? `${body.slice(0, EXCERPT).trimEnd()}…` : body;+ return [+ // A plain login: the forum list previews this line without rendering links.+ `Opened on GitHub by ${issue.user.login}: <${issue.html_url}>`,+ excerpt,+ "-# Replies here stay in Discord. Comment on GitHub to reach the issue.",+ ].filter(Boolean).join("\n\n");+}diff --git a/discord/src/milestones.ts b/discord/src/milestones.tsindex 6109fb51..88d126b4 100644--- a/discord/src/milestones.ts+++ b/discord/src/milestones.ts@@ -1,8 +1,7 @@// Milestones in #milestones, each posted once with @everyone and the way left to the goal: every 100th GitHub// star (from the repo webhook) and every 1,000th download of the desktop app (counted once a day).-import { github, send } from "./guild.ts";-import { json } from "./http.ts";+import { githubAll, send } from "./guild.ts";import type { Env } from "./index.ts";export type Kind = "stars" | "downloads";@@ -45,15 +44,8 @@ const INSTALLER = /\.(dmg|exe|appimage|deb|rpm)$|^codync-linux-.*\.tar\.gz$/i;/** Desktop app downloads across every release. */export async function downloads(env: Env): Promise<number> {- let total = 0;- for (let page = 1; ; page++) {- const releases = await json<{ assets: { name: string; download_count: number }[] }[]>(- `https://api.github.com/repos/${env.REPO}/releases?per_page=100&page=${page}`, github(env));- for (const { assets } of releases) {- total += assets.filter((a) => INSTALLER.test(a.name)).reduce((sum, a) => sum + a.download_count, 0);- }- if (releases.length < 100) return total;- }+ const releases = await githubAll<{ assets: { name: string; download_count: number }[] }>(env, "releases");+ return releases.flatMap((r) => r.assets).filter((a) => INSTALLER.test(a.name)).reduce((sum, a) => sum + a.download_count, 0);}const PITCH = "Codync: your coding agents, as teammates you can message. Free and open source.";diff --git a/discord/src/webhook.ts b/discord/src/webhook.tsindex 36cd468c..cd871673 100644--- a/discord/src/webhook.ts+++ b/discord/src/webhook.ts@@ -1,9 +1,11 @@// GitHub webhook (pull_request, issues, star): a linked member earns a role as soon as their pull request merges-// or their issue opens, without opening the link again; each 100th star is celebrated in #milestones.+// or their issue opens, without opening the link again; issues get their forum posts (issues.ts); each 100th+// star is celebrated in #milestones.import { grant, notify, profile, roles, type Role } from "./guild.ts";import { verify } from "./hmac.ts";import type { Env } from "./index.ts";+import { type Issue, syncIssue } from "./issues.ts";import { celebrate } from "./milestones.ts";interface Item {@@ -15,7 +17,7 @@ interface Item {interface Payload {action: string;pull_request?: Item & { merged: boolean };- issue?: Item;+ issue?: Item & Issue;repository?: { stargazers_count: number };}@@ -33,6 +35,11 @@ export async function webhook(req: Request, env: Env): Promise<Response> {await celebrate(env, "stars", payload.repository.stargazers_count);return done();}+ if (event === "issues" && payload.issue) {+ const { number } = payload.issue;+ // The daily run posts an open issue whose post failed here; the role below goes ahead either way.+ await syncIssue(env, payload.action, payload.issue).catch((e) => console.error("issue sync failed", { issue: number, error: String(e) }));+ }const earned = earnedBy(event, payload, env);if (!earned) return done();const { role, item, what } = earned;diff --git a/discord/test/claim.test.ts b/discord/test/claim.test.tsindex 43d2fbac..e1147f46 100644--- a/discord/test/claim.test.ts+++ b/discord/test/claim.test.ts@@ -145,6 +145,7 @@ assert.deepEqual(calls, ["role contributor", "notify <@42> ([octo](https://githucalls = stub({ held: ["reporter"] });const issue = { action: "opened", issue: { number: 5, html_url: "https://github.com/leepokai/Codync/issues/5", user: { id: 7, login: "octo" } } };+links.set("issue:5", "{}"); // already in the forum (issues.test.ts covers the post)assert.equal(await hook("issues", issue), 204);assert.deepEqual(calls, []);@@ -182,6 +183,7 @@ globalThis.fetch = (async (input: string, init?: RequestInit) => {const url = String(input);const page = url.match(/^https:\/\/api\.github\.com\/repos\/leepokai\/Codync\/releases\?per_page=100&page=(\d+)$/)?.[1];if (page) return Response.json(releases[Number(page) - 1] ?? []);+ if (url.startsWith("https://api.github.com/repos/leepokai/Codync/issues?")) return Response.json([]);assert.equal(url, "https://discord.com/api/v10/channels/milestones/messages");if (!up) return new Response("down", { status: 503 });const body = JSON.parse(String(init?.body));diff --git a/discord/test/issues.test.ts b/discord/test/issues.test.tsnew file mode 100644index 00000000..eb6c3ee7--- /dev/null+++ b/discord/test/issues.test.ts@@ -0,0 +1,79 @@+// GitHub issues → Discord forum posts, against stubbed Discord, GitHub and KV: an opened issue gets one post in the+// right forum, closing and reopening update it, and the daily run posts open issues that have none yet.+import assert from "node:assert/strict";+import { sign } from "../src/hmac.ts";+import worker from "../src/index.ts";++const links = new Map<string, string>();+const env = {+ DISCORD_BOT_TOKEN: "bot", GITHUB_TOKEN: "gh", GITHUB_WEBHOOK_SECRET: "hook", REPO: "leepokai/Codync",+ BUG_FORUM_ID: "bugs", FEATURE_FORUM_ID: "features", MILESTONES_CHANNEL_ID: "milestones", STAR_GOAL: "1000", DOWNLOAD_GOAL: "10000",+ LINKS: { get: async (k: string) => links.get(k) ?? null, put: async (k: string, v: string) => void links.set(k, v) },+} as never;++const tags = {+ bugs: [{ id: "gh-b", name: "GitHub" }, { id: "fixed", name: "Fixed" }],+ features: [{ id: "gh-f", name: "GitHub" }, { id: "shipped", name: "Shipped" }],+};+let open: object[] = [];+let calls: string[] = [];+let threadTags: string[] = [];+globalThis.fetch = (async (input: string, init?: RequestInit) => {+ const url = String(input);+ const method = init?.method ?? "GET";+ const body = init?.body ? JSON.parse(String(init.body)) : null;+ if (url.startsWith("https://api.github.com/repos/leepokai/Codync/releases?")) return Response.json([]);+ if (url.startsWith("https://api.github.com/repos/leepokai/Codync/issues?state=open")) return Response.json(open);+ const forum = url.match(/\/channels\/(bugs|features)(\/threads)?$/);+ if (forum && !forum[2]) return Response.json({ available_tags: tags[forum[1] as "bugs"] });+ if (forum) {+ calls.push(`post ${forum[1]} "${body.name}" ${body.applied_tags} ${body.message.content.split("\n")[0]}`);+ return Response.json({ id: `t${body.name.match(/#(\d+)/)[1]}` });+ }+ const thread = url.match(/\/channels\/(t\d+)(\/messages)?$/);+ if (thread?.[2]) { calls.push(`say ${thread[1]} ${body.content}`); return Response.json({}); }+ if (thread && method === "GET") return Response.json({ applied_tags: threadTags });+ if (thread && method === "PATCH") { threadTags = body.applied_tags; calls.push(`set ${thread[1]} [${body.applied_tags}] archived=${body.archived}`); return Response.json({}); }+ if (url.includes("/guilds/")) throw new Error("no roles for unlinked accounts");+ throw new Error(`unexpected ${method} ${url}`);+}) as typeof fetch;++const hook = async (action: string, issue: object) => {+ const body = JSON.stringify({ action, issue });+ const res = await worker.fetch(new Request("https://discord.test/webhook", {+ method: "POST", body, headers: { "X-GitHub-Event": "issues", "X-Hub-Signature-256": `sha256=${await sign("hook", body)}` },+ }), env);+ return res.status;+};+const issue = (number: number, title: string, extra: object = {}) => ({+ number, title, body: "<!-- template -->\nSteps to reproduce", html_url: `https://github.com/leepokai/Codync/issues/${number}`,+ labels: [], user: { id: 9, login: "octo" }, ...extra,+});++// Opened: one post in the matching forum, tagged GitHub; a redelivery doesn't post again.+const feature = issue(7, "[Feature] Android app");+assert.equal(await hook("opened", feature), 204);+assert.equal(await hook("opened", feature), 204);+assert.deepEqual(calls, ['post features "#7 [Feature] Android app" gh-f Opened on GitHub by octo: <https://github.com/leepokai/Codync/issues/7>']);+assert.deepEqual(JSON.parse(links.get("issue:7")!), { kind: "feature", thread: "t7" });++// Closed as completed: said in the thread, Shipped added, closed; reopened: said, Shipped removed, open again.+calls = []; threadTags = ["gh-f"];+assert.equal(await hook("closed", { ...feature, state_reason: "completed" }), 204);+assert.equal(await hook("reopened", feature), 204);+assert.deepEqual(calls, [+ "say t7 ✅ Closed as completed on GitHub: <https://github.com/leepokai/Codync/issues/7>",+ "set t7 [gh-f,shipped] archived=true",+ "say t7 🔄 Reopened on GitHub: <https://github.com/leepokai/Codync/issues/7>",+ "set t7 [gh-f] archived=false",+]);+calls = [];+assert.equal(await hook("closed", { ...feature, state_reason: "not_planned" }), 204);+assert.deepEqual(calls, ["say t7 Closed as not planned on GitHub: <https://github.com/leepokai/Codync/issues/7>", "set t7 [gh-f] archived=true"]);++// Daily run: open issues without a post get one (an `enhancement` label counts as a feature); pull requests don't.+calls = [];+open = [feature, issue(8, "Crash on launch"), issue(9, "Custom icons", { labels: [{ name: "enhancement" }] }), issue(10, "A PR", { pull_request: {} })];+await worker.scheduled({} as ScheduledController, env);+assert.deepEqual(calls.map((c) => c.split(" Opened")[0]), ['post bugs "#8 Crash on launch" gh-b', 'post features "#9 Custom icons" gh-f']);+console.log("issue tests ok");diff --git a/discord/wrangler.toml b/discord/wrangler.tomlindex 60293f3e..3b5225db 100644--- a/discord/wrangler.toml+++ b/discord/wrangler.toml@@ -3,7 +3,7 @@ main = "src/index.ts"compatibility_date = "2026-09-01"routes = [{ pattern = "discord.codync.dev", custom_domain = true }]-# Daily download count for the #milestones posts (01:00 UTC, 09:00 in Taiwan).+# Daily (01:00 UTC, 09:00 in Taiwan): download count for #milestones, forum posts for open issues missing one.[triggers]crons = ["0 1 * * *"]@@ -17,6 +17,8 @@ CONTRIBUTOR_ROLE_ID = "1559453466894663680"REPORTER_ROLE_ID = "1559885097535148133"STAFF_CHANNEL_ID = "1559451211860672512"MILESTONES_CHANNEL_ID = "1560254402168758403"+BUG_FORUM_ID = "1559834539004661760"+FEATURE_FORUM_ID = "1559451567143387237"STAR_GOAL = "1000"DOWNLOAD_GOAL = "10000"REPO = "leepokai/Codync"