slack_agent.rb 2.3 KB

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