1
0

slack_agent.rb 2.4 KB

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