Class: Lita::Handlers::Webhook

Inherits:
Handler
  • Object
show all
Defined in:
lib/lita/handlers/webhook.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(robot) ⇒ Webhook

Returns a new instance of Webhook.



7
8
9
10
# File 'lib/lita/handlers/webhook.rb', line 7

def initialize(robot)
  @robot = robot
  @client = robot.chat_service.client
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



4
5
6
# File 'lib/lita/handlers/webhook.rb', line 4

def client
  @client
end

#robotObject (readonly)

Returns the value of attribute robot.



5
6
7
# File 'lib/lita/handlers/webhook.rb', line 5

def robot
  @robot
end

Instance Method Details

#callback(request, response) ⇒ Object



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
# File 'lib/lita/handlers/webhook.rb', line 16

def callback(request, response)
  body = request.body.read
  signature = request.env['HTTP_X_LINE_SIGNATURE']
  unless client.validate_signature(body, signature)
    log.info "Unvalidate Signature: #{signature}"
    response.status = 401
  else
    response.status = 200
    events = client.parse_events_from(body)
    events.map do |event|
      case event
      when ::Line::Bot::Event::Message
        case event.type
        when ::Line::Bot::Event::MessageType::Text
          log.info "Webhook: #{DateTime.strptime(event['timestamp'].to_s, '%Q')}[#{event.message['id']}##{event.message['type']}]: #{event.message['text']} "
          user = create_user event['source']
          source = Lita::Source.new(user: user, room: event['replyToken'])
          message = Lita::Message.new(robot, event.message['text'], source)
          robot.receive(message)
        end
      end
    end
  end
  response.finish
end

#create_user(event_source) ⇒ Object



42
43
44
45
46
47
# File 'lib/lita/handlers/webhook.rb', line 42

def create_user(event_source)
  source_type = event_source['type']
  user = Lita::User.create(event_source["#{source_type}Id"], { type: source_type })
  log.info "Create User: #{user.id} - #{user.}"
  user
end

#logObject



12
13
14
# File 'lib/lita/handlers/webhook.rb', line 12

def log
  Lita.logger
end