Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: support target_user_ids for private messages (#37708)

Samf9fce4712b51
diff --git a/lib/post_creator.rb b/lib/post_creator.rb
index 1eec0e12ec9..7925fcdfa90 100644
--- a/lib/post_creator.rb
+++ b/lib/post_creator.rb
@@ -49,7 +49,9 @@ class PostCreator
# is_warning - Is the topic a warning?
# category - Category to assign to topic
# target_usernames - comma delimited list of usernames for membership (private message)
+ # target_user_ids - array of user IDs for membership (private message, alternative to target_usernames)
# target_group_names - comma delimited list of groups for membership (private message)
+ # target_emails - comma delimited list of emails for membership (private message)
# created_at - Topic creation time (optional)
# pinned_at - Topic pinned time (optional)
# pinned_globally - Is the topic pinned globally (optional)
@@ -100,13 +102,25 @@ class PostCreator
return false
end
- if @opts[:target_usernames].present? && !skip_validations? && [email protected]?
- names = @opts[:target_usernames].split(",").flatten.map(&:downcase)
+ if @opts[:target_usernames].present? && @opts[:target_user_ids].present?
+ raise ArgumentError, "Cannot specify both target_usernames and target_user_ids"
+ end
+
+ if (@opts[:target_usernames].present? || @opts[:target_user_ids].present?) &&
+ !skip_validations? && [email protected]?
+ if @opts[:target_user_ids].present?
+ ids = Array.wrap(@opts[:target_user_ids])
+ target_users = User.where(id: ids).pluck(:id, :username).to_h
+ recipient_count = ids.length
+ else
+ names = @opts[:target_usernames].split(",").flatten.map(&:downcase)
+ target_users = User.where(username_lower: names).pluck(:id, :username).to_h
+ recipient_count = names.length
+ end
- # Make sure max_allowed_message_recipients setting is respected
max_allowed_message_recipients = SiteSetting.max_allowed_message_recipients
- if names.length > max_allowed_message_recipients
+ if recipient_count > max_allowed_message_recipients
errors.add(
:base,
I18n.t(:max_pm_recipients, recipients_limit: max_allowed_message_recipients),
@@ -115,9 +129,6 @@ class PostCreator
return false
end
- # Make sure none of the users have muted or ignored the creator or prevented
- # PMs from being sent to them
- target_users = User.where(username_lower: names.map(&:downcase)).pluck(:id, :username).to_h
UserCommScreener
.new(acting_user: @user, target_user_ids: target_users.keys)
.preventing_actor_communication
diff --git a/lib/topic_creator.rb b/lib/topic_creator.rb
index cd086f8e81d..72d9288457a 100644
--- a/lib/topic_creator.rb
+++ b/lib/topic_creator.rb
@@ -241,8 +241,12 @@ class TopicCreator
return unless @opts[:archetype] == Archetype.private_message
topic.subtype = TopicSubtype.user_to_user unless topic.subtype
- if @opts[:target_usernames].blank? && @opts[:target_emails].blank? &&
- @opts[:target_group_names].blank?
+ if @opts[:target_usernames].present? && @opts[:target_user_ids].present?
+ raise ArgumentError, "Cannot specify both target_usernames and target_user_ids"
+ end
+
+ if @opts[:target_usernames].blank? && @opts[:target_user_ids].blank? &&
+ @opts[:target_emails].blank? && @opts[:target_group_names].blank?
rollback_with!(topic, :no_user_selected)
end
@@ -250,7 +254,11 @@ class TopicCreator
rollback_with!(topic, :send_to_email_disabled)
end
- add_users(topic, @opts[:target_usernames])
+ if @opts[:target_user_ids].present?
+ add_users_by_id(topic, @opts[:target_user_ids])
+ else
+ add_users(topic, @opts[:target_usernames])
+ end
add_emails(topic, @opts[:target_emails])
add_groups(topic, @opts[:target_group_names])
@@ -267,11 +275,21 @@ class TopicCreator
return unless usernames
names = usernames.split(",").flatten.map(&:downcase)
+ add_users_from_scope(topic, User.where("username_lower in (?)", names), names.length)
+ end
+
+ def add_users_by_id(topic, user_ids)
+ return unless user_ids
+
+ ids = Array.wrap(user_ids)
+ add_users_from_scope(topic, User.where(id: ids), ids.length)
+ end
+
+ def add_users_from_scope(topic, scope, expected_count)
len = 0
- User
+ scope
.includes(:user_option)
- .where("username_lower in (?)", names)
.find_each do |user|
check_can_send_permission!(topic, user)
@added_users << user
@@ -279,7 +297,7 @@ class TopicCreator
len += 1
end
- rollback_with!(topic, :target_user_not_found) unless len == names.length
+ rollback_with!(topic, :target_user_not_found) unless len == expected_count
end
def add_emails(topic, emails)
diff --git a/plugins/automation/app/jobs/scheduled/discourse_automation/tracker.rb b/plugins/automation/app/jobs/scheduled/discourse_automation/tracker.rb
index 902e60adc70..e8c47f47daa 100644
--- a/plugins/automation/app/jobs/scheduled/discourse_automation/tracker.rb
+++ b/plugins/automation/app/jobs/scheduled/discourse_automation/tracker.rb
@@ -37,8 +37,12 @@ module Jobs
next if !::DiscourseAutomation::PendingPm.exists?(pending_pm.id)
::DiscourseAutomation::Scriptable::Utils.send_pm(
- pending_pm.attributes.slice("target_usernames", "title", "raw"),
- sender: pending_pm.sender,
+ {
+ "target_user_ids" => pending_pm.target_user_ids,
+ "title" => pending_pm.title,
+ "raw" => pending_pm.raw,
+ },
+ sender: pending_pm.sender_id,
)
pending_pm.destroy!
diff --git a/plugins/automation/app/models/discourse_automation/pending_pm.rb b/plugins/automation/app/models/discourse_automation/pending_pm.rb
index ae31e603d3f..7a8442a470c 100644
--- a/plugins/automation/app/models/discourse_automation/pending_pm.rb
+++ b/plugins/automation/app/models/discourse_automation/pending_pm.rb
@@ -3,7 +3,8 @@
module DiscourseAutomation
class PendingPm < ActiveRecord::Base
# TODO: Remove after 20260106102330_drop_prefers_encrypt_from_pending_pms has been promoted
- self.ignored_columns = %w[prefers_encrypt]
+ # TODO (2026-08-11): Remove sender and target_usernames after column drop migration has been promoted
+ self.ignored_columns = %w[prefers_encrypt sender target_usernames]
self.table_name = "discourse_automation_pending_pms"
@@ -15,13 +16,13 @@ end
#
# Table name: discourse_automation_pending_pms
#
-# id :bigint not null, primary key
-# execute_at :datetime not null
-# raw :string
-# sender :string
-# target_usernames :string is an Array
-# title :string
-# created_at :datetime not null
-# updated_at :datetime not null
-# automation_id :bigint not null
+# id :bigint not null, primary key
+# execute_at :datetime not null
+# raw :string
+# target_user_ids :bigint is an Array
+# title :string
+# created_at :datetime not null
+# updated_at :datetime not null
+# automation_id :bigint not null
+# sender_id :bigint
#
diff --git a/plugins/automation/db/migrate/20260211051130_add_user_ids_to_pending_pms.rb b/plugins/automation/db/migrate/20260211051130_add_user_ids_to_pending_pms.rb
new file mode 100644
index 00000000000..ddf735f4767
--- /dev/null
+++ b/plugins/automation/db/migrate/20260211051130_add_user_ids_to_pending_pms.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+class AddUserIdsToPendingPms < ActiveRecord::Migration[7.2]
+ def up
+ add_column :discourse_automation_pending_pms, :sender_id, :bigint, null: true
+ add_column :discourse_automation_pending_pms, :target_user_ids, :bigint, array: true, null: true
+
+ execute <<~SQL
+ UPDATE discourse_automation_pending_pms ppm
+ SET sender_id = u.id
+ FROM users u
+ WHERE u.username = ppm.sender
+ AND ppm.sender_id IS NULL
+ SQL
+
+ execute <<~SQL
+ UPDATE discourse_automation_pending_pms ppm
+ SET target_user_ids = subquery.user_ids
+ FROM (
+ SELECT ppm2.id,
+ ARRAY_AGG(u.id ORDER BY array_position(ppm2.target_usernames, u.username)) AS user_ids
+ FROM discourse_automation_pending_pms ppm2
+ CROSS JOIN LATERAL unnest(ppm2.target_usernames) AS target_username
+ JOIN users u ON u.username = target_username
+ WHERE ppm2.target_user_ids IS NULL
+ GROUP BY ppm2.id
+ ) subquery
+ WHERE ppm.id = subquery.id
+ SQL
+ end
+
+ def down
+ remove_column :discourse_automation_pending_pms, :sender_id
+ remove_column :discourse_automation_pending_pms, :target_user_ids
+ end
+end
diff --git a/plugins/automation/lib/discourse_automation/scriptable.rb b/plugins/automation/lib/discourse_automation/scriptable.rb
index 281ee6c7136..42390b0c911 100644
--- a/plugins/automation/lib/discourse_automation/scriptable.rb
+++ b/plugins/automation/lib/discourse_automation/scriptable.rb
@@ -253,31 +253,71 @@ module DiscourseAutomation
def self.send_pm(pm, sender: Discourse.system_user.username, delay: nil, automation_id: nil)
pm = pm.symbolize_keys
+ sender_user =
+ if sender.is_a?(Integer)
+ User.find_by(id: sender)
+ else
+ User.find_by(username: sender)
+ end
+
+ if !sender_user
+ DiscourseAutomation::Logger.warn(
+ "Did not send PM #{pm[:title]} - sender does not exist: `#{sender}`",
+ )
+ return
+ end
+
if delay && delay.to_i > 0 && automation_id
+ if pm[:target_user_ids].present?
+ target_user_ids = Array.wrap(pm[:target_user_ids])
+ if !User.where(id: target_user_ids).exists?
+ DiscourseAutomation::Logger.warn(
+ "Did not create pending PM #{pm[:title]} - no valid targets exist",
+ )
+ return
+ end
+ else
+ target_usernames = Array.wrap(pm[:target_usernames])
+ target_user_ids = User.where(username: target_usernames).pluck(:id)
+ if target_user_ids.empty?
+ DiscourseAutomation::Logger.warn(
+ "Did not create pending PM #{pm[:title]} - no valid targets exist",
+ )
+ return
+ end
+ end
+
+ pm.delete(:target_usernames)
pm[:execute_at] = delay.to_i.minutes.from_now
- pm[:sender] = sender
+ pm[:sender_id] = sender_user.id
+ pm[:target_user_ids] = target_user_ids
pm[:automation_id] = automation_id
DiscourseAutomation::PendingPm.create!(pm)
else
- sender = User.find_by(username: sender)
- if !sender
- DiscourseAutomation::Logger.warn(
- "Did not send PM #{pm[:title]} - sender does not exist: `#{sender}`",
- )
- return
+ if pm[:target_user_ids].present?
+ pm[:target_user_ids] = Array.wrap(pm[:target_user_ids])
+ pm.delete(:target_usernames)
+ else
+ pm[:target_usernames] = Array.wrap(pm[:target_usernames])
end
-
- pm[:target_usernames] = Array.wrap(pm[:target_usernames])
pm[:target_group_names] = Array.wrap(pm[:target_group_names])
pm[:target_emails] = Array.wrap(pm[:target_emails])
- if pm[:target_usernames].empty? && pm[:target_group_names].empty? &&
- pm[:target_emails].empty?
+ if pm[:target_user_ids].blank? && pm[:target_usernames].blank? &&
+ pm[:target_group_names].empty? && pm[:target_emails].empty?
return
end
non_existing_targets = []
+ if pm[:target_user_ids].present?
+ existing_ids = User.where(id: pm[:target_user_ids]).pluck(:id)
+ if existing_ids.length != pm[:target_user_ids].length
+ non_existing_targets << "#{pm[:target_user_ids].length - existing_ids.length} user(s) by ID"
+ pm[:target_user_ids] = existing_ids
+ end
+ end
+
if pm[:target_usernames].present?
existing_target_usernames = User.where(username: pm[:target_usernames]).pluck(:username)
if existing_target_usernames.length != pm[:target_usernames].length
@@ -303,12 +343,12 @@ module DiscourseAutomation
end
pm = pm.merge(archetype: Archetype.private_message)
- pm[:target_usernames] = pm[:target_usernames].join(",")
+ pm[:target_usernames] = pm[:target_usernames].join(",") if pm[:target_usernames].present?
pm[:target_group_names] = pm[:target_group_names].join(",")
pm[:target_emails] = pm[:target_emails].join(",")
- if pm[:target_usernames].blank? && pm[:target_group_names].blank? &&
- pm[:target_emails].blank?
+ if pm[:target_user_ids].blank? && pm[:target_usernames].blank? &&
+ pm[:target_group_names].blank? && pm[:target_emails].blank?
DiscourseAutomation::Logger.warn(
"Did not send PM #{pm[:title]} - no valid targets exist",
)
@@ -320,7 +360,7 @@ module DiscourseAutomation
end
pm[:acting_user] = Discourse.system_user
- creator = PostCreator.new(sender, pm)
+ creator = PostCreator.new(sender_user, pm)
post = creator.create
if post.blank? || creator.errors.present?
error_message = creator.errors.full_messages.join(", ")
diff --git a/plugins/automation/spec/jobs/scheduled/discourse_automation/tracker_spec.rb b/plugins/automation/spec/jobs/scheduled/discourse_automation/tracker_spec.rb
index d0c88bb76fb..aca9830443c 100644
--- a/plugins/automation/spec/jobs/scheduled/discourse_automation/tracker_spec.rb
+++ b/plugins/automation/spec/jobs/scheduled/discourse_automation/tracker_spec.rb
@@ -115,9 +115,9 @@ describe Jobs::DiscourseAutomation::Tracker do
automation.pending_pms.create!(
title: "Il pleure dans mon cœur Comme il pleut sur la ville;",
raw: "Quelle est cette langueur Qui pénètre mon cœur ?",
- sender: "system",
+ sender_id: Discourse.system_user.id,
+ target_user_ids: [Discourse.system_user.id],
execute_at: Time.now,
- target_usernames: ["system"],
)
end
@@ -151,5 +151,29 @@ describe Jobs::DiscourseAutomation::Tracker do
end
end.to change { Topic.private_messages_for_user(Discourse.system_user).count }.by(1)
end
+
+ context "when target user changes username after pending PM creation" do
+ fab!(:target_user) { Fabricate(:user, username: "original_name") }
+
+ let!(:pending_pm_with_rename) do
+ automation.pending_pms.create!(
+ title: "Test PM",
+ raw: "Test content",
+ sender_id: Discourse.system_user.id,
+ target_user_ids: [target_user.id],
+ execute_at: 2.hours.ago,
+ )
+ end
+
+ it "sends the PM using the user's current username" do
+ target_user.update!(username: "new_name")
+
+ expect { Jobs::DiscourseAutomation::Tracker.new.execute }.to change {
+ Topic.private_messages_for_user(target_user).count
+ }.by(1)
+
+ expect(Topic.last.allowed_users).to include(target_user)
+ end
+ end
end
end
diff --git a/plugins/automation/spec/lib/scriptable_spec.rb b/plugins/automation/spec/lib/scriptable_spec.rb
index 5f68b9ca1dc..0958fa78508 100644
--- a/plugins/automation/spec/lib/scriptable_spec.rb
+++ b/plugins/automation/spec/lib/scriptable_spec.rb
@@ -293,7 +293,7 @@ describe DiscourseAutomation::Scriptable do
let(:user) { Fabricate(:user) }
context "when pm is delayed" do
- it "creates a pending pm" do
+ it "creates a pending pm with user IDs" do
expect {
DiscourseAutomation::Scriptable::Utils.send_pm(
{
@@ -305,6 +305,10 @@ describe DiscourseAutomation::Scriptable do
automation_id: automation.id,
)
}.to change { DiscourseAutomation::PendingPm.count }.by(1)
+
+ pending_pm = DiscourseAutomation::PendingPm.last
+ expect(pending_pm.sender_id).to eq(Discourse.system_user.id)
+ expect(pending_pm.target_user_ids).to eq([user.id])
end
end
diff --git a/plugins/automation/spec/scripts/send_pms_spec.rb b/plugins/automation/spec/scripts/send_pms_spec.rb
index de89fff6e19..e651be87a62 100644
--- a/plugins/automation/spec/scripts/send_pms_spec.rb
+++ b/plugins/automation/spec/scripts/send_pms_spec.rb
@@ -95,7 +95,8 @@ describe "SendPms" do
pending_pm = DiscourseAutomation::PendingPm.last
expect(pending_pm.title).to eq("Delayed")
- expect(pending_pm.target_usernames).to eq([user.username])
+ expect(pending_pm.sender_id).to eq(Discourse.system_user.id)
+ expect(pending_pm.target_user_ids).to eq([user.id])
expect(pending_pm.execute_at).to be_within(1.minute).of(5.minutes.from_now)
end
end
diff --git a/spec/lib/post_creator_spec.rb b/spec/lib/post_creator_spec.rb
index b6e0de28408..1345234a800 100644
--- a/spec/lib/post_creator_spec.rb
+++ b/spec/lib/post_creator_spec.rb
@@ -1328,6 +1328,38 @@ RSpec.describe PostCreator do
end
end
+ describe "private message with target_user_ids" do
+ fab!(:target_user1) { coding_horror }
+ fab!(:target_user2, :moderator)
+
+ it "creates a PM targeting users by ID" do
+ post =
+ PostCreator.create!(
+ user,
+ title: "PM via user IDs",
+ raw: "this is a PM sent using target_user_ids",
+ archetype: Archetype.private_message,
+ target_user_ids: [target_user1.id, target_user2.id],
+ )
+
+ expect(post.topic.archetype).to eq(Archetype.private_message)
+ expect(post.topic.allowed_users).to include(target_user1, target_user2, user)
+ end
+
+ it "raises when both target_usernames and target_user_ids are provided" do
+ expect {
+ PostCreator.create!(
+ user,
+ title: "PM with both",
+ raw: "this should fail",
+ archetype: Archetype.private_message,
+ target_usernames: target_user1.username,
+ target_user_ids: [target_user2.id],
+ )
+ }.to raise_error(ArgumentError, /Cannot specify both/)
+ end
+ end
+
describe "private message to group" do
fab!(:target_user1) { coding_horror }
fab!(:target_user2, :moderator)
diff --git a/spec/lib/topic_creator_spec.rb b/spec/lib/topic_creator_spec.rb
index b771acfb324..0b1b847ade0 100644
--- a/spec/lib/topic_creator_spec.rb
+++ b/spec/lib/topic_creator_spec.rb
@@ -736,4 +736,29 @@ RSpec.describe TopicCreator do
end
end
end
+
+ describe "private message with target_user_ids" do
+ it "creates a PM targeting users by ID" do
+ topic =
+ TopicCreator.create(
+ admin,
+ Guardian.new(admin),
+ pm_valid_attrs.except(:target_usernames).merge(target_user_ids: [moderator.id]),
+ )
+
+ expect(topic).to be_valid
+ expect(topic.archetype).to eq(Archetype.private_message)
+ expect(topic.topic_allowed_users.map(&:user_id)).to include(moderator.id)
+ end
+
+ it "raises when both target_usernames and target_user_ids are provided" do
+ expect {
+ TopicCreator.create(
+ admin,
+ Guardian.new(admin),
+ pm_valid_attrs.merge(target_user_ids: [moderator.id]),
+ )
+ }.to raise_error(ArgumentError, /Cannot specify both/)
+ end
+ end
end