Skip to content

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

FEATURE: Send chat direct messages from workflows

Régis Hanol469acd38dfcd
diff --git a/plugins/chat/config/locales/client.en.yml b/plugins/chat/config/locales/client.en.yml
index 4631d1fa9db..9776743336d 100644
--- a/plugins/chat/config/locales/client.en.yml
+++ b/plugins/chat/config/locales/client.en.yml
@@ -932,15 +932,24 @@ en:
"action:chat_approval": "Chat approval"
"trigger:chat_message_created": "Chat message created"
node_descriptions:
- "action:send_chat_message": "Send a message to a chat channel"
+ "action:send_chat_message": "Send a message to a chat channel, or a direct message to one or more users"
"action:chat_approval": "Send an approval request to a chat channel and wait for a response"
"trigger:chat_message_created": "Fires when a new chat message is created"
chat_message_created:
channel_id: "Channel"
channel_id_description: "Leave blank to trigger for all chat channels."
send_chat_message:
+ target: "Send to"
+ targets:
+ channel: "Channel"
+ user: "Users (a direct message each)"
+ group: "Group (one direct message with everyone)"
channel_id: "Channel"
+ target_usernames: "Recipients"
+ target_usernames_description: "Users to message. Use an expression such as $trigger.user.username to pick them from each item."
message: "Message"
+ actor_username: "Sender"
+ actor_username_description: "Direct messages are sent as this user, and recipients see them as written by them."
chat_approval:
message: "Message"
buttons: "Buttons"
diff --git a/plugins/chat/config/locales/server.en.yml b/plugins/chat/config/locales/server.en.yml
index 724a04dcee3..cb1f7d38f81 100644
--- a/plugins/chat/config/locales/server.en.yml
+++ b/plugins/chat/config/locales/server.en.yml
@@ -258,9 +258,23 @@ en:
default_deny_label: "Deny"
errors:
send_chat_message:
- invalid_params: "Invalid params: %{errors}"
+ invalid_params: "The message is invalid: %{errors}"
channel_not_found: "Channel not found: %{channel_id}"
- failed: "Failed to send chat message."
+ channel_blocked: "Can't post in channel %{channel_id}: %{reason}"
+ failed: "Couldn't send the chat message (failed step: %{step})."
+ recipient_blank: "No recipient usernames were given."
+ recipient_staged: "'%{username}' is a staged user and can't use chat."
+ recipient_suspended: "'%{username}' is suspended and can't receive direct messages."
+ recipient_inactive: "'%{username}' hasn't activated their account yet."
+ recipient_chat_disabled: "'%{username}' has disabled chat in their preferences."
+ recipient_cannot_chat: "'%{username}' can't use chat because they aren't in a group allowed by the 'chat allowed groups' setting."
+ sender_anonymous: "Direct messages can't be sent anonymously. Choose a user as the sender."
+ sender_chat_disabled: "Sender '%{sender}' has disabled chat in their preferences."
+ sender_cannot_chat: "Sender '%{sender}' can't use chat because they aren't in a group allowed by the 'chat allowed groups' setting."
+ sender_cannot_create_dm: "Sender '%{sender}' isn't allowed to send direct messages (see the 'direct message enabled groups' setting)."
+ sender_dms_disabled: "Sender '%{sender}' has disabled personal messages in their preferences."
+ user_blocked: "'%{sender}' can't send a direct message to '%{username}': %{reason}"
+ group_blocked: "'%{sender}' can't send a group direct message to %{usernames}: %{reason}"
chat_approval:
channel_not_found: "Chat message failed: channel %{channel_id} not found."
invalid_params: "Chat message failed: %{errors}"
@@ -276,6 +290,15 @@ en:
button_value_too_long: "Chat approval button %{position} value must be %{max} characters or fewer."
button_style_invalid: "Chat approval button %{position} style must be one of: %{styles}."
button_icon_too_long: "Chat approval button %{position} icon must be %{max} characters or fewer."
+ hints:
+ send_chat_message:
+ self_message: "Sender and recipient are both '%{username}', so the message was posted to their personal chat."
+ preferences_bypassed: "'%{username}' doesn't accept direct messages from '%{sender}', but the message was delivered because the sender is staff."
+ logs:
+ send_chat_message:
+ sent_to_channel: "Item %{item_index}: sent message %{message_id} to channel %{channel_id}."
+ sent_to_user: "Item %{item_index}: '%{sender}' sent message %{message_id} to '%{username}'."
+ sent_to_group: "Item %{item_index}: '%{sender}' sent message %{message_id} to the group direct message with %{usernames}."
reviewable_score_types:
needs_review:
diff --git a/plugins/chat/lib/discourse_workflows/nodes/send_chat_message/v1.rb b/plugins/chat/lib/discourse_workflows/nodes/send_chat_message/v1.rb
index f4ad8ecf8a0..70738306197 100644
--- a/plugins/chat/lib/discourse_workflows/nodes/send_chat_message/v1.rb
+++ b/plugins/chat/lib/discourse_workflows/nodes/send_chat_message/v1.rb
@@ -7,6 +7,17 @@ if defined?(DiscourseWorkflows)
class V1 < DiscourseWorkflows::NodeType
include ChatChannelSelection
+ TARGETS = %w[channel user group].freeze
+ DM_TARGETS = %w[user group].freeze
+
+ # Per-item state passed through the send helpers.
+ ItemRun =
+ Data.define(:exec_ctx, :item, :item_index, :message) do
+ def parameter(path, default: nil)
+ exec_ctx.get_node_parameter(path, item_index, default:)
+ end
+ end
+
description(
name: "action:send_chat_message",
version: "1.0",
@@ -29,17 +40,40 @@ if defined?(DiscourseWorkflows)
"channel_id" => {
"type" => "integer",
},
+ "message_id" => {
+ "type" => "integer",
+ },
"message" => {
"type" => "string",
},
+ "username" => {
+ "type" => "string",
+ },
+ "usernames" => {
+ "type" => "array",
+ "items" => {
+ "type" => "string",
+ },
+ },
},
},
},
],
properties: {
+ target: {
+ type: :options,
+ required: true,
+ options: TARGETS,
+ default: "channel",
+ },
channel_id: {
type: :integer,
required: true,
+ display_options: {
+ show: {
+ target: ["channel"],
+ },
+ },
type_options: {
load_options_method: "chat_channels",
},
@@ -62,6 +96,20 @@ if defined?(DiscourseWorkflows)
hidden: true,
},
},
+ target_usernames: {
+ type: :array,
+ required: true,
+ display_options: {
+ show: {
+ target: DM_TARGETS,
+ },
+ },
+ ui: {
+ control: :user,
+ expression: true,
+ multiple: true,
+ },
+ },
message: {
type: :string,
required: true,
@@ -69,6 +117,14 @@ if defined?(DiscourseWorkflows)
control: :textarea,
},
},
+ **actor_property(
+ allow_anonymous: false,
+ display_options: {
+ show: {
+ target: DM_TARGETS,
+ },
+ },
+ ),
},
)
@@ -81,62 +137,260 @@ if defined?(DiscourseWorkflows)
def execute(exec_ctx)
items =
- exec_ctx.input_items.map.with_index do |_item, item_index|
- config = {
- "channel_id" => exec_ctx.get_node_parameter("channel_id", item_index),
- "message" => exec_ctx.get_node_parameter("message", item_index),
- }
- result = process(config)
- wrap(result)
+ exec_ctx.each_item do |item, item_index|
+ run =
+ ItemRun.new(
+ exec_ctx:,
+ item:,
+ item_index:,
+ message: exec_ctx.get_node_parameter("message", item_index),
+ )
+ target = run.parameter("target", default: "channel")
+ if DM_TARGETS.include?(target)
+ send_direct_messages(run, group: target == "group")
+ else
+ send_to_channel(run)
+ end
end
[items]
end
private
- def process(config)
- channel_id = config["channel_id"]
- message = config["message"]
+ def send_to_channel(run)
+ channel_id = run.parameter("channel_id")
channel = selectable_chat_channel(channel_id)
- if channel.blank?
- raise_node_error!(
- I18n.t(
- "discourse_workflows.errors.send_chat_message.channel_not_found",
- channel_id: channel_id,
- ),
+ node_error!(run, :channel_not_found, channel_id:) if channel.blank?
+
+ wrap(
+ create_message(
+ run,
+ :channel,
+ Discourse.system_user.guardian,
+ channel,
+ channel_id: channel.id,
+ ),
+ )
+ end
+
+ def send_direct_messages(run, group:)
+ sender = run.exec_ctx.actor_from_parameter("actor_username", run.item_index)
+ # `allow_anonymous: false` only hides the option in the UI.
+ node_error!(run, :sender_anonymous) if sender.is_a?(DiscourseWorkflows::AnonymousActor)
+
+ # Account states are checked for every recipient before anything is sent.
+ recipients = resolve_recipients!(run)
+ ensure_sender_can_chat!(run, sender)
+
+ if group
+ members = recipients.reject { |recipient| recipient.id == sender.id }.presence
+ members ||= recipients
+ result = deliver_dm(run, sender, members)
+ return wrap(result.merge("usernames" => members.map(&:username)))
+ end
+
+ recipients.map do |recipient|
+ run
+ .exec_ctx
+ .guard_item(run.item, run.item_index) do
+ result = deliver_dm(run, sender, [recipient])
+ wrap(result.merge("username" => recipient.username))
+ end
+ end
+ end
+
+ # A single recipient gets a 1:1 DM, several share one group DM.
+ def deliver_dm(run, sender, recipients)
+ usernames = recipients.map(&:username)
+ target, labels =
+ if recipients.one?
+ [:user, { sender: sender.username, username: usernames.first }]
+ else
+ [
+ :group,
+ {
+ sender: sender.username,
+ usernames: usernames.map { |username| "'#{username}'" }.join(", "),
+ },
+ ]
+ end
+
+ # Rolls back a newly created DM channel when the message itself is rejected. Jobs
+ # enqueued by the message are deferred until commit.
+ result =
+ ActiveRecord::Base.transaction(requires_new: true) do
+ channel = create_direct_message_channel(run, sender, usernames, target, labels)
+ create_message(run, target, sender.guardian, channel, **labels)
+ end
+
+ # Step metadata keeps hints even when the step fails, so only add them once delivered.
+ add_delivery_hints(run, sender, recipients)
+ result
+ end
+
+ def add_delivery_hints(run, sender, recipients)
+ recipients.each do |recipient|
+ if recipient.id == sender.id
+ add_hint(run, :self_message, username: sender.username)
+ elsif preferences_bypassed?(sender, recipient)
+ add_hint(
+ run,
+ :preferences_bypassed,
+ sender: sender.username,
+ username: recipient.username,
+ )
+ end
+ end
+ end
+
+ # Mirrors UserCommScreener, which skips these checks entirely for staff senders.
+ def preferences_bypassed?(sender, recipient)
+ return false if !sender.staff?
+
+ options = recipient.user_option
+ guardian = sender.guardian
+
+ !options.allow_private_messages || guardian.is_muted_by_user?(recipient) ||
+ guardian.is_ignored_by_user?(recipient) ||
+ (
+ options.enable_allowed_pm_users &&
+ !::AllowedPmUser.exists?(user_id: recipient.id, allowed_pm_user_id: sender.id)
)
+ end
+
+ def resolve_recipients!(run)
+ usernames = normalize_usernames(run.parameter("target_usernames"))
+ node_error!(run, :recipient_blank) if usernames.empty?
+
+ usernames.map { |username| resolve_recipient!(run, username) }
+ end
+
+ def normalize_usernames(value)
+ Array
+ .wrap(value)
+ .flat_map { |entry| entry.to_s.split(",") }
+ .map { |username| username.strip.delete_prefix("@") }
+ .reject(&:blank?)
+ .uniq(&:downcase)
+ end
+
+ def resolve_recipient!(run, username)
+ recipient = run.exec_ctx.find_user(username:, item_index: run.item_index)
+
+ # Checked upfront because the chat services either silently drop such recipients
+ # (falling back to a self-DM) or let staff senders store messages nobody will see.
+ reason =
+ if recipient.staged?
+ :recipient_staged
+ elsif recipient.suspended?
+ :recipient_suspended
+ elsif !recipient.active?
+ :recipient_inactive
+ elsif !recipient.user_option&.chat_enabled
+ :recipient_chat_disabled
+ elsif !recipient.guardian.can_chat?
+ :recipient_cannot_chat
+ end
+ node_error!(run, reason, username: recipient.username) if reason
+
+ recipient
+ end
+
+ # DM permissions are left to the service's policies; these would otherwise surface as
+ # a missing target or a vague failure after the DM channel was created.
+ def ensure_sender_can_chat!(run, sender)
+ reason =
+ if !sender.user_option&.chat_enabled
+ :sender_chat_disabled
+ elsif !sender.guardian.can_chat?
+ :sender_cannot_chat
+ end
+ node_error!(run, reason, sender: sender.username) if reason
+ end
+
+ def create_direct_message_channel(run, sender, usernames, target, labels)
+ Chat::CreateDirectMessageChannel.call(
+ guardian: sender.guardian,
+ # Upserting makes re-runs reuse the group DM with the same members.
+ params: {
+ target_usernames: usernames,
+ upsert: true,
+ },
+ ) do |result|
+ on_success { |channel:| channel }
+ %i[targets_allow_dms_from_user satisfies_dms_max_users_limit].each do |policy_name|
+ on_failed_policy(policy_name) do |policy|
+ node_error!(run, :"#{target}_blocked", **labels, reason: policy.reason)
+ end
+ end
+ on_failed_policy(:can_create_direct_message) do
+ node_error!(run, :sender_cannot_create_dm, **labels)
+ end
+ on_failed_policy(:actor_allows_dms) do
+ node_error!(run, :sender_dms_disabled, **labels)
+ end
+ on_failure do
+ node_error!(run, :failed, step: ChatServiceFailure.failed_step_name(result))
+ end
end
+ end
+ def create_message(run, target, guardian, channel, **labels)
Chat::CreateMessage.call(
- guardian: Discourse.system_user.guardian,
+ guardian:,
params: {
chat_channel_id: channel.id,
- message: message,
+ message: run.message,
},
- ) do
- on_success { { "channel_id" => channel.id, "message" => message } }
- on_failed_contract do |contract|
- raise_node_error!(
+ ) do |result|
+ on_success do |message_instance:|
+ run.exec_ctx.log.info(
I18n.t(
- "discourse_workflows.errors.send_chat_message.invalid_params",
- errors: contract.errors.full_messages.join(", "),
+ "discourse_workflows.logs.send_chat_message.sent_to_#{target}",
+ item_index: run.item_index,
+ message_id: message_instance.id,
+ **labels,
),
)
+ {
+ "channel_id" => channel.id,
+ "message_id" => message_instance.id,
+ "message" => run.message,
+ }
end
- on_model_not_found(:channel) do
- raise_node_error!(
- I18n.t(
- "discourse_workflows.errors.send_chat_message.channel_not_found",
- channel_id: channel_id,
- ),
- )
+ on_failed_contract { |contract| invalid_params!(run, contract) }
+ on_model_errors(:message_instance) do |message_instance|
+ invalid_params!(run, message_instance)
+ end
+ on_failed_policy(:channel_allows_message_creation) do |policy|
+ node_error!(run, :"#{target}_blocked", **labels, reason: policy.reason)
end
on_failure do
- raise_node_error!(I18n.t("discourse_workflows.errors.send_chat_message.failed"))
+ node_error!(run, :failed, step: ChatServiceFailure.failed_step_name(result))
end
end
end
+
+ def invalid_params!(run, record)
+ node_error!(run, :invalid_params, errors: record.errors.full_messages.join(", "))
+ end
+
+ def add_hint(run, key, **args)
+ run.exec_ctx.add_execution_hints(
+ {
+ message: I18n.t("discourse_workflows.hints.send_chat_message.#{key}", **args),
+ location: "outputPane",
+ },
+ )
+ end
+
+ def node_error!(run, key, **args)
+ raise_node_error!(
+ I18n.t("discourse_workflows.errors.send_chat_message.#{key}", **args),
+ item_index: run.item_index,
+ )
+ end
end
end
end
diff --git a/plugins/chat/spec/integration/workflows_send_chat_dm_spec.rb b/plugins/chat/spec/integration/workflows_send_chat_dm_spec.rb
new file mode 100644
index 00000000000..a6e620501d9
--- /dev/null
+++ b/plugins/chat/spec/integration/workflows_send_chat_dm_spec.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+RSpec.describe "Workflow: send chat direct message to a user" do
+ fab!(:admin)
+
+ def publish_workflow(trigger_type, trigger_configuration = {})
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", trigger_type, configuration: trigger_configuration
+ g.node "action-1",
+ "action:send_chat_message",
+ configuration: {
+ "target" => "user",
+ "target_usernames" => "={{ $trigger.user.username }}",
+ "message" => "=Welcome {{ $trigger.user.username }}!",
+ }
+ g.chain "trigger-1", "action-1"
+ end
+
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ def run_last_enqueued_workflow
+ job_data = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.new.execute(job_data["args"].first.symbolize_keys)
+ end
+
+ before do
+ SiteSetting.chat_enabled = true
+ SiteSetting.enable_discourse_workflows = true
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.clear
+ end
+
+ it "sends a direct message from the system user once a user reaches trust level 1" do
+ publish_workflow("trigger:user_trust_level_changed", "new_trust_levels" => [TrustLevel[1].to_s])
+ user = Fabricate(:user, trust_level: TrustLevel[0], refresh_auto_groups: true)
+
+ Promotion.new(user).change_trust_level!(TrustLevel[1])
+ run_last_enqueued_workflow
+
+ execution = DiscourseWorkflows::Execution.last
+ expect(execution.status).to eq("success")
+
+ message = Chat::Message.last
+ expect(message).to have_attributes(
+ user_id: Discourse.system_user.id,
+ message: "Welcome #{user.username}!",
+ )
+ expect(message.chat_channel.chatable.users).to contain_exactly(Discourse.system_user, user)
+ end
+end
diff --git a/plugins/chat/spec/lib/discourse_workflows/nodes/send_chat_message_spec.rb b/plugins/chat/spec/lib/discourse_workflows/nodes/send_chat_message_spec.rb
index 5ff7fdbb7da..3cbacf8e44a 100644
--- a/plugins/chat/spec/lib/discourse_workflows/nodes/send_chat_message_spec.rb
+++ b/plugins/chat/spec/lib/discourse_workflows/nodes/send_chat_message_spec.rb
@@ -5,6 +5,31 @@ RSpec.describe DiscourseWorkflows::Nodes::SendChatMessage::V1 do
before { SiteSetting.chat_enabled = true }
+ def node_error(key, scope: :send_chat_message, item_index: 0, **args)
+ node_error_message(key, scope:, item_index:, **args)
+ end
+
+ def log_messages(ctx)
+ ctx.log.entries.map { |entry| entry["message"] }
+ end
+
+ def hint_messages(ctx)
+ ctx.execution_hints.map { |hint| hint["message"] }
+ end
+
+ def sent_log(target, message, item_index: 0, **args)
+ I18n.t(
+ "discourse_workflows.logs.send_chat_message.sent_to_#{target}",
+ item_index:,
+ message_id: message.id,
+ **args,
+ )
+ end
+
+ def hint(key, **args)
+ I18n.t("discourse_workflows.hints.send_chat_message.#{key}", **args)
+ end
+
describe ".load_options_context" do
fab!(:other_channel) { Fabricate(:chat_channel, name: "Announcements") }
fab!(:closed_channel) { Fabricate(:chat_channel, name: "Closed", status: :closed) }
@@ -56,97 +81,542 @@ RSpec.describe DiscourseWorkflows::Nodes::SendChatMessage::V1 do
end
describe "#execute" do
- def build_exec_ctx(input_items:, parameters:, resolver_context:)
- sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context)
- resolver = DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)
- exec_ctx =
- DiscourseWorkflows::Executor::NodeExecutionContext.new(
- input_items: input_items,
- resolver: resolver,
- parameters: parameters,
- property_schema: described_class.property_schema,
- node_identifier: described_class.identifier,
- resolver_context: resolver_context,
+ it "sends the message resolved for each input item and logs each send" do
+ log = nil
+
+ output =
+ execute_node_output(
+ configuration: {
+ "channel_id" => "={{ $json.target_channel }}",
+ "message" => "={{ $json.text }}",
+ },
+ input_items: [
+ { "json" => { "target_channel" => channel.id, "text" => "First message" } },
+ { "json" => { "target_channel" => channel.id, "text" => "Second message" } },
+ ],
+ ) { |ctx| log = log_messages(ctx) }
+
+ first, second = channel.chat_messages.order(:id).last(2)
+ expect(output.first.map { |item| item["json"] }).to eq(
+ [
+ { "channel_id" => channel.id, "message_id" => first.id, "message" => "First message" },
+ { "channel_id" => channel.id, "message_id" => second.id, "message" => "Second message" },
+ ],
+ )
+ expect([first, second].map(&:message)).to eq(["First message", "Second message"])
+ expect(log).to eq(
+ [
+ sent_log(:channel, first, channel_id: channel.id),
+ sent_log(:channel, second, item_index: 1, channel_id: channel.id),
+ ],
+ )
+ end
+
+ it "rejects expression-resolved channels outside the selectable channel scope" do
+ closed_channel = Fabricate(:chat_channel, name: "Closed", status: :closed)
+
+ expect {
+ execute_node_output(
+ configuration: {
+ "channel_id" => "={{ $json.target_channel }}",
+ "message" => "Hidden target",
+ },
+ item: {
+ "json" => {
+ "target_channel" => closed_channel.id,
+ },
+ },
+ )
+ }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ node_error(:channel_not_found, channel_id: closed_channel.id),
+ )
+ expect(closed_channel.chat_messages).to be_empty
+ end
+
+ it "rejects direct message channels outside the selectable channel scope" do
+ dm_channel = Fabricate(:direct_message_channel)
+
+ expect {
+ execute_node_output(
+ configuration: {
+ "channel_id" => dm_channel.id.to_s,
+ "message" => "Hidden target",
+ },
)
+ }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ node_error(:channel_not_found, channel_id: dm_channel.id.to_s),
+ )
+ expect(dm_channel.chat_messages).to be_empty
+ end
- [exec_ctx, resolver, sandbox]
+ it "explains why the channel refused the message" do
+ channel.update!(status: :read_only)
+ configuration = { "channel_id" => channel.id.to_s, "message" => "Hello" }
+ node = described_class.new(parameters: configuration)
+ # Only open channels are selectable, so simulate a status change after selection.
+ allow(node).to receive(:selectable_chat_channel).and_return(channel)
+
+ expect { execute_node_output(configuration:, node:) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ node_error(
+ :channel_blocked,
+ channel_id: channel.id,
+ reason: I18n.t("chat.errors.channel_new_message_disallowed.read_only"),
+ ),
+ )
+ expect(channel.chat_messages).to be_empty
end
+ end
- it "resolves message expressions for each input item" do
- input_items = [
- { "json" => { "text" => "First message" } },
- { "json" => { "text" => "Second message" } },
+ describe "#execute with a failing item" do
+ let(:configuration) do
+ { "channel_id" => "={{ $json.channel_id }}", "message" => "={{ $json.text }}" }
+ end
+ let(:input_items) do
+ [
+ { "json" => { "channel_id" => channel.id, "text" => "First" } },
+ { "json" => { "channel_id" => -1, "text" => "Second" } },
+ { "json" => { "channel_id" => channel.id, "text" => "Third" } },
]
- parameters = { "channel_id" => channel.id.to_s, "message" => "={{ $json.text }}" }
- resolver_context = { "$json" => {} }
- exec_ctx, resolver, sandbox = build_exec_ctx(input_items:, parameters:, resolver_context:)
-
- output = described_class.new(parameters: parameters).execute(exec_ctx)
+ end
+ let(:item_error) { node_error(:channel_not_found, item_index: 1, channel_id: -1) }
- expect(output.first.map { |item| item["json"]["message"] }).to eq(
- ["First message", "Second message"],
+ it "stops at the failing item by default" do
+ expect { execute_node_output(configuration:, input_items:) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ item_error,
)
- expect(channel.chat_messages.order(:id).last(2).map(&:message)).to eq(
- ["First message", "Second message"],
+ expect(channel.chat_messages.sole.message).to eq("First")
+ end
+
+ it "reports the failure on its own item when continuing on error" do
+ output =
+ execute_node_output(
+ configuration:,
+ input_items:,
+ node_settings: {
+ "onError" => "continueErrorOutput",
+ },
+ )
+
+ expect(output.length).to eq(1)
+ sent, failed, sent_after = output.first
+ expect(channel.chat_messages.order(:id).pluck(:message)).to eq(%w[First Third])
+ expect([sent, sent_after].map { |item| item["json"]["message"] }).to eq(%w[First Third])
+ expect(output.first.map { |item| item.key?("error") }).to eq([false, true, false])
+ expect(failed).to include(
+ "json" => {
+ "channel_id" => -1,
+ "text" => "Second",
+ },
+ "error" => include("message" => item_error),
+ "__failed" => true,
+ "pairedItem" => {
+ "item" => 1,
+ },
)
- ensure
- resolver&.dispose
- sandbox&.dispose
end
+ end
- it "resolves channel_id expressions" do
- input_items = [{ "json" => { "target_channel" => channel.id } }]
- parameters = {
- "channel_id" => "={{ $json.target_channel }}",
- "message" => "Hello from expression",
- }
- resolver_context = { "$json" => {} }
- exec_ctx, resolver, sandbox = build_exec_ctx(input_items:, parameters:, resolver_context:)
+ describe "#execute with a user target" do
+ fab!(:recipient) { Fabricate(:user, username: "bob", refresh_auto_groups: true) }
+ fab!(:sender) { Fabricate(:user, username: "alice", refresh_auto_groups: true) }
- described_class.new(parameters: parameters).execute(exec_ctx)
+ def send_dm(input_items: nil, node_settings: {}, **parameters, &block)
+ execute_node_output(
+ configuration: {
+ "target" => "user",
+ "target_usernames" => [recipient.username],
+ "message" => "Hello there",
+ }.merge(parameters.stringify_keys),
+ input_items:,
+ node_settings:,
+ &block
+ )
+ end
- expect(channel.chat_messages.order(:id).last.message).to eq("Hello from expression")
- ensure
- resolver&.dispose
- sandbox&.dispose
+ def dm_user_ids(channel_id)
+ Chat::Channel.find(channel_id).chatable.users.pluck(:id)
end
- it "rejects expression-resolved channels outside the selectable channel scope" do
- closed_channel = Fabricate(:chat_channel, name: "Closed", status: :closed)
- input_items = [{ "json" => { "target_channel" => closed_channel.id } }]
- parameters = { "channel_id" => "={{ $json.target_channel }}", "message" => "Hidden target" }
- resolver_context = { "$json" => {} }
- exec_ctx, resolver, sandbox = build_exec_ctx(input_items:, parameters:, resolver_context:)
-
- expect { described_class.new(parameters: parameters).execute(exec_ctx) }.to raise_error(
- I18n.t(
- "discourse_workflows.errors.send_chat_message.channel_not_found",
- channel_id: closed_channel.id,
- ),
+ def expect_no_dm_side_effects(&block)
+ expect(&block).to not_change { Chat::DirectMessageChannel.count }.and not_change {
+ Chat::Message.count
+ }
+ end
+
+ it "sends a direct message from the system user to the recipient" do
+ hints = nil
+ log = nil
+
+ output =
+ send_dm do |ctx|
+ hints = hint_messages(ctx)
+ log = log_messages(ctx)
+ end
+
+ json = output.first.first["json"]
+ message = Chat::Message.find(json["message_id"])
+ expect(json).to eq(
+ "channel_id" => message.chat_channel_id,
+ "message_id" => message.id,
+ "message" => "Hello there",
+ "username" => recipient.username,
+ )
+ expect(message).to have_attributes(message: "Hello there", user_id: Discourse.system_user.id)
+ expect(dm_user_ids(json["channel_id"])).to contain_exactly(
+ Discourse.system_user.id,
+ recipient.id,
+ )
+ expect(hints).to be_empty
+ expect(log).to eq(
+ [
+ sent_log(
+ :user,
+ message,
+ sender: Discourse.system_user.username,
+ username: recipient.username,
+ ),
+ ],
)
- expect(closed_channel.chat_messages).to be_empty
- ensure
- resolver&.dispose
- sandbox&.dispose
end
- it "rejects direct message channels outside the selectable channel scope" do
- dm_channel = Fabricate(:direct_message_channel)
- parameters = { "channel_id" => dm_channel.id.to_s, "message" => "Hidden target" }
- resolver_context = { "$json" => {} }
- exec_ctx, resolver, sandbox =
- build_exec_ctx(input_items: [{ "json" => {} }], parameters:, resolver_context:)
-
- expect { described_class.new(parameters: parameters).execute(exec_ctx) }.to raise_error(
- I18n.t(
- "discourse_workflows.errors.send_chat_message.channel_not_found",
- channel_id: dm_channel.id.to_s,
- ),
+ it "doesn't leave a new direct message channel behind when the message is rejected" do
+ SiteSetting.chat_maximum_message_length = 100
+
+ expect {
+ expect { send_dm(message: "x" * 101) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ /#{Regexp.escape(I18n.t("discourse_workflows.errors.send_chat_message.invalid_params", errors: ""))}/,
+ )
+ }.to not_change { Chat::DirectMessageChannel.count }.and not_change {
+ Chat::UserChatChannelMembership.count
+ }.and not_change { Chat::DirectMessage.count }
+ end
+
+ it "fails when the recipient username is blank" do
+ expect { send_dm(target_usernames: " ") }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ node_error(:recipient_blank),
)
- expect(dm_channel.chat_messages).to be_empty
- ensure
- resolver&.dispose
- sandbox&.dispose
+ end
+
+ {
+ "is staged" => [:recipient_staged, -> { recipient.update!(staged: true) }],
+ "is suspended" => [
+ :recipient_suspended,
+ -> { recipient.update!(suspended_till: 1.day.from_now, suspended_at: Time.zone.now) },
+ ],
+ "is inactive" => [:recipient_inactive, -> { recipient.update!(active: false) }],
+ "disabled chat" => [
+ :recipient_chat_disabled,
+ -> { recipient.user_option.update!(chat_enabled: false) },
+ ],
+ "is not allowed to chat" => [
+ :recipient_cannot_chat,
+ -> { SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:staff] },
+ ],
+ }.each do |condition, (error_key, setup)|
+ it "fails when the recipient #{condition}" do
+ instance_exec(&setup)
+
+ expect { send_dm }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ node_error(error_key, username: recipient.username),
+ )
+ end
+ end
+
+ it "fails when the sender is anonymous" do
+ expect {
+ send_dm(actor_username: DiscourseWorkflows::AnonymousActor::USERNAME)
+ }.to raise_error(DiscourseWorkflows::NodeError, node_error(:sender_anonymous))
+ end
+
+ {
+ "disabled chat" => [
+ :sender_chat_disabled,
+ -> { sender.user_option.update!(chat_enabled: false) },
+ ],
+ "is not allowed to chat" => [
+ :sender_cannot_chat,
+ -> do
+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:trust_level_2]
+ recipient.update!(trust_level: TrustLevel[2])
+ Group.refresh_automatic_groups_for_user!(recipient)
+ end,
+ ],
+ }.each do |condition, (error_key, setup)|
+ it "fails when the sender #{condition}" do
+ instance_exec(&setup)
+
+ expect { send_dm(actor_username: sender.username) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ node_error(error_key, sender: sender.username),
+ )
+ end
+ end
+
+ {
+ "is not allowed to send direct messages" => [
+ :sender_cannot_create_dm,
+ -> { SiteSetting.direct_message_enabled_groups = Group::AUTO_GROUPS[:staff] },
+ ],
+ "disabled personal messages" => [
+ :sender_dms_disabled,
+ -> { sender.user_option.update!(allow_private_messages: false) },
+ ],
+ }.each do |condition, (error_key, setup)|
+ it "fails without creating a direct message when the sender #{condition}" do
+ instance_exec(&setup)
+
+ expect_no_dm_side_effects do
+ expect { send_dm(actor_username: sender.username) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ node_error(error_key, sender: sender.username),
+ )
+ end
+ end
+ end
+
+ it "doesn't hint at a bypass when the direct message is not delivered" do
+ staff_sender = Fabricate(:moderator, refresh_auto_groups: true)
+ recipient.user_option.update!(allow_private_messages: false)
+ MutedUser.create!(user_id: staff_sender.id, muted_user_id: recipient.id)
+ hints = nil
+
+ output =
+ send_dm(
+ actor_username: staff_sender.username,
+ node_settings: {
+ "onError" => "continueRegularOutput",
+ },
+ ) { |ctx| hints = ctx.execution_hints }
+
+ expect(output.first.sole).to include("error")
+ expect(hints).to be_empty
+ end
+
+ context "with several recipients" do
+ fab!(:carol) { Fabricate(:user, username: "carol", refresh_auto_groups: true) }
+ fab!(:dave) { Fabricate(:user, username: "dave", refresh_auto_groups: true) }
+
+ let(:usernames) { [recipient.username, carol.username, dave.username] }
+
+ it "accepts comma-separated usernames, dropping blanks, duplicates and leading @" do
+ output = send_dm(target_usernames: [" @bob, carol ,, BOB", "dave"])
+
+ expect(output.first.map { |item| item["json"]["username"] }).to eq(usernames)
+ end
+
+ context "when sending individual direct messages" do
+ it "fails the whole item without sending anything when one of the recipients can't receive it" do
+ carol.update!(active: false)
+ output = nil
+ item_errors = nil
+
+ expect_no_dm_side_effects do
+ output =
+ send_dm(
+ target_usernames: usernames,
+ node_settings: {
+ "onError" => "continueErrorOutput",
+ },
+ ) { |ctx| item_errors = ctx.metadata["item_errors"] }
+ end
+
+ expect(output.first.sole).to include(
+ "error" =>
+ include("message" => node_error(:recipient_inactive, username: carol.username)),
+ "pairedItem" => {
+ "item" => 0,
+ },
+ )
+ expect(item_errors.size).to eq(1)
+ end
+
+ it "sends each recipient a separate direct message and fails only the refused ones" do
+ MutedUser.create!(user_id: carol.id, muted_user_id: sender.id)
+ item_errors = nil
+
+ output =
+ send_dm(
+ target_usernames: usernames,
+ actor_username: sender.username,
+ node_settings: {
+ "onError" => "continueErrorOutput",
+ },
+ ) { |ctx| item_errors = ctx.metadata["item_errors"] }
+
+ items = output.first
+ delivered_to_bob, refused, delivered_to_dave = items
+ expect(items.map { |item| item["pairedItem"] }).to all(eq("item" => 0))
+ expect(items.map { |item| item.key?("__failed") }).to eq([false, true, false])
+ expect(
+ [delivered_to_bob, delivered_to_dave].map { |item| item["json"]["username"] },
+ ).to eq([recipient.username, dave.username])
+ expect(refused).to include(
+ "error" =>
+ include(
+ "message" =>
+ node_error(
+ :user_blocked,
+ sender: sender.username,
+ username: carol.username,
+ reason: I18n.t("chat.errors.not_accepting_dms", username: carol.username),
+ ),
+ ),
+ )
+ expect(item_errors.size).to eq(1)
+ expect(
+ [delivered_to_bob, delivered_to_dave].map do |item|
+ dm_user_ids(item["json"]["channel_id"])
+ end,
+ ).to match(
+ [contain_exactly(sender.id, recipient.id), contain_exactly(sender.id, dave.id)],
+ )
+ end
+ end
+
+ context "when sending a group direct message" do
+ it "sends one group direct message to all recipients and reuses it on re-runs" do
+ log = nil
+ output =
+ send_dm(
+ target_usernames: usernames,
+ target: "group",
+ actor_username: sender.username,
+ ) { |ctx| log = log_messages(ctx) }
+
+ item = output.first.sole
+ channel_id = item["json"]["channel_id"]
+ expect(item["json"]).to include("usernames" => usernames, "message" => "Hello there")
+ expect(item["pairedItem"]).to eq("item" => 0)
+ expect(Chat::Channel.find(channel_id).chatable).to be_group
+ expect(dm_user_ids(channel_id)).to contain_exactly(
+ sender.id,
+ recipient.id,
+ carol.id,
+ dave.id,
+ )
+ expect(log).to eq(
+ [
+ sent_log(
+ :group,
+ Chat::Message.find(item["json"]["message_id"]),
+ sender: sender.username,
+ usernames: "'bob', 'carol', 'dave'",
+ ),
+ ],
+ )
+
+ rerun = nil
+ expect {
+ rerun =
+ send_dm(
+ target_usernames: usernames.reverse,
+ target: "group",
+ actor_username: sender.username,
+ # Identical consecutive messages are rejected as duplicates.
+ message: "Hello again",
+ )
+ }.not_to change { Chat::DirectMessageChannel.count }
+ expect(rerun.first.sole["json"]["channel_id"]).to eq(channel_id)
+ expect(Chat::Message.where(chat_channel_id: channel_id).count).to eq(2)
+ end
+
+ it "explains why a repeated identical message is rejected" do
+ parameters = {
+ target_usernames: usernames,
+ target: "group",
+ actor_username: sender.username,
+ }
+ send_dm(**parameters)
+
+ expect { send_dm(**parameters) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ /\A#{Regexp.escape(I18n.t("discourse_workflows.errors.send_chat_message.invalid_params", errors: ""))}.+ \[item 0\]\z/,
+ )
+ end
+
+ it "drops the sender from the recipients" do
+ output =
+ send_dm(
+ target_usernames: [sender.username, *usernames],
+ target: "group",
+ actor_username: sender.username,
+ )
+
+ json = output.first.sole["json"]
+ expect(json["usernames"]).to eq(usernames)
+ expect(dm_user_ids(json["channel_id"])).to contain_exactly(
+ sender.id,
+ recipient.id,
+ carol.id,
+ dave.id,
+ )
+ end
+
+ it "posts to the personal chat with a hint when the sender is the only recipient" do
+ hints = nil
+ output =
+ send_dm(
+ target_usernames: sender.username,
+ target: "group",
+ actor_username: sender.username,
+ ) { |ctx| hints = ctx.execution_hints }
+
+ json = output.first.sole["json"]
+ expect(json["usernames"]).to eq([sender.username])
+ expect(dm_user_ids(json["channel_id"])).to eq([sender.id])
+ expect(hints).to eq(
+ [
+ {
+ "message" => hint(:self_message, username: sender.username),
+ "location" => "outputPane",
+ },
+ ],
+ )
+ end
+
+ it "explains why the group is too large and creates nothing" do
+ SiteSetting.chat_max_direct_message_users = 2
+
+ expect_no_dm_side_effects do
+ expect {
+ send_dm(target_usernames: usernames, target: "group", actor_username: sender.username)
+ }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ node_error(
+ :group_blocked,
+ sender: sender.username,
+ usernames: "'bob', 'carol', 'dave'",
+ reason: I18n.t("chat.errors.over_chat_max_direct_message_users", count: 2),
+ ),
+ )
+ end
+ end
+
+ it "hints at each recipient whose preferences a staff sender bypassed" do
+ carol.user_option.update!(allow_private_messages: false)
+ dave.user_option.update!(enable_allowed_pm_users: true)
+ hints = nil
+
+ send_dm(target_usernames: usernames, target: "group") { |ctx| hints = hint_messages(ctx) }
+
+ expect(hints).to eq(
+ [carol, dave].map do |user|
+ hint(
+ :preferences_bypassed,
+ username: user.username,
+ sender: Discourse.system_user.username,
+ )
+ end,
+ )
+ end
+ end
end
end
end