From 0cf182fd77e72bce6c3103b89163e8d43087260a Mon Sep 17 00:00:00 2001 From: TripleU <182648541+TripleU613@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:37:09 -0500 Subject: [PATCH 1/2] Discord chat: a moderators' log, and timeouts that follow forum restrictions discord_chat_mod_log_channel_id posts what the forum does in the server to a moderators-only channel: who got in (with their forum username), who lost access, and timeouts set and lifted. Lines never ping anyone, and a line that fails to post is dropped rather than stopping the sync. discord_chat_sync_timeouts times a linked member out while they're suspended or silenced on the forum, capped at Discord's 28 days and renewed as it runs down. A timeout already within a day of the right end is left alone, so long suspensions aren't rewritten every minute. The forum records the timeouts it set and lifts only those; a moderator's own timeout in the server is never cleared. The server owner is skipped. Both settings default off. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BUGDaR7qv2d8CuVp7UGSTs --- config/locales/server.en.yml | 14 ++++ config/settings.yml | 10 +++ docs/features/discord-chat.md | 19 +++++ lib/discourse_discord_chat/member_sync.rb | 84 +++++++++++++++++++ lib/discourse_discord_chat/mod_log.rb | 22 +++++ .../member_sync_spec.rb | 74 ++++++++++++++++ sub_plugins/discord_chat.rb | 1 + 7 files changed, 224 insertions(+) create mode 100644 lib/discourse_discord_chat/mod_log.rb diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml index 21b8d6d8..6f2e48ff 100644 --- a/config/locales/server.en.yml +++ b/config/locales/server.en.yml @@ -162,6 +162,20 @@ en: forum, /search, /guide, /whois and /leaderboard find nothing. Turning this off removes the commands from the server. + discord_chat_mod_log_channel_id: ID of a moderators-only Discord channel + where the forum logs what it does in the server (who got in or lost + access, timeouts set and lifted, reports). Leave blank for no log. Make + sure only moderators can read it, since the bot posts whatever it is told to + log there. + + discord_chat_sync_timeouts: Time a linked member out in the Discord server + while they're suspended or silenced on the forum, and lift it when that + ends. Discord's longest timeout is 28 days, so a longer suspension is + renewed as it runs. Only timeouts the forum set are ever lifted; a + moderator's own timeout in the server is left alone. The bot's role + needs the Timeout Members permission, and can't time out anyone with a + higher role. Kicks and bans in the server don't come back to the forum. + 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 bde541c2..c66b04d1 100644 --- a/config/settings.yml +++ b/config/settings.yml @@ -1866,3 +1866,13 @@ jtech_discord_chat: client: false depends_on: - "discord_chat_enabled" + discord_chat_mod_log_channel_id: + default: "" + client: false + depends_on: + - "discord_chat_enabled" + discord_chat_sync_timeouts: + default: false + client: false + depends_on: + - "discord_chat_enabled" diff --git a/docs/features/discord-chat.md b/docs/features/discord-chat.md index 0520b3f1..13c1b5eb 100644 --- a/docs/features/discord-chat.md +++ b/docs/features/discord-chat.md @@ -61,3 +61,22 @@ from the public, so the reply never says which. Nobody is pinged by an answer. in the server (needs `discord_chat_bot_token` and `discord_chat_guild_id`). Turning it off removes them again. Changing the public key registers them again too. + +## Moderators' log + +`discord_chat_mod_log_channel_id`: a moderators-only channel where the forum +posts what it did in the server: who got in (with their forum username), who +lost access, and timeouts set and lifted. Lines never ping anyone. If a line +can't be posted it is dropped; the sync carries on. + +## Timeouts from forum restrictions + +`discord_chat_sync_timeouts`: while a linked member is suspended or silenced +on the forum, they are timed out in the server until it ends. Discord caps a +timeout at 28 days, so longer ones are renewed as they run down. The forum +remembers which timeouts it set and only ever lifts those, so a moderator's +own timeout in the server stays. The bot's role needs Timeout Members, and it +can't time out anyone ranked above it. + +This only runs forum → server. A kick or ban in the server doesn't touch the +forum account. diff --git a/lib/discourse_discord_chat/member_sync.rb b/lib/discourse_discord_chat/member_sync.rb index 9bd29178..dbf934ff 100644 --- a/lib/discourse_discord_chat/member_sync.rb +++ b/lib/discourse_discord_chat/member_sync.rb @@ -15,6 +15,18 @@ class MemberSync # the run up to the next one. MAX_WAIT = 10 + # Discord's longest timeout is 28 days; a longer forum suspension is + # covered by renewing it as it runs down. + MAX_TIMEOUT = 28.days - 1.hour + + # A timeout already this close to the one wanted is left alone, so a + # long suspension isn't rewritten on every run. + TIMEOUT_SLACK = 1.day + + # Remembers which timeouts the forum set, so a moderator's own timeout + # in the server is never lifted by the sync. + STORE = "discord_chat" + def initialize(api: Api.new, sleeper: ->(seconds) { sleep(seconds) }) @api = api @sleeper = sleeper @@ -45,11 +57,15 @@ def sync_member(member, user, owner_id:) want = allowed && tests.any? { |wanted| wanted.call(user) } if want && !has.include?(role_id) call(:put, "/guilds/#{guild_id}/members/#{discord_id}/roles/#{role_id}") + log_access(discord_id, user, granted: true) if role_id == member_role_id elsif !want && has.include?(role_id) call(:delete, "/guilds/#{guild_id}/members/#{discord_id}/roles/#{role_id}") + log_access(discord_id, user, granted: false) if role_id == member_role_id end end + sync_timeout(member, user) if discord_id != owner_id && SiteSetting.discord_chat_sync_timeouts + # Discord doesn't let anyone rename the server's owner. return if discord_id == owner_id return unless allowed && SiteSetting.discord_chat_sync_nicknames @@ -61,8 +77,76 @@ def sync_member(member, user, owner_id:) Rails.logger.warn("#{DiscourseDiscordChat::LOG_TAG} member #{discord_id}: #{e.message}") end + # A forum suspension or silence times the member out in the server for + # as long as it lasts (up to Discord's 28 days, renewed as it runs). + # Only a timeout the forum set is ever lifted. + def sync_timeout(member, user) + discord_id = member.dig("user", "id") + wanted = timeout_until(user) + current = Time.zone.parse(member["communication_disabled_until"].to_s) + current = nil if current && current <= Time.zone.now + ours = PluginStore.get(STORE, timeout_key(discord_id)).present? + + if wanted + return if current && (current - wanted).abs < TIMEOUT_SLACK + return if current && !ours && current > wanted + call( + :patch, + "/guilds/#{guild_id}/members/#{discord_id}", + { communication_disabled_until: wanted.iso8601 }, + ) + PluginStore.set(STORE, timeout_key(discord_id), true) + unless ours + ModLog.post( + "⏸️ <@#{discord_id}> (#{user.username}) timed out until #{wanted.to_date}: restricted on the forum.", + api: @api, + ) + end + elsif ours + if current + call( + :patch, + "/guilds/#{guild_id}/members/#{discord_id}", + { communication_disabled_until: nil }, + ) + ModLog.post( + "▶️ <@#{discord_id}> timeout lifted: no longer restricted on the forum.", + api: @api, + ) + end + PluginStore.remove(STORE, timeout_key(discord_id)) + end + rescue Api::RateLimited + raise + rescue Api::Error => e + Rails.logger.warn("#{DiscourseDiscordChat::LOG_TAG} timeout #{discord_id}: #{e.message}") + end + private + def timeout_until(user) + return if user.nil? + now = Time.zone.now + ends = [user.suspended_till, user.silenced_till].compact.select { |time| time > now }.max + [ends, now + MAX_TIMEOUT].min if ends + end + + def timeout_key(discord_id) + "timeout_#{discord_id}" + end + + def member_role_id + SiteSetting.discord_chat_member_role_id.to_s.strip + end + + def log_access(discord_id, user, granted:) + if granted + ModLog.post("✅ <@#{discord_id}> got in as forum user #{user.username}.", api: @api) + else + ModLog.post("⛔ <@#{discord_id}> lost access to the chat.", api: @api) + end + end + # A launch can link many people at once; a short rate limit is waited # out instead of ending the run. def call(*args, **kwargs) diff --git a/lib/discourse_discord_chat/mod_log.rb b/lib/discourse_discord_chat/mod_log.rb new file mode 100644 index 00000000..36c1bbfc --- /dev/null +++ b/lib/discourse_discord_chat/mod_log.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +module DiscourseDiscordChat + # One line per thing the forum did in the server, in the moderators' + # log channel. A line that can't be posted is dropped: the log is a + # convenience and never holds up the work it describes. + module ModLog + def self.post(text, api: Api.new) + channel = SiteSetting.discord_chat_mod_log_channel_id.to_s.strip + return if channel.blank? || !DiscourseDiscordChat.configured? + api.bot( + :post, + "/channels/#{channel}/messages", + { content: text.to_s.truncate(2000), allowed_mentions: { parse: [] } }, + ) + nil + rescue Api::Error => e + Rails.logger.warn("#{DiscourseDiscordChat::LOG_TAG} mod log: #{e.message}") + nil + end + end +end diff --git a/spec/lib/discourse_discord_chat/member_sync_spec.rb b/spec/lib/discourse_discord_chat/member_sync_spec.rb index 0da4625c..2a537ce8 100644 --- a/spec/lib/discourse_discord_chat/member_sync_spec.rb +++ b/spec/lib/discourse_discord_chat/member_sync_spec.rb @@ -213,4 +213,78 @@ def role_calls(method) expect(calls.map { |_, p, _| p }.grep(%r{/roles/90})).to be_empty end end + describe "timeouts from forum restrictions" do + before { SiteSetting.discord_chat_sync_timeouts = true } + + def timeout_calls + calls.select { |m, _, body| m == :patch && body&.key?("communication_disabled_until") } + end + + it "times a suspended member out until the suspension ends" do + freeze_time + described_class.new.run + expect(timeout_calls.map { |_, p, _| p }).to eq(["/guilds/7/members/11"]) + until_time = Time.zone.parse(timeout_calls.first[2]["communication_disabled_until"]) + expect(until_time).to be_within(1.second).of(suspended.suspended_till) + end + + it "caps the timeout at Discord's 28 days" do + freeze_time + suspended.update!(suspended_till: 1.year.from_now) + described_class.new.run + until_time = Time.zone.parse(timeout_calls.first[2]["communication_disabled_until"]) + expect(until_time).to be <= 28.days.from_now + end + + it "leaves a timeout that is already about right alone" do + members[1]["communication_disabled_until"] = (suspended.suspended_till - 1.hour).iso8601 + described_class.new.run + expect(timeout_calls).to be_empty + end + + it "lifts a timeout the forum set once the restriction ends" do + described_class.new.run + suspended.update!(suspended_till: nil, suspended_at: nil) + members[1]["communication_disabled_until"] = 3.days.from_now.iso8601 + calls.clear + described_class.new.run + expect(timeout_calls).to eq( + [[:patch, "/guilds/7/members/11", { "communication_disabled_until" => nil }]], + ) + end + + it "never lifts a moderator's own timeout in the server" do + members[0]["communication_disabled_until"] = 2.days.from_now.iso8601 + described_class.new.run + expect(timeout_calls.map { |_, p, _| p }).not_to include("/guilds/7/members/10") + end + + it "does nothing when the setting is off" do + SiteSetting.discord_chat_sync_timeouts = false + described_class.new.run + expect(timeout_calls).to be_empty + end + end + + describe "the moderators' log" do + before { SiteSetting.discord_chat_mod_log_channel_id = "555" } + + def log_lines + calls.select { |m, p, _| m == :post && p == "/channels/555/messages" }.map { |_, _, b| b } + end + + it "logs who got in and who lost access, without pinging anyone" do + described_class.new.run + texts = log_lines.map { |b| b["content"] } + expect(texts).to include(a_string_including("<@10>", "moshe")) + expect(texts).to include(a_string_including("<@11>", "lost access")) + expect(log_lines.map { |b| b["allowed_mentions"] }.uniq).to eq([{ "parse" => [] }]) + end + + it "logs nothing without a channel" do + SiteSetting.discord_chat_mod_log_channel_id = "" + described_class.new.run + expect(calls.map { |_, p, _| p }.grep(%r{/channels/})).to be_empty + end + end end diff --git a/sub_plugins/discord_chat.rb b/sub_plugins/discord_chat.rb index bc3bc8f8..f5646d5b 100644 --- a/sub_plugins/discord_chat.rb +++ b/sub_plugins/discord_chat.rb @@ -34,6 +34,7 @@ def self.allowed?(user) end 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/signature" require_relative "../lib/discourse_discord_chat/commands" From 450a6776844da1a02c8362ecfc075db6b0b8ef72 Mon Sep 17 00:00:00 2001 From: TripleU <182648541+TripleU613@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:46:06 -0500 Subject: [PATCH 2/2] Specs: blank line between example groups Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BUGDaR7qv2d8CuVp7UGSTs --- spec/lib/discourse_discord_chat/member_sync_spec.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/spec/lib/discourse_discord_chat/member_sync_spec.rb b/spec/lib/discourse_discord_chat/member_sync_spec.rb index 2a537ce8..cdec9153 100644 --- a/spec/lib/discourse_discord_chat/member_sync_spec.rb +++ b/spec/lib/discourse_discord_chat/member_sync_spec.rb @@ -213,6 +213,7 @@ def role_calls(method) expect(calls.map { |_, p, _| p }.grep(%r{/roles/90})).to be_empty end end + describe "timeouts from forum restrictions" do before { SiteSetting.discord_chat_sync_timeouts = true }