创建自定义自动化

也许最好的起点是查看添加到 Data Explorer 插件的自动化脚本:discourse-data-explorer/plugin.rb at main · discourse/discourse-data-explorer · GitHub Automation 插件现有的脚本和触发器:https://github.com/discourse/discourse-automation/tree/main/lib/discourse_automation

由于 Meta 上关于添加自定义自动化的信息不多,这里有一个 plugin.rb 文件示例,它添加了一个脚本来更新用户的“活动摘要”电子邮件偏好设置。该脚本可以由 Automation 插件的“user_added_to_group”或“user_removed_from_group”触发器触发。

# 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 =
        "user_update_summary_email_options"
      add_automation_scriptable(
        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)
            end
          end
        end
      end
    end
  end
end

完整的插件代码在这里:https://github.com/scossar/automation-script-example。

:warning: 请不要在生产环境中使用此代码。我直到今天晚上才查看 Automation 代码。如果我发现有关代码潜在问题的反馈,我会更新此帖子和 GitHub 仓库。

编辑:我担心的是如何最好地处理由“user_added_to_group”或“user_removed_from_group”触发器触发的多个自动化脚本的情况。插件的初始版本检查了:

fields.has_key?("email_digests")

但这感觉有点不可靠。如果添加了另一个也具有 email_digests 键的脚本怎么办?

更新后的代码将 automation 参数传递给代码块并进行检查:

automation.script == "user_update_summary_email_options"

这应该可以确保脚本不会为错误的自动化运行。

……再想一想,脚本不太可能被它未配置的自动化触发 :slight_smile:

7 个赞