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
20 changes: 20 additions & 0 deletions app/jobs/scheduled/discord_chat_starboard.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# frozen_string_literal: true

module Jobs
# Looks for newly starred messages in the server's listed channels.
class DiscordChatStarboard < ::Jobs::Scheduled
every 2.minutes

def execute(_args)
return unless DiscourseDiscordChat.configured?
return if SiteSetting.discord_chat_starboard_channel_id.to_s.strip.blank?
DistributedMutex.synchronize("discord_chat_starboard", validity: 2.minutes) do
DiscourseDiscordChat::Starboard.new.run
end
rescue DiscourseDiscordChat::Api::RateLimited
nil
rescue DiscourseDiscordChat::Api::Error => e
Rails.logger.warn("#{DiscourseDiscordChat::LOG_TAG} starboard: #{e.message}")
end
end
end
14 changes: 14 additions & 0 deletions config/locales/server.en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,20 @@ en:
welcomed, 10 a minute at most; anyone with direct messages closed is
skipped and not tried again.

discord_chat_starboard_channel_id: ID of the Discord channel that starred
messages are reposted to (make it read-only for members). Leave blank
to turn the starboard off. Needs the Message Content intent on the bot
(Developer Portal → Bot) so the reposts carry the text.

discord_chat_starboard_channels: IDs of the Discord channels the
starboard reads. Only these are ever looked at, so list public channels
only; a starred message in a channel left off the list is never
reposted.

discord_chat_starboard_threshold: How many ⭐ reactions a message needs to
be reposted to the starboard. Each message is reposted once; messages
older than 7 days are ignored.

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
19 changes: 19 additions & 0 deletions config/settings.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1887,3 +1887,22 @@ jtech_discord_chat:
client: false
depends_on:
- "discord_chat_enabled"
discord_chat_starboard_channel_id:
default: ""
client: false
depends_on:
- "discord_chat_enabled"
discord_chat_starboard_channels:
type: list
list_type: simple
default: ""
client: false
depends_on:
- "discord_chat_enabled"
discord_chat_starboard_threshold:
default: 3
min: 1
max: 100
client: false
depends_on:
- "discord_chat_enabled"
9 changes: 9 additions & 0 deletions docs/features/discord-chat.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,12 @@ the chat opens for them. `{username}` becomes their forum username. Only people
who joined the server in the last 7 days are welcomed, at most 10 a minute, and
someone with direct messages closed is marked done rather than retried. Blank
sends nothing.

## Starboard

Messages that get `discord_chat_starboard_threshold` ⭐ reactions (3 by default)
are reposted once to `discord_chat_starboard_channel_id`, with the author, the
text, the first image and a link back. Only the channel IDs in
`discord_chat_starboard_channels` are read, so private channels can't leak into
it; messages older than 7 days and bot messages are skipped. The forum checks
every 2 minutes. The bot needs the Message Content intent for the text.
89 changes: 89 additions & 0 deletions lib/discourse_discord_chat/starboard.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# frozen_string_literal: true

module DiscourseDiscordChat
# Reposts messages that collected enough ⭐ reactions into the starboard
# channel. Only the channels listed in the setting are read, so a starred
# message in a private channel the bot can see never reaches members.
class Starboard
STAR = "⭐"
LOOKBACK = 50
MAX_AGE = 7.days
STORE = MemberSync::STORE

def initialize(api: Api.new)
@api = api
end

def run
target = SiteSetting.discord_chat_starboard_channel_id.to_s.strip
return if target.blank?

sources.each do |channel_id|
next if channel_id == target
messages = @api.bot(:get, "/channels/#{channel_id}/messages", query: { limit: LOOKBACK })
starred = Array(messages).select { |message| qualifies?(message) }
next if starred.empty?

keys = starred.map { |message| key(message["id"]) }
done = PluginStoreRow.where(plugin_name: STORE, key: keys).pluck(:key).to_set
starred.each do |message|
next if done.include?(key(message["id"]))
PluginStore.set(STORE, key(message["id"]), true)
@api.bot(:post, "/channels/#{target}/messages", repost(message, channel_id))
Comment on lines +31 to +32

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 Record completion only after Discord accepts the repost

When the POST is rate-limited or fails with another Discord API error, this row has already been stored, while the scheduled job catches the exception and returns. On every later run the message is therefore treated as done and is never reposted, even after the transient failure clears; persist the marker only after a successful POST.

