Discourse GitHub

:discourse2: Summary Discourse GitHub Allows staff to assign badges to users based on GitHub contributions. Also allows users to create Github Linkbacks, Permalinks, and display live PR status on oneboxes.
:open_book: Install Guide This plugin is bundled with Discourse core. There is no need to install the plugin separately.

Features

GitHub Badges

Assign badges to your users based on GitHub contributions.

How to use:
  1. Enable github badges enabled in Settings → Plugins.
  2. Generate a GitHub access token and paste it into the github linkback access token setting. See below for instructions.
  3. Add one or more URLs of the GitHub repos to scan for contributions to the github badges repos site setting.
How badge counting works:

Badges count commits across all repositories, and when a user contributes to multiple repos, all their commits are added together into one total count.

Committer Badges:

Badge Commits Required
Bronze 1 commit
Silver 25 commits
Gold 1000 commits

Badge Progression: As users accumulate more contributions across any of the tracked repositories, they automatically progress through badge tiers. For example, if a user commits to Repo A and then Repo B, both contributions count toward their total, allowing them to progress from Bronze to Silver to Gold.


GitHub Linkback

Create a link from a GitHub pull request or commit back to a Discourse post where it is mentioned.

How to use:
  1. Enable github linkback enabled in Settings → Plugins.
  2. Generate a GitHub access token and paste it into the github linkback access token setting. See below for instructions.
  3. Finally, add the projects you wish to post to in the github linkback projects site setting in the formats:
    • username/repository for specific repositories
    • username/* for all repositories of a certain user

GitHub Permalink

Replace GitHub non-permalinks with permalinks.

How to use:
  1. Enable github permalinks enabled in Settings → Plugins.

PR Live Status

Display live status indicators on GitHub pull request oneboxes in posts and chat messages. The status updates automatically via webhooks when PRs change on GitHub.

Status Types
Status Color Description
Draft Gray PR is marked as draft
Open Gray PR is open and awaiting review
Approved Green PR has been approved by reviewers
Changes Requested Orange Reviewers have requested changes
Merged Purple PR has been merged
Closed Red PR was closed without merging
How to use:
Step 1: Enable the Feature

Go to Admin > Settings > Plugins and set github pr status enabled to true.

Step 2: Configure GitHub Access Tokens

To fetch PR status (especially for private repositories), configure GitHub access tokens.

Setting: github onebox access tokens

Format:

organization_name|ghp_your_token_here
default|ghp_fallback_token_here

You can specify tokens per organization, plus a default token used as a fallback. Each line should contain org_name|token where the token is a GitHub Personal Access Token (classic) with repo scope.

Example:

discourse|ghp_xxxxxxxxxxxxxxxxxxxx
my-company|ghp_yyyyyyyyyyyyyyyyyyyy
default|ghp_zzzzzzzzzzzzzzzzzzzzzz
Step 3: Set Up GitHub Webhooks (for Real-Time Updates)

To get automatic status updates when PRs change, configure a webhook on GitHub.

Generate a Webhook Secret:

openssl rand -hex 32

Set the github webhook secret site setting to your generated secret.

Create the Webhook on GitHub:

You can create the webhook at the organization level (to cover all repos) or per-repository.

For an organization:

  1. Go to your organization’s Settings
  2. Navigate to Webhooks (under Code, planning, and automation)
  3. Click Add webhook

For a repository:

  1. Go to your repository’s Settings
  2. Navigate to Webhooks
  3. Click Add webhook

Webhook Configuration:

Field Value
Payload URL https://your-discourse-site.com/discourse-github/webhooks/github
Content type application/json
Secret Your generated webhook secret
SSL verification Enable (recommended)
Events Select “Let me select individual events”

Select these events:

  • Pull requests
  • Pull request reviews

Click Add webhook to save.

Step 4: Verify the Setup
  1. Create a test post with a GitHub PR URL
  2. Verify the onebox displays with a status icon
  3. Change the PR status on GitHub (e.g., approve it, or close it)
  4. Within a few seconds, refresh the Discourse page — the status should update

You can check the webhook delivery status in GitHub’s webhook settings to confirm events are being sent and received successfully.

Status Priority

When a PR has multiple states (e.g., approved but also has changes requested), the status is determined by this priority:

  1. Merged (highest priority)
  2. Closed
  3. Draft
  4. Changes Requested
  5. Approved
  6. Open (default)
Review Status Logic

The feature fetches review information from the GitHub API to determine approval status:

  • Takes the latest review from each reviewer
  • Ignores “commented” and “pending” review states
  • Shows “changes requested” if any reviewer has requested changes
  • Shows “approved” only if reviews exist and none request changes
Where It Works
  • Forum posts — Any post containing a GitHub PR onebox
  • Chat messages — PR oneboxes in chat also display live status

Note: Inline oneboxes (when a link appears inline in text rather than as a full preview) do not display status icons.

Migrating from GitHub Status Theme Component

This feature replaces the GitHub Status Indicators theme component. The two are not compatible and should not be used together.

If you’re currently using the theme component:

  1. Disable and remove the github-status-theme theme component
  2. Enable this built-in feature via the github pr status enabled setting

Configuration

GitHub Access Token

In order for the linkback feature to work and the badges to be granted to your users, you need to provide a GitHub access token. You can generate your token here: Sign in to GitHub · GitHub.

The linkback feature requires the public_repo scope, and granting badges requires no scope (leave everything unchecked if you only want badges). Since the public_repo scope grants write access to repositories, we recommend you create a throwaway GitHub account that has access to no repositories and use it just to generate a token.

Token Scopes by Feature

Feature Required Scope
Badges No scope required
Linkback public_repo
PR Status (public repos) No scope required
PR Status (private repos) repo

Site Settings Reference

Setting Default Description
enable discourse github plugin false Master switch for the plugin
github badges enabled false Enable GitHub contribution badges
github badges repos (empty) Repository URLs to track for badges
github linkback enabled false Enable linkbacks from GitHub to Discourse
github linkback access token (empty) Access token for linkback feature
github linkback projects (empty) Projects to create linkbacks for
github permalinks enabled false Replace GitHub links with permalinks
github pr status enabled false Enable PR status icons on oneboxes
github webhook secret (empty) Secret for webhook signature verification
github onebox access tokens (empty) Access tokens for GitHub API (format: org|token)

Technical Details

PR Status API Usage

When a GitHub PR onebox is generated, Discourse makes up to two API calls:

  1. PR Data: GET /repos/{owner}/{repo}/pulls/{number} — Fetches basic PR information including state, merged status, and draft status
  2. Reviews: GET /repos/{owner}/{repo}/pulls/{number}/reviews — Fetches review data to determine approval status

These calls use your configured access token if available, allowing access to private repositories.

Webhook Security

Webhook requests are verified using HMAC-SHA256 signature validation. GitHub signs the webhook payload with your secret, and Discourse verifies this signature before processing. Invalid signatures are rejected with a 403 response.

Webhook Events That Trigger Updates

  • PR state changes (opened, closed, reopened)
  • PR merged
  • Draft status changes (converted to draft, ready for review)
  • Pull request reviews submitted
  • Reviews edited or dismissed

Performance Considerations

  • Rebaking is queued as a low-priority background job to avoid impacting site performance
  • Only posts/messages with full GitHub PR oneboxes are rebaked (inline oneboxes are skipped)
  • Chat message rebakes skip notifications to prevent duplicate alerts

CHANGELOG

2025-12-10

  • FIX: Skip notifications when rebaking chat messages from GitHub webhooks

2025-12-09

  • FIX: Skip rebaking posts with inline GitHub PR oneboxes
  • FIX: Avoid intermediate state when rebaking posts with oneboxes
  • FIX: Rebake chat messages when GitHub PR status changes
  • UX: Use min-height to prevent layout shift when the status icon changes
  • UX: Reduce GitHub PR status icon size on mobile

2025-12-08

  • FEATURE: Add “changes requested” status to GitHub PR oneboxes

2025-12-04

  • FEATURE: GitHub PR live status icon

2025-11-10

  • FEATURE: Allow and denylist for linkbacks

2025-11-08

  • FEATURE: Add category ignore list for GitHub linkbacks

2024-12-20

  • DEV: Move discourse-github to core (no longer requires separate installation)

Last edited by @zogstrip 2025-12-10T13:26:48Z

Check documentPerform check on document:
33 лайка

Каков процесс для нескольких ссылок? Просто добавляет их в тот же комментарий к коммиту или создаёт новый комментарий каждый раз?

1 лайк

Интересно, можно ли упростить бейджи коммитов и PR, ведь мы стараемся избегать парадокса выбора :slight_smile:

Сейчас я просто сделал форк и удалил бейджи коммитов, но, конечно, я потерял связь с бейджем коммитов (потому что делаю коммиты напрямую), а форк — это не то же самое, что всегда оставаться в тесной связке с ядром проекта.

Подстановочный знак * не сработал для меня в случае организации GitHub, в итоге я добавил каждый репозиторий вручную. У кого-нибудь еще возникали проблемы с этим при работе с организацией, а не с пользователем?

Как установить язык комментария обратной ссылки?

Спасибо, мне очень нравится этот плагин! Я был сбит с толку системой значков, но рад, что нашел объяснение в другой теме: Github Badges are not working. Its hard to see if I do something wrong or if the plugin is not working - #4 by simon

Однако в том ответе отмечается, что

Плагин создает 6 значков:

Я не вижу ни одного из этих значков, не уверен, что произошло? Есть ли способ (повторно) запустить создание этих значков?

1 лайк

Чтобы ответить на свой собственный вопрос: через несколько часов запланированная задача выполнилась, и именно тогда были созданы значки.

Ручной способ сделать это, похоже, — запустить задачу Sidekiq.

1 лайк

Запрос функции: исключение категорий и/или тегов из обратных ссылок

У нас есть категория Announcements, в которую плагин RSS автоматически подтягивает новые релизы с GitHub. Когда в примечаниях к релизу есть ссылки на задачи, эта ссылка также появляется в Discourse, и создается обратная ссылка, но она никому не полезна и создает беспорядок на GitHub.

Я хотел бы иметь возможность исключать определенные сообщения, то есть категории или теги, или даже просто сообщения от пользователя, настроенного в плагине RSS, из создания обратных ссылок.

:partying_face: Этот плагин теперь включён в ядро Discourse в рамках Bundling more popular plugins with Discourse core. Если вы размещаете Discourse самостоятельно и используете этот плагин, вам нужно удалить его из файла app.yml перед следующим обновлением.