slack_agent.rb 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. module Agents
  2. class SlackAgent < Agent
  3. DEFAULT_USERNAME = 'Huginn'
  4. cannot_be_scheduled!
  5. cannot_create_events!
  6. gem_dependency_check { defined?(Slack) }
  7. description <<-MD
  8. #{'## Include `slack-notifier` in your Gemfile to use this Agent!' if dependencies_missing?}
  9. The SlackAgent lets you receive events and send notifications to [Slack](https://slack.com/).
  10. To get started, you will first need to setup an incoming webhook.
  11. Go to, <code>https://<em>your_team_name</em>.slack.com/services/new/incoming-webhook</code>,
  12. choose a default channel and add the integration.
  13. Your webhook URL will look like: <code>https://hooks.slack.com/services/<em>random1</em>/<em>random2</em>/<em>token</em></code>
  14. Once the webhook has been setup it can be used to post to other channels or ping team members.
  15. To send a private message to team-mate, assign his username as `@username` to the channel option.
  16. To communicate with a different webhook on slack, assign your custom webhook name to the webhook option.
  17. Messages can also be formatted using [Liquid](https://github.com/cantino/huginn/wiki/Formatting-Events-using-Liquid)
  18. MD
  19. def default_options
  20. {
  21. 'webhook_url' => 'https://hooks.slack.com/services/...',
  22. 'channel' => '#general',
  23. 'username' => DEFAULT_USERNAME,
  24. 'message' => "Hey there, It's Huginn",
  25. }
  26. end
  27. def validate_options
  28. unless options['webhook_url'].present? ||
  29. (options['auth_token'].present? && options['team_name'].present?) # compatibility
  30. errors.add(:base, "webhook_url is required")
  31. end
  32. errors.add(:base, "channel is required") unless options['channel'].present?
  33. end
  34. def working?
  35. received_event_without_error?
  36. end
  37. def webhook_url
  38. case
  39. when url = interpolated[:webhook_url].presence
  40. url
  41. when (team = interpolated[:team_name].presence) && (token = interpolated[:auth_token])
  42. webhook = interpolated[:webhook].presence || 'incoming-webhook'
  43. # old style webhook URL
  44. "https://#{Rack::Utils.escape_path(team)}.slack.com/services/hooks/#{Rack::Utils.escape_path(webhook)}?token=#{Rack::Utils.escape(token)}"
  45. end
  46. end
  47. def username
  48. interpolated[:username].presence || DEFAULT_USERNAME
  49. end
  50. def slack_notifier
  51. @slack_notifier ||= Slack::Notifier.new(webhook_url, username: username)
  52. end
  53. def receive(incoming_events)
  54. incoming_events.each do |event|
  55. opts = interpolated(event)
  56. slack_notifier.ping opts[:message], channel: opts[:channel], username: opts[:username]
  57. end
  58. end
  59. end
  60. end