Class: Slackbotsy::Bot

Inherits:
Object
  • Object
show all
Defined in:
lib/slackbotsy/bot.rb

Instance Method Summary collapse

Constructor Details

#initialize(options, &block) ⇒ Bot



10
11
12
13
14
15
# File 'lib/slackbotsy/bot.rb', line 10

def initialize(options, &block)
  @options = options
  @regexes = {}
  setup_incoming_webhook    # http connection for async replies
  instance_eval &block if block # eval any hear statements in block
end

Instance Method Details

#attach(text, attachment, options = {}) ⇒ Object



44
45
46
47
# File 'lib/slackbotsy/bot.rb', line 44

def attach(text, attachment, options = {})
  options = { attachments: [ attachment ] }.merge(options)
  say(text, options)
end

#encode_payload(text, options = {}) ⇒ Object

format to send text to incoming webhook



26
27
28
29
30
31
32
33
34
# File 'lib/slackbotsy/bot.rb', line 26

def encode_payload(text, options = {})
  payload = {
    text:     text,
    username: @options['name'],
    channel:  @options['channel'].gsub(/^#?/, '#'), # ensure channel begins with #
  }.merge(options)

  "payload=#{payload.to_json.to_s}"
end

#handle_item(msg) ⇒ Object

check message and run blocks for any matches



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/slackbotsy/bot.rb', line 55

def handle_item(msg)
  return nil unless msg[:token] == @options['outgoing_token'] # ensure messages are for us from slack
  return nil if msg[:user_name] == 'slackbot'  # do not reply to self
  return nil unless msg[:text].is_a?(String) # skip empty messages

  ## loop things to look for and collect immediate responses
  responses = @regexes.map do |regex, proc|
    if mdata = msg[:text].strip.match(regex)
      proc.call(msg, mdata)
    end
  end

  ## format any replies for http response
  if responses
    # text = responses.compact.join('\n')
    # %Q[{"text": "#{text}"}]
    { text: responses.compact.join("\n") }.to_json
  end
end

#hear(regex, &block) ⇒ Object

add regex to things to hear



50
51
52
# File 'lib/slackbotsy/bot.rb', line 50

def hear(regex, &block)
  @regexes[regex] = block
end

#say(text, options = {}) ⇒ Object

send text to slack using incoming webhook



37
38
39
40
41
42
# File 'lib/slackbotsy/bot.rb', line 37

def say(text, options = {})
  request = Net::HTTP::Post.new(@uri.request_uri)
  request.body = encode_payload(text, options)
  response = @http.request(request)
  return nil                # so as not to trigger text in outgoing webhook reply
end

#setup_incoming_webhookObject

setup http connection for sending async incoming webhook messages to slack



18
19
20
21
22
23
# File 'lib/slackbotsy/bot.rb', line 18

def setup_incoming_webhook
  @uri  = URI.parse "https://#{@options['team']}.slack.com/services/hooks/incoming-webhook?token=#{@options['incoming_token']}"
  @http = Net::HTTP.new(@uri.host, @uri.port)
  @http.use_ssl = true
  @http.verify_mode = OpenSSL::SSL::VERIFY_PEER
end