Class: SlackBot::Events::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/slack_bot/events/client.rb

Constant Summary collapse

BASE_API =
"https://slack.com/api"

Instance Method Summary collapse

Instance Method Details

#events_api(handler:, schema:, parsed_data:) ⇒ Object



54
55
56
57
58
59
60
61
62
# File 'lib/slack_bot/events/client.rb', line 54

def events_api(handler:, schema:, parsed_data:)
  return if handler.nil?

  Events.logger.info { schema.tldr } if Events.config.print_tldr

  # This gets rescued in the MessageHandler middleware
  # on_success and on_failure happens there as well
  handler.call(schema: schema, raw_data: parsed_data)
end

#process(type:, socket_event:) ⇒ Object



48
49
50
51
52
# File 'lib/slack_bot/events/client.rb', line 48

def process(type:, socket_event:)
  SlackBot::Events.public_send(:"#{type}_middleware").invoke(type: type, socket_event: socket_event) do
    yield if block_given?
  end
end

#process_message(socket_event:) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/slack_bot/events/client.rb', line 38

def process_message(socket_event:)
  schema_data = Schematize.call(data: socket_event.data)

  listener = find_listener(schema: schema_data[:schema]) # Events.config.listeners[schema_data[:schema]&.type.to_sym]

  SlackBot::Events.message_middleware.invoke_message(websocket: websocket, listener: listener, type: :message, socket_event: socket_event, **schema_data) do
    yield(listener: listener, **schema_data) if block_given?
  end
end

#start!Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/slack_bot/events/client.rb', line 13

def start!
  EventMachine.run do
     websocket.on :open do |socket_event|
      process(type: :open, socket_event: socket_event) { |**| }
    end

    websocket.on :message do |socket_event|
      process_message(socket_event: socket_event) do |listener:, parsed_data:, schema: nil|
        case parsed_data["type"]
        when "events_api"
          events_api(handler: listener&.dig(:handler), schema: schema, parsed_data: parsed_data)
        end
      end
    end

    websocket.on :close do |socket_event|
      process(type: :close, socket_event: socket_event) { |**| }
      @websocket = nil

      # The websocket is closed, explcitly stop the event machine to to end the loop and return to the parent
      EventMachine.stop
    end
  end
end