Class: Slacks::Connection

Inherits:
Object
  • Object
show all
Includes:
Observer
Defined in:
lib/slacks/connection.rb

Constant Summary collapse

EVENT_CHANNEL_CREATED =
"channel_created".freeze
EVENT_GROUP_JOINED =
"group_joined".freeze
EVENT_MESSAGE =
"message".freeze
EVENT_USER_JOINED =
"team_join".freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Observer

#on

Constructor Details

#initialize(token, options = {}) ⇒ Connection

Returns a new instance of Connection.



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/slacks/connection.rb', line 19

def initialize(token, options={})
  @token = token
  @typing_speed = options.fetch(:typing_speed, 100.0)

  @user_ids_dm_ids = {}
  @users_by_id = {}
  @user_id_by_name = {}
  @groups_by_id = {}
  @group_id_by_name = {}
  @channels_by_id = {}
  @channel_id_by_name = {}
end

Instance Attribute Details

#botObject (readonly)

Returns the value of attribute bot.



16
17
18
# File 'lib/slacks/connection.rb', line 16

def bot
  @bot
end

#teamObject (readonly)

Returns the value of attribute team.



16
17
18
# File 'lib/slacks/connection.rb', line 16

def team
  @team
end

#tokenObject (readonly)

Returns the value of attribute token.



16
17
18
# File 'lib/slacks/connection.rb', line 16

def token
  @token
end

#typing_speedObject

Returns the value of attribute typing_speed.



17
18
19
# File 'lib/slacks/connection.rb', line 17

def typing_speed
  @typing_speed
end

Instance Method Details

#add_reaction(emojis, message) ⇒ Object



77
78
79
80
81
82
83
84
85
86
# File 'lib/slacks/connection.rb', line 77

def add_reaction(emojis, message)
  Array(emojis).each do |emoji|
    api("reactions.add", {
      name: emoji.gsub(/^:|:$/, ""),
      channel: message.channel.id,
      timestamp: message.timestamp })
  end
rescue Slacks::ResponseError
  $!.response
end

#channelsObject



152
153
154
# File 'lib/slacks/connection.rb', line 152

def channels
  user_id_by_name.keys + group_id_by_name.keys + channel_id_by_name.keys
end

#find_channel(id) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/slacks/connection.rb', line 158

def find_channel(id)
  case id
  when /^U/ then find_user(id)
  when /^D/
    user = find_user(get_user_id_for_dm(id))
    Slacks::Channel.new self, {
      "id" => id,
      "is_im" => true,
      "name" => user.username }
  when /^G/
    Slacks::Channel.new self, groups_by_id.fetch(id) do
      raise ArgumentError, "Unable to find a group with the ID #{id.inspect}"
    end
  else
    Slacks::Channel.new self, channels_by_id.fetch(id) do
      raise ArgumentError, "Unable to find a channel with the ID #{id.inspect}"
    end
  end
end

#find_user(id) ⇒ Object



178
179
180
181
182
# File 'lib/slacks/connection.rb', line 178

def find_user(id)
  Slacks::User.new self, users_by_id.fetch(id) do
    raise ArgumentError, "Unable to find a user with the ID #{id.inspect}"
  end
end

#find_user_by_nickname(nickname) ⇒ Object



184
185
186
# File 'lib/slacks/connection.rb', line 184

def find_user_by_nickname(nickname)
  find_user to_user_id(nickname)
end

#get_message(channel, ts) ⇒ Object



51
52
53
54
55
56
57
58
# File 'lib/slacks/connection.rb', line 51

def get_message(channel, ts)
  params = {
    channel: to_channel_id(channel),
    timestamp: ts }
  api("reactions.get", params)
rescue Slacks::ResponseError
  $!.response
end

#listen!Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/slacks/connection.rb', line 94

def listen!
  response = api("rtm.start")
  unless response["ok"]
    raise MigrationInProgress if response["error"] == "migration_in_progress"
    raise ResponseError.new(response, response["error"])
  end
  store_context!(response)

  @websocket = Slacks::Driver.new
  websocket.connect_to websocket_url
  trigger "connected"

  websocket.on(:error) do |event|
    raise ConnectionError.new(event)
  end

  websocket.on(:message) do |data|
    case data["type"]
    when EVENT_GROUP_JOINED
      group = data["channel"]
      @groups_by_id[group["id"]] = group
      @group_id_by_name[group["name"]] = group["id"]

    when EVENT_USER_JOINED
      user = data["user"]
      @users_by_id[user["id"]] = user
      @user_id_by_name[user["name"]] = user["id"]

    when EVENT_CHANNEL_CREATED
      channel = data["channel"]
      @channels_by_id[channel["id"]] = channel
      @channel_id_by_name[channel["name"]] = channel["id"]

    when EVENT_MESSAGE
      # Don't respond to things that this bot said
      next if data["user"] == bot.id
      # ...or to messages with no text
      next if data["text"].nil? || data["text"].empty?
    end

    trigger data["type"], data
  end

  websocket.main_loop

rescue EOFError
  # Slack hung up on us, we'll ask for a new WebSocket URL and reconnect.
  trigger "error", "Websocket Driver received EOF; reconnecting"
  retry
end

#send_message(message, options = {}) ⇒ Object Also known as: say



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/slacks/connection.rb', line 34

def send_message(message, options={})
  channel = options.fetch(:channel) { raise ArgumentError, "Missing parameter :channel" }
  attachments = Array(options[:attachments])
  params = {
    channel: to_channel_id(channel),
    text: message,
    as_user: true, # post as the authenticated user (rather than as slackbot)
    link_names: 1} # find and link channel names and user names
  params.merge!(attachments: MultiJson.dump(attachments)) if attachments.any?
  params.merge!(options.select { |key, _| [:username, :as_user, :parse, :link_names,
    :unfurl_links, :unfurl_media, :icon_url, :icon_emoji].member?(key) })
  api("chat.postMessage", params)
rescue Slacks::ResponseError
  $!.response
end

#typing_on(channel) ⇒ Object



88
89
90
# File 'lib/slacks/connection.rb', line 88

def typing_on(channel)
  websocket.write MultiJson.dump(type: "typing", channel: to_channel_id(channel))
end

#update_message(ts, message, options = {}) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/slacks/connection.rb', line 60

def update_message(ts, message, options={})
  channel = options.fetch(:channel) { raise ArgumentError, "Missing parameter :channel" }
  attachments = Array(options[:attachments])
  params = {
    ts: ts,
    channel: to_channel_id(channel),
    text: message,
    as_user: true, # post as the authenticated user (rather than as slackbot)
    link_names: 1} # find and link channel names and user names
  params.merge!(attachments: MultiJson.dump(attachments)) if attachments.any?
  params.merge!(options.select { |key, _| [:username, :as_user, :parse, :link_names,
    :unfurl_links, :unfurl_media, :icon_url, :icon_emoji].member?(key) })
  api("chat.update", params)
rescue Slacks::ResponseError
  $!.response
end

#user_exists?(username) ⇒ Boolean

Returns:

  • (Boolean)


190
191
192
193
194
195
# File 'lib/slacks/connection.rb', line 190

def user_exists?(username)
  return false if username.nil?
  to_user_id(username).present?
rescue ArgumentError
  false
end

#usersObject



197
198
199
200
# File 'lib/slacks/connection.rb', line 197

def users
  fetch_users! if @users_by_id.empty?
  @users_by_id.values
end