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/3] 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/3] 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 } From 58293fe0575c3b4879a4e4d9cf6ee1b7a6bc93d5 Mon Sep 17 00:00:00 2001 From: TripleU <182648541+TripleU613@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:38:41 -0500 Subject: [PATCH 3/3] Discord chat: "Report to moderators" on any message in the server MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit discord_chat_reports_enabled registers a message command, so right-clicking or long-pressing a message → Apps → "Report to moderators" sends it to the moderators. The reporter gets a private "Sent" reply at once; a job posts the report to the moderators' log channel and messages the forum's moderators group with the reporter and author (and their forum accounts when linked), a link to the message and its text. The reported text is untrusted: on the forum it goes in a plain code block with its own fences defused, accounts are shown as profile links rather than @mentions, and the log line pings nobody. Only reports from the configured server are taken, 5 per member per hour. It works whether or not the slash commands are on; the registered list now comes from Commands.definitions. Off by default. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BUGDaR7qv2d8CuVp7UGSTs --- .../regular/discord_chat_register_commands.rb | 9 +-- app/jobs/regular/discord_chat_report.rb | 65 ++++++++++++++++ config/locales/server.en.yml | 8 ++ config/settings.yml | 5 ++ docs/features/discord-chat.md | 11 +++ lib/discourse_discord_chat/commands.rb | 58 +++++++++++++- .../discord_chat_register_commands_spec.rb | 7 ++ spec/jobs/discord_chat_report_spec.rb | 70 +++++++++++++++++ .../discourse_discord_chat/commands_spec.rb | 75 +++++++++++++++++++ sub_plugins/discord_chat.rb | 10 ++- 10 files changed, 308 insertions(+), 10 deletions(-) create mode 100644 app/jobs/regular/discord_chat_report.rb create mode 100644 spec/jobs/discord_chat_report_spec.rb diff --git a/app/jobs/regular/discord_chat_register_commands.rb b/app/jobs/regular/discord_chat_register_commands.rb index 8d891a2b..a1dc3ba7 100644 --- a/app/jobs/regular/discord_chat_register_commands.rb +++ b/app/jobs/regular/discord_chat_register_commands.rb @@ -17,14 +17,7 @@ def execute(_args) end guild_id = SiteSetting.discord_chat_guild_id.to_s.strip - commands = - ( - if SiteSetting.discord_chat_commands_enabled - DiscourseDiscordChat::Commands::DEFINITIONS - else - [] - end - ) + commands = DiscourseDiscordChat::Commands.definitions DiscourseDiscordChat::Api.new.bot( :put, diff --git a/app/jobs/regular/discord_chat_report.rb b/app/jobs/regular/discord_chat_report.rb new file mode 100644 index 00000000..d4439d39 --- /dev/null +++ b/app/jobs/regular/discord_chat_report.rb @@ -0,0 +1,65 @@ +# frozen_string_literal: true + +module Jobs + # A message reported in the Discord server: a line in the moderators' log + # there, and a message to the forum's moderators group, where moderators + # already work. The reported text is untrusted, so it goes in as a code + # block on the forum (no mentions, links or formatting) and pings nobody + # in the server. + class DiscordChatReport < ::Jobs::Base + def execute(args) + return if !DiscourseDiscordChat.configured? || !DiscourseDiscordChat.reports_enabled? + + guild = SiteSetting.discord_chat_guild_id.to_s.strip + link = "https://discord.com/channels/#{guild}/#{args[:channel_id]}/#{args[:message_id]}" + content = args[:content].to_s + + DiscourseDiscordChat::ModLog.post( + "🚩 <@#{args[:reporter_id]}> reported a message by <@#{args[:author_id]}> in <##{args[:channel_id]}>: #{link}\n" + + content.lines.first(10).map { |line| "> #{line.chomp}" }.join("\n"), + ) + + moderators = Group.find_by(id: Group::AUTO_GROUPS[:moderators]) + return if moderators.nil? + + PostCreator.create!( + Discourse.system_user, + title: "Server report: a message by #{plain(args[:author_name])}", + raw: forum_body(args, link, content), + archetype: Archetype.private_message, + target_group_names: [moderators.name], + skip_validations: true, + ) + end + + private + + def forum_body(args, link, content) + fence = "~~~~" + <<~MD + A message in the JTech server was reported. + + - **Reported by:** #{who(args[:reporter_id], args[:reporter_name])} + - **Written by:** #{who(args[:author_id], args[:author_name])} + - **Message:** #{link} + + #{fence}text + #{content.gsub(/~{3,}/, "~~")} + #{fence} + MD + end + + # The server name, plus the forum account when it's linked, as a profile + # link rather than an @mention so nobody is notified. + def who(discord_id, discord_name) + user = + UserAssociatedAccount.find_by(provider_name: "discord", provider_uid: discord_id.to_s)&.user + name = plain(discord_name) + user ? "#{name} (forum: [#{user.username}](#{user.full_url}))" : "#{name} (not linked)" + end + + def plain(text) + text.to_s.gsub(/[^\w.\- ]/, "").strip.truncate(40).presence || "unknown" + end + end +end diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml index 6f2e48ff..5a32fc15 100644 --- a/config/locales/server.en.yml +++ b/config/locales/server.en.yml @@ -176,6 +176,14 @@ en: 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. + discord_chat_reports_enabled: Add "Report to moderators" to the Discord + server's message menu (right-click or long-press a message, then Apps). + A report goes to the moderators' log channel and, as a message, to the + forum's moderators group, with a link to the reported message and its + text quoted as plain text. The reporter gets a private "Sent" reply. + Each member can send 5 reports an hour. Needs the Interactions Endpoint + URL and public key set up as for the slash commands. + 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 c66b04d1..a1e37a7d 100644 --- a/config/settings.yml +++ b/config/settings.yml @@ -1876,3 +1876,8 @@ jtech_discord_chat: client: false depends_on: - "discord_chat_enabled" + discord_chat_reports_enabled: + default: false + client: false + depends_on: + - "discord_chat_enabled" diff --git a/docs/features/discord-chat.md b/docs/features/discord-chat.md index 13c1b5eb..dd7331c9 100644 --- a/docs/features/discord-chat.md +++ b/docs/features/discord-chat.md @@ -80,3 +80,14 @@ 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. + +## Report to moderators + +`discord_chat_reports_enabled` adds "Report to moderators" to the server's +message menu (right-click or long-press a message → Apps). The reporter gets a +private "Sent to the moderators" reply; the report goes to the moderators' log +channel and, as a message, to the forum's moderators group with the reporter, +the author (with their forum accounts when linked), a link to the message and +its text as a plain code block. Nobody is pinged or @mentioned. Each member can +send 5 reports an hour, and only reports from the configured server are taken. +It works whether or not the slash commands are on. diff --git a/lib/discourse_discord_chat/commands.rb b/lib/discourse_discord_chat/commands.rb index 9c044d25..30541c64 100644 --- a/lib/discourse_discord_chat/commands.rb +++ b/lib/discourse_discord_chat/commands.rb @@ -16,6 +16,7 @@ module Commands EPHEMERAL = 64 ANSWER_DELAY = 2.seconds CHAT_INPUT = 1 + MESSAGE_COMMAND = 3 STRING = 3 USER = 6 @@ -25,6 +26,13 @@ module Commands NOT_LINKED = "Not linked to a JTech account." + REPORT = "Report to moderators" + REPORTS_PER_HOUR = 5 + REPORT_LENGTH = 1500 + + # Right-click a message → Apps. Message commands take no description. + REPORT_DEFINITION = { name: REPORT, type: MESSAGE_COMMAND }.freeze + DEFINITIONS = [ { name: "search", @@ -50,6 +58,14 @@ module Commands { name: "leaderboard", type: CHAT_INPUT, description: "Top members on the forum" }, ].freeze + # What the server's command list should hold right now. + def self.definitions + list = [] + list.concat(DEFINITIONS) if SiteSetting.discord_chat_commands_enabled + list << REPORT_DEFINITION if SiteSetting.discord_chat_reports_enabled + list + end + def self.respond(interaction) case interaction["type"] when PING @@ -62,9 +78,10 @@ def self.respond(interaction) end def self.command(interaction) + data = interaction["data"].is_a?(Hash) ? interaction["data"] : {} + return report(interaction, data) if data["type"] == MESSAGE_COMMAND && data["name"] == REPORT return reply("Commands are off.", ephemeral: true) if !DiscourseDiscordChat.commands_enabled? - data = interaction["data"].is_a?(Hash) ? interaction["data"] : {} case data["name"] when "search" defer("search", option(data, "query"), interaction) @@ -81,6 +98,45 @@ def self.command(interaction) end end + # Takes the reported message as Discord resolved it, answers the reporter + # straight away (only they see it), and leaves the posting to a job. + def self.report(interaction, data) + return reply("Reports are off.", ephemeral: true) if !DiscourseDiscordChat.reports_enabled? + if interaction["guild_id"].to_s != SiteSetting.discord_chat_guild_id.to_s.strip + return reply("Reports only work in the JTech server.", ephemeral: true) + end + + message = data.dig("resolved", "messages", data["target_id"].to_s) + reporter = interaction.dig("member", "user") + if !message.is_a?(Hash) || !reporter.is_a?(Hash) + return reply("That message can't be reported.", ephemeral: true) + end + + begin + RateLimiter.new( + nil, + "discord_chat_report_#{reporter["id"]}", + REPORTS_PER_HOUR, + 1.hour, + ).performed! + rescue RateLimiter::LimitExceeded + return reply("That's a lot of reports. Try again in a while.", ephemeral: true) + end + + author = message["author"].is_a?(Hash) ? message["author"] : {} + Jobs.enqueue( + :discord_chat_report, + reporter_id: reporter["id"].to_s, + reporter_name: reporter["username"].to_s, + author_id: author["id"].to_s, + author_name: author["username"].to_s, + channel_id: (message["channel_id"] || interaction["channel_id"]).to_s, + message_id: message["id"].to_s, + content: message["content"].to_s.truncate(REPORT_LENGTH), + ) + reply("Sent to the moderators. Thanks.", ephemeral: true) + end + # Search can take longer than the 3 seconds Discord waits for an answer, # so it runs in a job that edits the "thinking" message afterwards. The # job waits a moment: run straight away it reached Discord before this diff --git a/spec/jobs/discord_chat_register_commands_spec.rb b/spec/jobs/discord_chat_register_commands_spec.rb index 7b09dd16..a57a46af 100644 --- a/spec/jobs/discord_chat_register_commands_spec.rb +++ b/spec/jobs/discord_chat_register_commands_spec.rb @@ -52,6 +52,13 @@ expect(whois["options"].first).to include("name" => "user", "type" => 6, "required" => true) end + it "adds the message menu's report entry when reports are on" do + SiteSetting.discord_chat_commands_enabled = false + SiteSetting.discord_chat_reports_enabled = true + described_class.new.execute({}) + expect(calls.first[:body]).to eq([{ "name" => "Report to moderators", "type" => 3 }]) + end + it "empties the server's command list when commands are off" do SiteSetting.discord_chat_commands_enabled = false described_class.new.execute({}) diff --git a/spec/jobs/discord_chat_report_spec.rb b/spec/jobs/discord_chat_report_spec.rb new file mode 100644 index 00000000..eb647ffd --- /dev/null +++ b/spec/jobs/discord_chat_report_spec.rb @@ -0,0 +1,70 @@ +# frozen_string_literal: true + +require "rails_helper" + +RSpec.describe Jobs::DiscordChatReport do + fab!(:reporter) { Fabricate(:user, username: "helper_forum") } + fab!(:moderator) + + let(:calls) { [] } + let(:args) do + { + reporter_id: "40", + reporter_name: "helper", + author_id: "41", + author_name: "troll", + channel_id: "300", + message_id: "900", + content: "hey @#{moderator.username} look ~~~ [link](https://evil.example)", + } + 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_reports_enabled = true + SiteSetting.discord_chat_mod_log_channel_id = "555" + UserAssociatedAccount.create!(provider_name: "discord", provider_uid: "40", user: reporter) + + WebMock + .stub_request(:any, %r{\Ahttps://discord\.com/api/v10/}) + .to_return do |request| + calls << [request.uri.path.delete_prefix("/api/v10"), JSON.parse(request.body)] + { status: 200, body: "{}", headers: { "Content-Type" => "application/json" } } + end + end + + it "messages the forum's moderators group with the text as a plain code block" do + expect { described_class.new.execute(args) }.to change { Topic.private_messages.count }.by(1) + topic = Topic.private_messages.last + expect(topic.allowed_groups.map(&:id)).to eq([Group::AUTO_GROUPS[:moderators]]) + raw = topic.first_post.raw + expect(raw).to include("https://discord.com/channels/7/300/900") + expect(raw).to include("[helper_forum](#{reporter.full_url})") + expect(raw).to include("troll (not linked)") + expect(raw).to match(/~~~~text\n.*look ~~ \[link\]/m) + expect(topic.first_post.cooked).not_to include("mention") + end + + it "notifies nobody by name" do + expect { described_class.new.execute(args) }.not_to change { + Notification.where(user: moderator, notification_type: Notification.types[:mentioned]).count + } + end + + it "logs the report in the server without pinging anyone" do + described_class.new.execute(args) + path, body = calls.find { |p, _| p == "/channels/555/messages" } + expect(path).to be_present + expect(body["content"]).to include("<@40>", "<@41>", "<#300>", "> hey") + expect(body["allowed_mentions"]).to eq({ "parse" => [] }) + end + + it "does nothing while reports are off" do + SiteSetting.discord_chat_reports_enabled = false + expect { described_class.new.execute(args) }.not_to change { Topic.count } + expect(calls).to be_empty + end +end diff --git a/spec/lib/discourse_discord_chat/commands_spec.rb b/spec/lib/discourse_discord_chat/commands_spec.rb index 181d46a7..5e95179c 100644 --- a/spec/lib/discourse_discord_chat/commands_spec.rb +++ b/spec/lib/discourse_discord_chat/commands_spec.rb @@ -174,4 +174,79 @@ def link_for(topic) expect(described_class.leaderboard).to eq("Leaderboard: <#{url}>") end end + + describe "Report to moderators" do + before do + SiteSetting.discord_chat_guild_id = "7" + SiteSetting.discord_chat_reports_enabled = true + end + + def report(guild_id: "7", message: nil) + message ||= { + "id" => "900", + "channel_id" => "300", + "content" => "something nasty @everyone", + "author" => { + "id" => "41", + "username" => "troll", + }, + } + described_class.respond( + { + "type" => 2, + "guild_id" => guild_id, + "channel_id" => "300", + "member" => { + "user" => { + "id" => "40", + "username" => "helper", + }, + }, + "data" => { + "type" => 3, + "name" => "Report to moderators", + "target_id" => "900", + "resolved" => { + "messages" => { + "900" => message, + }, + }, + }, + }, + ) + end + + it "answers only the reporter, and queues the report" do + expect_enqueued_with( + job: :discord_chat_report, + args: { + reporter_id: "40", + author_id: "41", + channel_id: "300", + message_id: "900", + content: "something nasty @everyone", + }, + ) do + response = report + expect(response[:data][:flags]).to eq(described_class::EPHEMERAL) + expect(response[:data][:content]).to eq("Sent to the moderators. Thanks.") + end + end + + it "works with the slash commands off" do + SiteSetting.discord_chat_commands_enabled = false + expect(report[:data][:content]).to eq("Sent to the moderators. Thanks.") + end + + it "takes nothing from another server" do + expect { report(guild_id: "8") }.not_to change { Jobs::DiscordChatReport.jobs.size } + end + + it "takes nothing while reports are off" do + SiteSetting.discord_chat_reports_enabled = false + response = report + expect(response[:data][:content]).to eq("Reports are off.") + expect(Jobs::DiscordChatReport.jobs).to be_empty + end + end end diff --git a/sub_plugins/discord_chat.rb b/sub_plugins/discord_chat.rb index f5646d5b..0a1bf4f2 100644 --- a/sub_plugins/discord_chat.rb +++ b/sub_plugins/discord_chat.rb @@ -24,6 +24,10 @@ def self.commands_enabled? enabled? && SiteSetting.discord_chat_commands_enabled end + def self.reports_enabled? + enabled? && SiteSetting.discord_chat_reports_enabled + end + # Whether a forum account may be in the chat. def self.allowed?(user) return false if user.nil? @@ -44,7 +48,11 @@ def self.allowed?(user) next unless name.to_s.start_with?("discord_chat_") next unless DiscourseDiscordChat.configured? Jobs.enqueue(:discord_chat_sync_members) - if %i[discord_chat_commands_enabled discord_chat_public_key].include?(name.to_sym) + if %i[ + discord_chat_commands_enabled + discord_chat_reports_enabled + discord_chat_public_key + ].include?(name.to_sym) Jobs.enqueue(:discord_chat_register_commands) end end