slack_agent.rb 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. module Agents
  2. class SlackAgent < Agent
  3. cannot_be_scheduled!
  4. cannot_create_events!
  5. DEFAULT_WEBHOOK = 'incoming-webhook'
  6. DEFAULT_USERNAME = 'Huginn'
  7. description <<-MD
  8. The SlackAgent lets you receive events and send notifications to [slack](https://slack.com/).
  9. To get started, you will first need to setup an incoming webhook.
  10. Go to, https://`your_team_name`.slack.com/services/new/incoming-webhook,
  11. choose a default channel and add the integration.
  12. Your webhook URL will look like:
  13. https://`your_team_name`.slack.com/services/hooks/incoming-webhook?token=`your_auth_token`
  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. 'team_name' => 'your_team_name',
  22. 'auth_token' => 'your_auth_token',
  23. 'channel' => '#general',
  24. 'username' => DEFAULT_USERNAME,
  25. 'message' => "Hey there, It's Huginn",
  26. 'webhook' => DEFAULT_WEBHOOK
  27. }
  28. end
  29. def validate_options
  30. errors.add(:base, "auth_token is required") unless options['auth_token'].present?
  31. errors.add(:base, "team_name is required") unless options['team_name'].present?
  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
  38. interpolated[:webhook].presence || DEFAULT_WEBHOOK
  39. end
  40. def username
  41. interpolated[:username].presence || DEFAULT_USERNAME
  42. end
  43. def slack_notifier
  44. @slack_notifier ||= Slack::Notifier.new(interpolated[:team_name], interpolated[:auth_token], webhook, username: username)
  45. end
  46. def receive(incoming_events)
  47. incoming_events.each do |event|
  48. opts = interpolated(event.payload)
  49. slack_notifier.ping opts[:message], channel: opts[:channel], username: opts[:username]
  50. end
  51. end
  52. end
  53. end