Class: Pechkin::Connector::Slack

Inherits:
Base
  • Object
show all
Defined in:
lib/pechkin/connector/slack.rb

Overview

:nodoc:

Constant Summary

Constants inherited from Base

Base::DEFAULT_HEADERS

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#post_data, #preview

Constructor Details

#initialize(bot_token, name) ⇒ Slack

Returns a new instance of Slack.



8
9
10
11
12
13
# File 'lib/pechkin/connector/slack.rb', line 8

def initialize(bot_token, name)
  super()

  @headers = { 'Authorization' => "Bearer #{bot_token}" }
  @name = name
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



6
7
8
# File 'lib/pechkin/connector/slack.rb', line 6

def name
  @name
end

Instance Method Details

#resolve_user_id(email, logger) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/pechkin/connector/slack.rb', line 15

def resolve_user_id(email, logger)
  url = "https://slack.com/api/users.lookupByEmail?email=#{email}"

  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = url.start_with?('https://')

  request = Net::HTTP::Get.new(uri.request_uri, @headers)

  response = http.request(request)

  if response.is_a?(Net::HTTPSuccess)
    logger.warn "#{email}HTTPSuccess"
    resp = JSON.parse(response.body)
  else
    logger.warn "#{email}Sending failed#{response.message}"
    raise SlackApiRequestError, response.message
  end

  logger.warn "#{email} RESPONSE:#{resp['user']['id']}"

  resp['user']['id']
end

#send_message(channel, email, message, message_desc, logger) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/pechkin/connector/slack.rb', line 39

def send_message(channel, email, message, message_desc, logger)
  text = CGI.unescape_html(message)

  channel = resolve_user_id(email, logger) if channel == 'email'

  attachments = message_desc['slack_attachments'] || {}

  if text.strip.empty? && attachments.empty?
    return { channel: channel, code: 400,
             response: 'Internal error: message is empty' }
  end

  params = { channel: channel, text: text, attachments: attachments }

  url = 'https://slack.com/api/chat.postMessage'
  response = post_data(url, params, headers: @headers)

  logger.warn "#{email} RESPONSE: #{response.body}"

  { channel: channel, code: response.code.to_i, response: response.body }
end