class Slack::Rtm::Bot::Helper

Constants

RTM_PATH
SLACK_URL
USERS_PATH
VERSION

Attributes

channel[RW]
id[RW]
me[RW]
message_block[RW]
wss[RW]

Public Class Methods

new(token, channel, name, message_block) click to toggle source
# File lib/slack-rtm-bot-helper/helper.rb, line 12
def initialize(token, channel, name, message_block)
  @token         = token
  @channel       = channel
  @message_block = message_block
  @name          = name
  @me            = me_id(token, name) unless name.nil?

  @id  = 1
  @wss = nil
end
run(token:nil, channel:nil, name: nil, &message_block) click to toggle source
# File lib/slack-rtm-bot-helper/helper.rb, line 23
def self.run(token:nil, channel:nil, name: nil, &message_block)
  raise NotEnoughArgumentsError if token.nil? || message_block.nil?

  s = new(token, channel, name, message_block)
  s.connect

  loop do
    sleep 1
    unless s.wss.open?
      s.connect
    end
  end 
end

Public Instance Methods

connect() click to toggle source
# File lib/slack-rtm-bot-helper/helper.rb, line 37
def connect
  conn = ::Faraday.new(SLACK_URL) do |faraday|
    faraday.request  :url_encoded
    faraday.adapter  ::Faraday.default_adapter
  end

  res = conn.post RTM_PATH, token: @token
  url = ::JSON.parse(res.body).to_h['url']

  return if url.nil?

  @wss = ::WebSocket::Client::Simple.connect url
  @wss.on :message, &(base_block(self))
end
to_me?(text) click to toggle source
# File lib/slack-rtm-bot-helper/helper.rb, line 52
def to_me?(text)
  !text.match(/<@#{@me}(?:\|#{@name})?/).nil?
end

Private Instance Methods

base_block(helper) click to toggle source
# File lib/slack-rtm-bot-helper/helper.rb, line 68
def base_block(helper)
  Proc.new do |msg|
    data = ::JSON.parse(msg.data)
    close if data.empty?

    msg = if !data['text'].empty?
            if helper.me.nil?
              helper.message_block.call(data) 
            else
              helper.message_block.call(data) if helper.to_me?(data['text'])
            end
          end

    if !(msg.nil? || msg.empty?)
      target_ch = helper.channel || data['channel']
      msg_json = {
         id:      helper.id,
         type:    'message',
         channel: target_ch,
         text:    msg.to_s
      }.to_json

      send(msg_json) && helper.id += 1
    end
  end
end
me_id(token, name) click to toggle source
# File lib/slack-rtm-bot-helper/helper.rb, line 58
def me_id(token, name)
  conn = ::Faraday.new(SLACK_URL) do |faraday|
    faraday.request  :url_encoded
    faraday.adapter  ::Faraday.default_adapter
  end

  res = conn.post USERS_PATH, token: @token
  (::JSON.parse(res.body)['members'].select { |m| m['name'] == name }.first)&.fetch('id')
end