Sha256: a457f2ee96814c78c4bce86874984d7dbd9757980fd74586b19e266c95cadd0f

Contents?: true

Size: 1.92 KB

Versions: 1

Compression:

Stored size: 1.92 KB

Contents

module Slappy
  class Client
    include Slappy::Debuggable

    attr_reader :start_time

    def initialize
      Slack.configure { |slack| slack.token = config.token }
      @callbacks = {}
    end

    def client
      @client ||= Slack.realtime
    end

    def start
      @start_time = Time.now
      @callbacks.each do |event_name, listeners|
        register_event event_name, listeners
      end
      set_signal_trap
      Debug.log 'Slappy start'
      client.start
    end

    def hello(&block)
      @callbacks[:hello] ||= []
      @callbacks[:hello].push block
      Debug.log "Add hello event(#{@callbacks[:hello].size})"
    end

    def hear(pattern, &block)
      @callbacks[:message] ||= []
      @callbacks[:message].push Listener::TextListener.new(pattern, block)
      Debug.log "Add here event(#{@callbacks[:message].size}): #{pattern}"
    end

    def monitor(type, &block)
      @callbacks[type.to_sym] ||= []
      @callbacks[type.to_sym].push Listener::TypeListener.new(type, block)
      Debug.log "Add monitor event(#{@callbacks[type.to_sym].size}): #{type}"
    end

    def say(text, options = {})
      options[:text] = text
      Messanger.new(options).message
    end

    def schedule(pattern, options = {}, &block)
      @schedule ||= Schedule.new
      @schedule.register pattern, options, &block
      Debug.log "Add schedule event(#{@schedule.list.size}): #{pattern}"
    end

    private

    def set_signal_trap
      [:TERM, :INT].each do |signal|
        Signal.trap(signal) do
          EventMachine.stop
        end
      end
    end

    def register_event(event_name, listeners)
      client.on event_name do |data|
        listeners.each do |listener|
          case event_name
          when :hello
            listener.call
          else
            event = Event.new(data)
            listener.call(event)
          end
        end
      end
    end

    def config
      Slappy.configuration
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
slappy-0.5.2 lib/slappy/client.rb