Useful? React with 👍 / 👎.

end
end
end

private

def sources
SiteSetting.discord_chat_starboard_channels.to_s.split("|").map(&:strip).reject(&:blank?)
end

def qualifies?(message)
return false if message.dig("author", "bot")
sent = Time.zone.parse(message["timestamp"].to_s)
return false if sent.nil? || sent < MAX_AGE.ago
stars(message) >= SiteSetting.discord_chat_starboard_threshold
end

def stars(message)
reaction = Array(message["reactions"]).find { |r| r.dig("emoji", "name") == STAR }
reaction ? reaction["count"].to_i : 0
end

def key(message_id)
"starred_#{message_id}"
end

def repost(message, channel_id)
guild = SiteSetting.discord_chat_guild_id.to_s.strip
link = "https://discord.com/channels/#{guild}/#{channel_id}/#{message["id"]}"
author = message["author"] || {}
embed = {
author: {
name: (author["global_name"].presence || author["username"]).to_s.truncate(256),
icon_url: avatar(author),
}.compact,
description: message["content"].to_s.truncate(4000),
timestamp: message["timestamp"],
}
image =
Array(message["attachments"]).find { |a| a["content_type"].to_s.start_with?("image/") }
embed[:image] = { url: image["url"] } if image

{
content: "#{STAR} #{stars(message)} · <##{channel_id}> · #{link}",
embeds: [embed],
allowed_mentions: {
parse: [],
},
}
end

def avatar(author)
return if author["id"].blank? || author["avatar"].blank?
"https://cdn.discordapp.com/avatars/#{author["id"]}/#{author["avatar"]}.png"
end
end
end
83 changes: 83 additions & 0 deletions spec/lib/discourse_discord_chat/starboard_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# frozen_string_literal: true

require "rails_helper"

RSpec.describe DiscourseDiscordChat::Starboard do
let(:calls) { [] }
let(:messages) do
{
"300" => [
message("1", stars: 3, content: "great @everyone"),
message("2", stars: 2),
message("3", stars: 5, bot: true),
message("4", stars: 9, at: 10.days.ago),
],
"666" => [message("5", stars: 9)],
}
end

def message(id, stars:, content: "hi", bot: false, at: 1.hour.ago)
{
"id" => id,
"content" => content,
"timestamp" => at.iso8601,
"author" => {
"id" => "41",
"username" => "moshe",
"avatar" => "abc",
"bot" => bot,
},
"reactions" => [{ "emoji" => { "name" => "⭐" }, "count" => stars }],
}
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_starboard_channel_id = "999"
SiteSetting.discord_chat_starboard_channels = "300"
SiteSetting.discord_chat_starboard_threshold = 3

WebMock
.stub_request(:any, %r{\Ahttps://discord\.com/api/v10/})
.to_return do |request|
path = request.uri.path.delete_prefix("/api/v10")
calls << [request.method, path, request.body.presence && JSON.parse(request.body)]
channel = path[%r{\A/channels/(\d+)/messages\z}, 1]
body = request.method == :get ? messages.fetch(channel, []) : {}
{ status: 200, body: body.to_json, headers: { "Content-Type" => "application/json" } }
end
end

def reposts
calls.select { |m, p, _| m == :post && p == "/channels/999/messages" }.map(&:last)
end

it "reposts a message once it has enough stars, and only once" do
described_class.new.run
described_class.new.run
expect(reposts.size).to eq(1)
repost = reposts.first
expect(repost["content"]).to include("⭐ 3", "<#300>", "https://discord.com/channels/7/300/1")
expect(repost["embeds"].first["description"]).to eq("great @everyone")
expect(repost["allowed_mentions"]).to eq({ "parse" => [] })
end

it "skips bot messages, old messages and those under the threshold" do
described_class.new.run
expect(reposts.map { |r| r["content"] }).to all(include("/300/1"))
end

it "never reads a channel that isn't listed" do
described_class.new.run
expect(calls.map { |_, p, _| p }).not_to include("/channels/666/messages")
end

it "does nothing without a starboard channel" do
SiteSetting.discord_chat_starboard_channel_id = ""
described_class.new.run
expect(calls).to be_empty
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 @@ -40,6 +40,7 @@ def self.allowed?(user)
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/starboard"
require_relative "../lib/discourse_discord_chat/signature"
require_relative "../lib/discourse_discord_chat/commands"

Expand Down
Loading