Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions config/locales/server.en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 10 additions & 0 deletions config/settings.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
19 changes: 19 additions & 0 deletions docs/features/discord-chat.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
84 changes: 84 additions & 0 deletions lib/discourse_discord_chat/member_sync.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear or validate markers when timeout syncing is disabled

If an admin disables this setting after the forum has set a timeout, this guard prevents the stored ours marker from ever being cleaned up. If the forum restriction is then lifted, a Discord moderator applies a new manual timeout, and syncing is re-enabled, the stale marker makes the elsif ours branch clear the moderator's timeout, contradicting the guarantee that manually applied Discord timeouts are left alone; remove markers when disabling the setting or store enough state to verify that the current timeout is still the forum-created one.

Useful? React with 👍 / 👎.


# Discord doesn't let anyone rename the server's owner.
return if discord_id == owner_id
return unless allowed && SiteSetting.discord_chat_sync_nicknames
Expand All @@ -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?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preload timeout ownership before iterating members

When timeout syncing is enabled, every non-bot guild member reaches this PluginStore.get, which performs a separate database query even for members without a forum restriction. Because the scheduled job runs every minute, a guild with hundreds or thousands of members produces the same number of avoidable reads on every run; load the ownership keys in one query before entering members.each.

AGENTS.md reference: AGENTS.md:L24-L24

Useful? React with 👍 / 👎.


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)
Expand Down
22 changes: 22 additions & 0 deletions lib/discourse_discord_chat/mod_log.rb
Original file line number Diff line number Diff line change
@@ -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}")
Comment on lines +17 to +18

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Isolate transport failures from the member sync

When posting the optional log line encounters a network failure such as Net::ReadTimeout, Net::OpenTimeout, or SocketError, Api#bot propagates it because these exceptions are not Api::Error. This rescue therefore does not drop the failed line as documented: the exception escapes both sync_member and the scheduled job, aborting processing of all remaining members for that run. Rescue the expected transport exceptions here so logging cannot hold up synchronization.

Useful? React with 👍 / 👎.

nil
end
end
end
75 changes: 75 additions & 0 deletions spec/lib/discourse_discord_chat/member_sync_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -213,4 +213,79 @@ 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
1 change: 1 addition & 0 deletions sub_plugins/discord_chat.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading