From caa73f5484f26c9d10a0d999b57957e4b271daea 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] 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