From 810537eaf9eab7ce55c16aca6925bd16b89d93d7 Mon Sep 17 00:00:00 2001 From: TripleU <182648541+TripleU613@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:47:00 -0500 Subject: [PATCH] =?UTF-8?q?Discord=20chat:=20a=20starboard=20for=20message?= =?UTF-8?q?s=20that=20collect=20enough=20=E2=AD=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every 2 minutes the forum reads the last 50 messages of each channel listed in discord_chat_starboard_channels and reposts, once, any that reached discord_chat_starboard_threshold ⭐ (3 by default) into discord_chat_starboard_channel_id: author, text, first image and a link back, pinging nobody. Only listed channels are read, so a starred message in a private channel the bot can see never reaches members. Bot messages and messages older than 7 days are skipped. Off until a starboard channel is set. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BUGDaR7qv2d8CuVp7UGSTs --- app/jobs/scheduled/discord_chat_starboard.rb | 20 +++++ config/locales/server.en.yml | 14 +++ config/settings.yml | 19 ++++ docs/features/discord-chat.md | 9 ++ lib/discourse_discord_chat/starboard.rb | 89 +++++++++++++++++++ .../discourse_discord_chat/starboard_spec.rb | 83 +++++++++++++++++ sub_plugins/discord_chat.rb | 1 + 7 files changed, 235 insertions(+) create mode 100644 app/jobs/scheduled/discord_chat_starboard.rb create mode 100644 lib/discourse_discord_chat/starboard.rb create mode 100644 spec/lib/discourse_discord_chat/starboard_spec.rb diff --git a/app/jobs/scheduled/discord_chat_starboard.rb b/app/jobs/scheduled/discord_chat_starboard.rb new file mode 100644 index 00000000..34fd052a --- /dev/null +++ b/app/jobs/scheduled/discord_chat_starboard.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true + +module Jobs + # Looks for newly starred messages in the server's listed channels. + class DiscordChatStarboard < ::Jobs::Scheduled + every 2.minutes + + def execute(_args) + return unless DiscourseDiscordChat.configured? + return if SiteSetting.discord_chat_starboard_channel_id.to_s.strip.blank? + DistributedMutex.synchronize("discord_chat_starboard", validity: 2.minutes) do + DiscourseDiscordChat::Starboard.new.run + end + rescue DiscourseDiscordChat::Api::RateLimited + nil + rescue DiscourseDiscordChat::Api::Error => e + Rails.logger.warn("#{DiscourseDiscordChat::LOG_TAG} starboard: #{e.message}") + end + end +end diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml index 8bd75789..51b005a7 100644 --- a/config/locales/server.en.yml +++ b/config/locales/server.en.yml @@ -191,6 +191,20 @@ en: welcomed, 10 a minute at most; anyone with direct messages closed is skipped and not tried again. + discord_chat_starboard_channel_id: ID of the Discord channel that starred + messages are reposted to (make it read-only for members). Leave blank + to turn the starboard off. Needs the Message Content intent on the bot + (Developer Portal → Bot) so the reposts carry the text. + + discord_chat_starboard_channels: IDs of the Discord channels the + starboard reads. Only these are ever looked at, so list public channels + only; a starred message in a channel left off the list is never + reposted. + + discord_chat_starboard_threshold: How many ⭐ reactions a message needs to + be reposted to the starboard. Each message is reposted once; messages + older than 7 days are ignored. + jtech_lean_palettes: Send the colour palettes in every page with only the colours their previews and swatches use (primary, secondary, tertiary, selected, header background and header text) instead of all of them. diff --git a/config/settings.yml b/config/settings.yml index 91358d92..d8828513 100644 --- a/config/settings.yml +++ b/config/settings.yml @@ -1887,3 +1887,22 @@ jtech_discord_chat: client: false depends_on: - "discord_chat_enabled" + discord_chat_starboard_channel_id: + default: "" + client: false + depends_on: + - "discord_chat_enabled" + discord_chat_starboard_channels: + type: list + list_type: simple + default: "" + client: false + depends_on: + - "discord_chat_enabled" + discord_chat_starboard_threshold: + default: 3 + min: 1 + max: 100 + client: false + depends_on: + - "discord_chat_enabled" diff --git a/docs/features/discord-chat.md b/docs/features/discord-chat.md index 32c93705..6c8a1074 100644 --- a/docs/features/discord-chat.md +++ b/docs/features/discord-chat.md @@ -99,3 +99,12 @@ the chat opens for them. `{username}` becomes their forum username. Only people who joined the server in the last 7 days are welcomed, at most 10 a minute, and someone with direct messages closed is marked done rather than retried. Blank sends nothing. + +## Starboard + +Messages that get `discord_chat_starboard_threshold` ⭐ reactions (3 by default) +are reposted once to `discord_chat_starboard_channel_id`, with the author, the +text, the first image and a link back. Only the channel IDs in +`discord_chat_starboard_channels` are read, so private channels can't leak into +it; messages older than 7 days and bot messages are skipped. The forum checks +every 2 minutes. The bot needs the Message Content intent for the text. diff --git a/lib/discourse_discord_chat/starboard.rb b/lib/discourse_discord_chat/starboard.rb new file mode 100644 index 00000000..53104662 --- /dev/null +++ b/lib/discourse_discord_chat/starboard.rb @@ -0,0 +1,89 @@ +# frozen_string_literal: true + +module DiscourseDiscordChat + # Reposts messages that collected enough ⭐ reactions into the starboard + # channel. Only the channels listed in the setting are read, so a starred + # message in a private channel the bot can see never reaches members. + class Starboard + STAR = "⭐" + LOOKBACK = 50 + MAX_AGE = 7.days + STORE = MemberSync::STORE + + def initialize(api: Api.new) + @api = api + end + + def run + target = SiteSetting.discord_chat_starboard_channel_id.to_s.strip + return if target.blank? + + sources.each do |channel_id| + next if channel_id == target + messages = @api.bot(:get, "/channels/#{channel_id}/messages", query: { limit: LOOKBACK }) + starred = Array(messages).select { |message| qualifies?(message) } + next if starred.empty? + + keys = starred.map { |message| key(message["id"]) } + done = PluginStoreRow.where(plugin_name: STORE, key: keys).pluck(:key).to_set + starred.each do |message| + next if done.include?(key(message["id"])) + PluginStore.set(STORE, key(message["id"]), true) + @api.bot(:post, "/channels/#{target}/messages", repost(message, channel_id)) + end + end + end + + private + + def sources + SiteSetting.discord_chat_starboard_channels.to_s.split("|").map(&:strip).reject(&:blank?) + end + + def qualifies?(message) + return false if message.dig("author", "bot") + sent = Time.zone.parse(message["timestamp"].to_s) + return false if sent.nil? || sent < MAX_AGE.ago + stars(message) >= SiteSetting.discord_chat_starboard_threshold + end + + def stars(message) + reaction = Array(message["reactions"]).find { |r| r.dig("emoji", "name") == STAR } + reaction ? reaction["count"].to_i : 0 + end + + def key(message_id) + "starred_#{message_id}" + end + + def repost(message, channel_id) + guild = SiteSetting.discord_chat_guild_id.to_s.strip + link = "https://discord.com/channels/#{guild}/#{channel_id}/#{message["id"]}" + author = message["author"] || {} + embed = { + author: { + name: (author["global_name"].presence || author["username"]).to_s.truncate(256), + icon_url: avatar(author), + }.compact, + description: message["content"].to_s.truncate(4000), + timestamp: message["timestamp"], + } + image = + Array(message["attachments"]).find { |a| a["content_type"].to_s.start_with?("image/") } + embed[:image] = { url: image["url"] } if image + + { + content: "#{STAR} #{stars(message)} · <##{channel_id}> · #{link}", + embeds: [embed], + allowed_mentions: { + parse: [], + }, + } + end + + def avatar(author) + return if author["id"].blank? || author["avatar"].blank? + "https://cdn.discordapp.com/avatars/#{author["id"]}/#{author["avatar"]}.png" + end + end +end diff --git a/spec/lib/discourse_discord_chat/starboard_spec.rb b/spec/lib/discourse_discord_chat/starboard_spec.rb new file mode 100644 index 00000000..803d15ae --- /dev/null +++ b/spec/lib/discourse_discord_chat/starboard_spec.rb @@ -0,0 +1,83 @@ +# frozen_string_literal: true + +require "rails_helper" + +RSpec.describe DiscourseDiscordChat::Starboard do + let(:calls) { [] } + let(:messages) do + { + "300" => [ + message("1", stars: 3, content: "great @everyone"), + message("2", stars: 2), + message("3", stars: 5, bot: true), + message("4", stars: 9, at: 10.days.ago), + ], + "666" => [message("5", stars: 9)], + } + end + + def message(id, stars:, content: "hi", bot: false, at: 1.hour.ago) + { + "id" => id, + "content" => content, + "timestamp" => at.iso8601, + "author" => { + "id" => "41", + "username" => "moshe", + "avatar" => "abc", + "bot" => bot, + }, + "reactions" => [{ "emoji" => { "name" => "⭐" }, "count" => stars }], + } + end + + before do + SiteSetting.jtech_enabled = true + SiteSetting.discord_chat_enabled = true + SiteSetting.discord_chat_bot_token = "bot-token" + SiteSetting.discord_chat_guild_id = "7" + SiteSetting.discord_chat_starboard_channel_id = "999" + SiteSetting.discord_chat_starboard_channels = "300" + SiteSetting.discord_chat_starboard_threshold = 3 + + WebMock + .stub_request(:any, %r{\Ahttps://discord\.com/api/v10/}) + .to_return do |request| + path = request.uri.path.delete_prefix("/api/v10") + calls << [request.method, path, request.body.presence && JSON.parse(request.body)] + channel = path[%r{\A/channels/(\d+)/messages\z}, 1] + body = request.method == :get ? messages.fetch(channel, []) : {} + { status: 200, body: body.to_json, headers: { "Content-Type" => "application/json" } } + end + end + + def reposts + calls.select { |m, p, _| m == :post && p == "/channels/999/messages" }.map(&:last) + end + + it "reposts a message once it has enough stars, and only once" do + described_class.new.run + described_class.new.run + expect(reposts.size).to eq(1) + repost = reposts.first + expect(repost["content"]).to include("⭐ 3", "<#300>", "https://discord.com/channels/7/300/1") + expect(repost["embeds"].first["description"]).to eq("great @everyone") + expect(repost["allowed_mentions"]).to eq({ "parse" => [] }) + end + + it "skips bot messages, old messages and those under the threshold" do + described_class.new.run + expect(reposts.map { |r| r["content"] }).to all(include("/300/1")) + end + + it "never reads a channel that isn't listed" do + described_class.new.run + expect(calls.map { |_, p, _| p }).not_to include("/channels/666/messages") + end + + it "does nothing without a starboard channel" do + SiteSetting.discord_chat_starboard_channel_id = "" + described_class.new.run + expect(calls).to be_empty + end +end diff --git a/sub_plugins/discord_chat.rb b/sub_plugins/discord_chat.rb index 0a1bf4f2..8fecb2ab 100644 --- a/sub_plugins/discord_chat.rb +++ b/sub_plugins/discord_chat.rb @@ -40,6 +40,7 @@ def self.allowed?(user) require_relative "../lib/discourse_discord_chat/api" require_relative "../lib/discourse_discord_chat/mod_log" require_relative "../lib/discourse_discord_chat/member_sync" +require_relative "../lib/discourse_discord_chat/starboard" require_relative "../lib/discourse_discord_chat/signature" require_relative "../lib/discourse_discord_chat/commands"