Files
chatwoot/app/services/message_templates/hook_execution_service.rb
Pranav 7e70f7a68a fix: Disable automations on auto-reply emails (#12101)
The term "sorcerer’s apprentice mode" is defined as a bug in a protocol
where, under some circumstances, the receipt of a message causes
multiple messages to be sent, each of which, when received, triggers the
same bug. - RFC3834

Reference: https://github.com/chatwoot/chatwoot/pull/9606

This PR:
- Adds an auto_reply attribute to message.
- Adds an auto_reply attribute to conversation. 
- Disable conversation_created / conversation_opened event if auto_reply
is set.
- Disable message_created event if auto_reply is set.

---------

Co-authored-by: Muhsin Keloth <muhsinkeramam@gmail.com>
2025-08-05 13:17:06 +05:30

60 lines
2.2 KiB
Ruby

class MessageTemplates::HookExecutionService
pattr_initialize [:message!]
def perform
return if conversation.campaign.present?
return if conversation.last_incoming_message.blank?
return if message.auto_reply_email?
trigger_templates
end
private
delegate :inbox, :conversation, to: :message
delegate :contact, to: :conversation
def trigger_templates
::MessageTemplates::Template::OutOfOffice.new(conversation: conversation).perform if should_send_out_of_office_message?
::MessageTemplates::Template::Greeting.new(conversation: conversation).perform if should_send_greeting?
::MessageTemplates::Template::EmailCollect.new(conversation: conversation).perform if inbox.enable_email_collect && should_send_email_collect?
end
def should_send_out_of_office_message?
# should not send if its a tweet message
return false if conversation.tweet?
# should not send for outbound messages
return false unless message.incoming?
# prevents sending out-of-office message if an agent has sent a message in last 5 minutes
# ensures better UX by not interrupting active conversations at the end of business hours
return false if conversation.messages.outgoing.where(private: false).exists?(['created_at > ?', 5.minutes.ago])
inbox.out_of_office? && conversation.messages.today.template.empty? && inbox.out_of_office_message.present?
end
def first_message_from_contact?
conversation.messages.outgoing.count.zero? && conversation.messages.template.count.zero?
end
def should_send_greeting?
# should not send if its a tweet message
return false if conversation.tweet?
first_message_from_contact? && inbox.greeting_enabled? && inbox.greeting_message.present?
end
def email_collect_was_sent?
conversation.messages.where(content_type: 'input_email').present?
end
# TODO: we should be able to reduce this logic once we have a toggle for email collect messages
def should_send_email_collect?
!contact_has_email? && inbox.web_widget? && !email_collect_was_sent?
end
def contact_has_email?
contact.email
end
end
MessageTemplates::HookExecutionService.prepend_mod_with('MessageTemplates::HookExecutionService')