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
7 changes: 7 additions & 0 deletions config/locales/server.en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,13 @@ en:
Each member can send 5 reports an hour. Needs the Interactions Endpoint
URL and public key set up as for the slash commands.

discord_chat_welcome_message: A direct message the bot sends each member
once, when the chat first opens for them (their account is linked and
allowed). {username} becomes their forum username. Leave blank to send
none. Only members who joined the server in the last 7 days are
welcomed, 10 a minute at most; anyone with direct messages closed is
skipped and not tried again.

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
6 changes: 6 additions & 0 deletions config/settings.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1881,3 +1881,9 @@ jtech_discord_chat:
client: false
depends_on:
- "discord_chat_enabled"
discord_chat_welcome_message:
default: ""
textarea: true
client: false
depends_on:
- "discord_chat_enabled"
8 changes: 8 additions & 0 deletions docs/features/discord-chat.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,11 @@ 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.

## Welcome message

`discord_chat_welcome_message`: a direct message sent once to each member when
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.
57 changes: 57 additions & 0 deletions lib/discourse_discord_chat/member_sync.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ class MemberSync
# in the server is never lifted by the sync.
STORE = "discord_chat"

# New members are welcomed by direct message a few at a time, so a
# launch rush doesn't look like spam to Discord. Only people who joined
# the server recently are welcomed at all.
WELCOMES_PER_RUN = 10
WELCOME_WINDOW = 7.days

def initialize(api: Api.new, sleeper: ->(seconds) { sleep(seconds) })
@api = api
@sleeper = sleeper
Expand All @@ -44,6 +50,34 @@ def run
next if member.dig("user", "bot")
sync_member(member, links[member.dig("user", "id")], owner_id: guild["owner_id"])
end

welcome(members, links) if welcome_text.present?
end

# A direct message for each newly let-in member, once. Marked as done
# whether or not it arrives: someone with direct messages closed would
# otherwise be tried again every minute.
def welcome(members, links)
recent =
members.select do |member|
next false if member.dig("user", "bot")
joined = Time.zone.parse(member["joined_at"].to_s)
user = links[member.dig("user", "id")]
joined && joined > WELCOME_WINDOW.ago && DiscourseDiscordChat.allowed?(user)
end
return if recent.empty?

keys = recent.map { |member| welcome_key(member.dig("user", "id")) }
done = PluginStoreRow.where(plugin_name: STORE, key: keys).pluck(:key).to_set

recent
.reject { |member| done.include?(welcome_key(member.dig("user", "id"))) }
.first(WELCOMES_PER_RUN)
.each do |member|
discord_id = member.dig("user", "id")
PluginStore.set(STORE, welcome_key(discord_id), true)

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 non-retryable outcomes

If Discord rate-limits this request after call exhausts its retries, returns a transient 5xx response, or the network request raises after this write, the member is permanently recorded as welcomed even though no message arrived; the next scheduled run therefore skips them. Persist the key after a successful send, or after identifying the specific closed-DM response that should not be retried, rather than before every delivery attempt.

Useful? React with 👍 / 👎.

send_welcome(discord_id, links[discord_id])
end
end

def sync_member(member, user, owner_id:)
Expand Down Expand Up @@ -124,6 +158,29 @@ def sync_timeout(member, user)

private

def welcome_text
SiteSetting.discord_chat_welcome_message.to_s.strip
end

def welcome_key(discord_id)
"welcomed_#{discord_id}"
end

def send_welcome(discord_id, user)
channel = call(:post, "/users/@me/channels", { recipient_id: discord_id })
text = welcome_text.gsub("{username}", user.username)
call(
:post,
"/channels/#{channel["id"]}/messages",
{ content: text.truncate(2000), allowed_mentions: { parse: [] } },
)
rescue Api::RateLimited
raise
rescue Api::Error => e
# Usually direct messages closed; nothing to do about that.
Rails.logger.info("#{DiscourseDiscordChat::LOG_TAG} welcome #{discord_id}: #{e.message}")
end

def timeout_until(user)
return if user.nil?
now = Time.zone.now
Expand Down
43 changes: 43 additions & 0 deletions spec/lib/discourse_discord_chat/member_sync_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ def link(user, discord_id)
{ "id" => "7", "owner_id" => "1" }
when "/guilds/7/members"
members
when "/users/@me/channels"
{ "id" => "dm" }
else
{}
end
Expand Down Expand Up @@ -288,4 +290,45 @@ def log_lines
expect(calls.map { |_, p, _| p }.grep(%r{/channels/})).to be_empty
end
end

describe "the welcome message" do
before do
SiteSetting.discord_chat_welcome_message = "Hi {username}, start in #introductions!"
members.each { |m| m["joined_at"] = 1.hour.ago.iso8601 }
end

def opened
calls
.select { |m, p, _| m == :post && p == "/users/@me/channels" }
.map { |_, _, b| b["recipient_id"] }
end

it "welcomes each allowed member once" do
described_class.new.run
expect(opened).to contain_exactly("10", "13", "1")
calls.clear
described_class.new.run
expect(opened).to be_empty
end

it "fills in the forum username and pings nobody" do
described_class.new.run
bodies =
calls.select { |m, p, _| m == :post && p == "/channels/dm/messages" }.map { |_, _, b| b }
expect(bodies.map { |b| b["content"] }).to include("Hi moshe, start in #introductions!")
expect(bodies.map { |b| b["allowed_mentions"] }.uniq).to eq([{ "parse" => [] }])
end

it "skips the suspended and anyone who joined long ago" do
members[0]["joined_at"] = 1.month.ago.iso8601
described_class.new.run
expect(opened).not_to include("10", "11")
end

it "sends nothing when the message is blank" do
SiteSetting.discord_chat_welcome_message = ""
described_class.new.run
expect(opened).to be_empty
end
end
end
Loading