Create custom Automations

Probably the best place to start looking is in the automation script that’s added to the Data Explorer plugin: discourse-data-explorer/plugin.rb at main · discourse/discourse-data-explorer · GitHub. It’s also worth looking at the Automation plugin’s existing scripts and triggers:

Since there’s not much information on Meta about adding custom automations, here’s an example plugin.rb file that adds a script to update a user’s Activity Summary email preference. The script can be triggered by the Automation plugin’s ‘user_added_to_group’ or ‘user_removed_from_group’ triggers.

# frozen_string_literal: true

# name: automation-script-example
# about: An example of how to add a script to an automation
# version: 0.0.1
# authors: scossar

enabled_site_setting :automation_script_example_enabled

after_initialize do
  reloadable_patch do
    if defined?(DiscourseAutomation)
      DiscourseAutomation::Scriptable::USER_UPDATE_SUMMARY_EMAIL_OPTIONS =
      ) do

        field :email_digests, component: :boolean

        version 1
        triggerables [:user_added_to_group, :user_removed_from_group]

        script do |context, fields, automation|
          if automation.script == "user_update_summary_email_options" && (context["kind"] == "user_added_to_group" || context["kind"] == "user_removed_from_group")
            user_id = context["user"].id
            digest_option = fields.dig("email_digests", "value")
            user_option = UserOption.find_by(user_id: user_id)

            if (user_option)
              user_option.update(email_digests: digest_option)

The full plugin code is here: GitHub - scossar/automation-script-example: An example of how to add a custom script to the Discourse Automation plugin..

:warning: please don’t use this code as it is on a production site. I hadn’t looked at the Automation code before this evening. If I get any feedback about potential issues with the code, I’ll update this post and the GitHub repo.

Edit: my concern was how to best deal with the case of multiple automation scripts being triggered by either the ‘user_added_to_group’ or ‘user_removed_from_group’ triggers. The initial version of the plugin was checking for:


but that felt kind of flaky. What if another script was added that also had an email_digests key?

The updated code passes the automation parameter to the code block and checks:

automation.script == "user_update_summary_email_options"

That should ensure that the script won’t be run for the wrong automation.

… thinking about it some more, it’s unlikely the script could get triggered by an automation it wasn’t configured for :slight_smile: