Skip to content
Closed
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],
Comment on lines +28 to +30

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep restricted-channel content inside its audience

When a report originates in a Discord channel that some forum moderators cannot view, such as an admin-only or private project channel, this unconditionally copies the raw message into a PM for the entire forum moderators group. The only authorization check is the guild ID; neither the interaction handler nor this job restricts source channels or recipients, so reporting widens access to restricted Discord content. Avoid copying the content unless every recipient is authorized for that channel, or constrain reports to an explicit safe channel set.

AGENTS.md reference: AGENTS.md:L9-L9

Useful? React with 👍 / 👎.

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
22 changes: 22 additions & 0 deletions config/locales/server.en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,28 @@ 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.

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
15 changes: 15 additions & 0 deletions config/settings.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1866,3 +1866,18 @@ 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"
discord_chat_reports_enabled:
default: false
client: false
depends_on:
- "discord_chat_enabled"
30 changes: 30 additions & 0 deletions docs/features/discord-chat.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,33 @@ 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.

## 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
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

# 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?

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}")
nil
end
end
end
Loading
Loading