Class: Qbot::Adapter::Slack

Inherits:
Driver
  • Object
show all
Defined in:
lib/qbot/adapter/slack.rb

Constant Summary collapse

SLACK_API_URL =
'https://slack.com/api'

Instance Method Summary collapse

Methods inherited from Driver

build, inherited, #run

Constructor Details

#initialize(api_token: nil) ⇒ Slack

Returns a new instance of Slack.



14
15
16
17
18
19
# File 'lib/qbot/adapter/slack.rb', line 14

def initialize(api_token: nil)
  @server = URI.join(SLACK_API_URL, '/').to_s
  @error  = false

  access_token(api_token || ENV['QBOT_SLACK_API_TOKEN'])
end

Instance Method Details

#access_token(token) ⇒ Object



21
22
23
# File 'lib/qbot/adapter/slack.rb', line 21

def access_token(token)
  @token = token
end

#on_message(&block) ⇒ Object



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
# File 'lib/qbot/adapter/slack.rb', line 25

def on_message(&block)
  resp = api_call(:get, '/rtm.start')
  data = JSON.parse(resp.body)
  ws_url = data['url']

  EM.run do
    @ws = Faye::WebSocket::Client.new(ws_url, {}, { ping: 60})

    @ws.on :open do |e|
      Qbot.app.logger.info("#{self.class} - Websocket connection opened")
    end

    @ws.on :close do |e|
      Qbot.app.logger.info("#{self.class} - Websocket connection closed")
      stop if @error
      on_message(&block) # restart
    end

    @ws.on :error do |e|
      Qbot.app.logger.error("#{self.class} - #{e.message}")
      @error = true
    end

    @ws.on :message do |e|
      data = JSON.parse(e.data)
      emit_event(data, block)
    end
  end
end

#post(text, **options) ⇒ Object



59
60
61
# File 'lib/qbot/adapter/slack.rb', line 59

def post(text, **options)
  api_call(:post, "/chat.postMessage", options.merge(text: text))
end

#reply_to(message, text, **options) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/qbot/adapter/slack.rb', line 63

def reply_to(message, text, **options)
  if options[:channel_id]
    channel_id = options[:channel_id]
  elsif options[:channel_name]
    channel = channel(options[:channel_name])
    channel_id = channel['id'] if channel
  end

  channel_id ||= message.data['channel'] if message
  return unless channel_id

  post(text, **options.merge(channel: channel_id))
end

#stopObject



55
56
57
# File 'lib/qbot/adapter/slack.rb', line 55

def stop
  EM.stop
end