A Slack Bot that pulls Pixiv information and posts the full image(s) into Slack, with iOS shortcuts.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
2.6 KiB

9 years ago
  1. module SlackRubyBot
  2. class App
  3. cattr_accessor :hooks
  4. include SlackRubyBot::Hooks::Hello
  5. include SlackRubyBot::Hooks::Message
  6. def initialize
  7. SlackRubyBot.configure do |config|
  8. config.token = ENV['SLACK_API_TOKEN'] || fail("Missing ENV['SLACK_API_TOKEN'].")
  9. config.aliases = ENV['SLACK_RUBY_BOT_ALIASES'].split(' ') if ENV['SLACK_RUBY_BOT_ALIASES']
  10. end
  11. Slack.configure do |config|
  12. config.token = SlackRubyBot.config.token
  13. end
  14. end
  15. def config
  16. SlackRubyBot.config
  17. end
  18. def self.instance
  19. @instance ||= SlackRubyBot::App.new
  20. end
  21. def run
  22. auth!
  23. start!
  24. end
  25. def stop!
  26. client.stop
  27. end
  28. private
  29. def logger
  30. @logger ||= begin
  31. $stdout.sync = true
  32. Logger.new(STDOUT)
  33. end
  34. end
  35. def start!
  36. loop do
  37. begin
  38. client.start!
  39. rescue Slack::Web::Api::Error => e
  40. logger.error e
  41. case e.message
  42. when 'migration_in_progress'
  43. sleep 1 # ignore, try again
  44. else
  45. raise e
  46. end
  47. rescue Faraday::Error::TimeoutError, Faraday::Error::ConnectionFailed, Faraday::Error::SSLError => e
  48. logger.error e
  49. sleep 1 # ignore, try again
  50. rescue StandardError => e
  51. logger.error e
  52. raise e
  53. ensure
  54. @client = nil
  55. end
  56. end
  57. end
  58. def client
  59. @client ||= begin
  60. client = Slack::RealTime::Client.new
  61. hooks.each do |hook|
  62. client.on hook do |data|
  63. begin
  64. send hook, client, data
  65. rescue StandardError => e
  66. logger.error e
  67. begin
  68. client.message(channel: data['channel'], text: e.message) if data.key?('channel')
  69. rescue
  70. # ignore
  71. end
  72. end
  73. end
  74. end
  75. client
  76. end
  77. end
  78. def auth!
  79. auth = client.web_client.auth_test
  80. SlackRubyBot.configure do |config|
  81. config.url = auth['url']
  82. config.team = auth['team']
  83. config.user = auth['user']
  84. config.team_id = auth['team_id']
  85. config.user_id = auth['user_id']
  86. end
  87. logger.info "Welcome '#{SlackRubyBot.config.user}' to the '#{SlackRubyBot.config.team}' team at #{SlackRubyBot.config.url}."
  88. end
  89. def reset!
  90. SlackRubyBot.configure do |config|
  91. config.url = nil
  92. config.team = nil
  93. config.user = nil
  94. config.team_id = nil
  95. config.user_id = nil
  96. end
  97. end
  98. end
  99. end