Class: BubBot::WebServer

Inherits:
Object
  • Object
show all
Defined in:
lib/bub_bot/web_server.rb

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/bub_bot/web_server.rb', line 15

def call(env)
  puts ' --- Got request ---'

  # Ignore retries for now.
  if env['HTTP_X_SLACK_RETRY_NUM']
    puts "Ignoring retry: #{env['HTTP_X_SLACK_RETRY_NUM']}, because #{env['HTTP_X_SLACK_RETRY_REASON']}"
    return [200, {}, ['ok']]
  end

  request = Rack::Request.new(env)

  # For easily checking if the server's up
  if request.path == '/' && request.get?
    return [200, {}, ['ok']]

  # When slack sends us a challenge request
  elsif request.path == '/' && request.post?
    params = parse_params(request)
    return [200, {}, [params[:challenge]]] if params[:challenge]

    event = params[:event]

    # Skip messages from bots
    return [200, {}, []] if event[:subtype] == 'bot_message'

    # Make sure this is in the form of 'bub foo'
    unless event[:text].starts_with?(BubBot.configuration.bot_name + ' ')
      puts "skipping non-bub message"
      return [200, {}, []]
    end

    command = BubBot::Slack::CommandParser.get_command(event[:text])

    puts " --- Running command #{command}"

    # Slack will retry any message that takes longer than 3 seconds to complete,
    # so do all message processing in a thread.
    command_thread = Thread.new do
      response =
        begin
          if command
            command.new(event).run
          else
            BubBot::Slack::Response.new("unknown command", slack_client)
          end
        rescue RespondableError => e
          BubBot::Slack::Response.new(e.message, slack_client)
        end

      response.deliver
    end
    command_thread.abort_on_exception = true

    return [200, {}, []]

  #elsif request.path == '/heroku_hook' && request.post?
    #HerokuInterface.new.handle_heroku_webhook(request.body.read)
    #return [200, {}, []]
  else
    raise BubError, "Failed request: #{request.request_method} #{request.path}"
    err 'invalid request'
  end
rescue BubError => e
  puts "Err: #{e.message}"
  return [400, {}, [e.message]]
end