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
9 changes: 1 addition & 8 deletions app/jobs/regular/discord_chat_register_commands.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
65 changes: 65 additions & 0 deletions app/jobs/regular/discord_chat_report.rb
Original file line number Diff line number Diff line change
@@ -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
8 changes: 8 additions & 0 deletions config/locales/server.en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 5 additions & 0 deletions config/settings.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
11 changes: 11 additions & 0 deletions docs/features/discord-chat.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
58 changes: 57 additions & 1 deletion lib/discourse_discord_chat/commands.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ module Commands
EPHEMERAL = 64
ANSWER_DELAY = 2.seconds
CHAT_INPUT = 1
MESSAGE_COMMAND = 3
STRING = 3
USER = 6

Expand All @@ -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",
Expand All @@ -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
Expand All @@ -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)
Expand All @@ -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
Expand Down
7 changes: 7 additions & 0 deletions spec/jobs/discord_chat_register_commands_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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({})
Expand Down
70 changes: 70 additions & 0 deletions spec/jobs/discord_chat_report_spec.rb
Original file line number Diff line number Diff line change
@@ -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
75 changes: 75 additions & 0 deletions spec/lib/discourse_discord_chat/commands_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading
Loading