Repository navigation
Discord chat: a starboard for messages that collect enough ⭐ #451
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)) | ||
| 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 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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 👍 / 👎.