Class: SlackbotFrd::SlackConnection

Inherits:
Object
  • Object
show all
Defined in:
lib/slackbot_frd/lib/slack_connection.rb

Constant Summary collapse

FILE_PATH =
File.expand_path(__FILE__)
APP_ROOT =
File.expand_path(File.dirname(File.dirname(FILE_PATH)))
FILE_DIR =
File.dirname(FILE_PATH)
LOG_FILE =
"#{APP_ROOT}/bp-slackbot.log"
PID_FILE_NAME =
"#{APP_ROOT}/bp-slackbot.pid"
PING_INTERVAL_SECONDS =
5

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(token:, errors_file:, monitor_connection: true) ⇒ SlackConnection



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 28

def initialize(token:, errors_file:, monitor_connection: true)
  log_and_add_to_error_file("No token passed to #{self.class}") unless token

  @token = token
  @errors_file = errors_file
  @monitor_connection = monitor_connection

  @event_id = 0
  @on_connected_callbacks = []
  @on_disconnected_callbacks = []
  @on_message_callbacks = UserChannelCallbacks.new
  @on_channel_left_callbacks = UserChannelCallbacks.new
  @on_channel_joined_callbacks = UserChannelCallbacks.new

  # These hashes are used to map ids to names efficiently
  @user_id_to_name = {}
  @user_name_to_id = {}
  @channel_id_to_name = {}
  @channel_name_to_id = {}

  @pong_received = true

  SlackbotFrd::Log.debug("Done initializing #{self.class}")
end

Instance Attribute Details

#tokenObject

Returns the value of attribute token.



26
27
28
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 26

def token
  @token
end

Instance Method Details

#channel_id_to_name(channel_id) ⇒ Object



266
267
268
269
270
271
272
273
274
275
276
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 266

def channel_id_to_name(channel_id)
  unless @channel_id_to_name && @channel_id_to_name.key?(channel_id)
    refresh_channel_info
  end
  unless @channel_id_to_name.include?(channel_id)
    SlackbotFrd::Log.warn(
      "#{self.class}: Channel id '#{channel_id}' not found"
    )
  end
  @channel_id_to_name[channel_id]
end

#channel_ids(_force_refresh = false) ⇒ Object



234
235
236
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 234

def channel_ids(_force_refresh = false)
  @user_id_to_name.keys
end

#channel_name_to_id(channel_name) ⇒ Object



278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 278

def channel_name_to_id(channel_name)
  return channel_name if channel_name == :any
  nc = normalize_channel_name(channel_name)
  unless @channel_name_to_id && @channel_name_to_id.key?(nc)
    refresh_channel_info
  end
  unless @channel_name_to_id.include?(nc)
    SlackbotFrd::Log.warn(
      "#{self.class}: Channel name '#{nc}' not found"
    )
  end
  @channel_name_to_id[nc]
end

#channel_names(_force_refresh = false) ⇒ Object



238
239
240
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 238

def channel_names(_force_refresh = false)
  @channel_name_to_id.keys
end

#delete_message(channel:, timestamp:) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 158

def delete_message(channel:, timestamp:)
  SlackbotFrd::Log.debug("#{self.class}: Deleting message with timestamp '#{timestamp}' from channel '#{channel}'")

  resp = SlackbotFrd::SlackMethods::ChatDelete.delete(
    token: @token,
    channel: channel_name_to_id(channel),
    timestamp: timestamp
  )

  SlackbotFrd::Log.debug("#{self.class}: Received response:  #{resp}")
end

#event_idObject



90
91
92
93
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 90

def event_id
  @event_id += 1
  @event_id
end

#im_channel_for_user(user:) ⇒ Object



199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 199

def im_channel_for_user(user:)
  SlackbotFrd::Log.debug(
    "#{self.class}: Opening or retrieving IM channel for user '#{user}'"
  )

  resp = JSON.parse(SlackbotFrd::SlackMethods::ImOpen.openChannel(
    token: @token,
    user: user_name_to_id(user)
  ))

  SlackbotFrd::Log.debug("#{self.class}: Received response:  #{resp}")
  return resp["channel"]["id"] if resp["channel"]
  resp
end

#invite_user(user:, channel:) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 185

def invite_user(user:, channel:)
  SlackbotFrd::Log.debug(
    "#{self.class}: Inviting user '#{user}' to channel '#{channel}'"
  )

  resp = SlackbotFrd::SlackMethods::ChannelsInvite.invite(
    token: @token,
    user: user_name_to_id(user),
    channel: channel_name_to_id(channel)
  )

  SlackbotFrd::Log.debug("#{self.class}: Received response:  #{resp}")
end

#num_users_in_channel(channel) ⇒ Object



222
223
224
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 222

def num_users_in_channel(channel)
  users_in_channel(channel).count
end

#on_channel_joined(user: :any, channel: :any, &block) ⇒ Object



123
124
125
126
127
128
129
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 123

def on_channel_joined(user: :any, channel: :any, &block)
  wrap_user_or_channel_lookup_on_callback('on_message_channel_joined', user, channel) do
    u = user_name_to_id(user)
    c = channel_name_to_id(channel)
    @on_channel_joined_callbacks.add(user: u, channel: c, callback: block)
  end
end

#on_channel_left(user: :any, channel: :any, &block) ⇒ Object



113
114
115
116
117
118
119
120
121
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 113

def on_channel_left(user: :any, channel: :any, &block)
  wrap_user_or_channel_lookup_on_callback('on_message_channel_left', user, channel) do
    @on_channel_left_callbacks.add(
      user: user_name_to_id(user),
      channel: channel_name_to_id(channel),
      callback: block
    )
  end
end

#on_close(&block) ⇒ Object



99
100
101
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 99

def on_close(&block)
  @on_disconnected_callbacks.push(block)
end

#on_connected(&block) ⇒ Object



95
96
97
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 95

def on_connected(&block)
  @on_connected_callbacks.push(block)
end

#on_message(user: :any, channel: :any, &block) ⇒ Object



103
104
105
106
107
108
109
110
111
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 103

def on_message(user: :any, channel: :any, &block)
  wrap_user_or_channel_lookup_on_callback('on_message', user, channel) do
    @on_message_callbacks.add(
      user: user_name_to_id(user),
      channel: channel_name_to_id(channel),
      callback: block
    )
  end
end

#post_reaction(name:, channel: nil, timestamp: nil) ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 170

def post_reaction(name:, channel: nil, timestamp: nil)
  SlackbotFrd::Log.debug(
    "#{self.class}: Posting reaction '#{name}' to channel '#{channel}' with timestamp '#{timestamp}'"
  )

  resp = SlackbotFrd::SlackMethods::ReactionsAdd.add(
    token: @token,
    name: name,
    channel: channel_name_to_id(channel),
    timestamp: timestamp
  )

  SlackbotFrd::Log.debug("#{self.class}: Received response:  #{resp}")
end

#send_im(user:, message:, username: nil, avatar_emoji: nil, avatar_url: nil) ⇒ Object



131
132
133
134
135
136
137
138
139
140
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 131

def send_im(user:, message:, username: nil, avatar_emoji: nil, avatar_url: nil)
  send_message(
    channel: im_channel_for_user(user),
    message: message,
    username: username,
    avatar_emoji: avatar_emoji,
    avatar_url: avatar_url,
    channel_is_id: true
  )
end

#send_message(channel:, message:, username: nil, avatar_emoji: nil, avatar_url: nil, channel_is_id: false, parse: 'full') ⇒ Object



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 142

def send_message(channel:, message:, username: nil, avatar_emoji: nil, avatar_url: nil, channel_is_id: false, parse: 'full')
  if (username && (avatar_emoji || avatar_url)) || parse != 'full'
    send_message_as_bot(
      channel: channel,
      message: message,
      username: username,
      avatar_emoji: avatar_emoji,
      avatar_url: avatar_url,
      channel_is_id: channel_is_id,
      parse: parse
    )
  else
    send_message_as_user(channel: channel, message: message, channel_is_id: channel_is_id)
  end
end

#startObject



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 53

def start
  # Write pid file
  File.write(PID_FILE_NAME, "#{Process.pid}")

  SlackbotFrd::Log.info("#{self.class}: starting event machine")

  EM.run do
    begin
      wss_url = SlackbotFrd::SlackMethods::RtmStart.wss_url(@token)
    rescue SocketError => e
      log_and_add_to_error_file(socket_error_message(e))
    end

    unless wss_url
      log_and_add_to_error_file(
        'No Real Time stream opened by slack.  Check for network connection and correct authentication token'
      )
      return
    end
    @ws = Faye::WebSocket::Client.new(wss_url)

    @on_connected_callbacks.each    { |callback| @ws.on(:open,  &callback) }
    @on_disconnected_callbacks.each { |callback| @ws.on(:close, &callback) }
    @ws.on(:message) { |event| process_message_received(event) }

    # Clean up our pid file
    @ws.on(:close) { |_event| File.delete(PID_FILE_NAME) }

    # This should ensure that we get a pong back at least every
    # PING_INTERVAL_SECONDS, otherwise we die because our
    # connection is probably toast
    EM.add_periodic_timer(PING_INTERVAL_SECONDS) { check_ping }
  end

  SlackbotFrd::Log.info("#{self.class}: event machine loop terminated")
end

#user_id_to_name(user_id) ⇒ Object



242
243
244
245
246
247
248
249
250
251
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 242

def user_id_to_name(user_id)
  return user_id if user_id == :any || user_id == :bot
  unless @user_id_to_name && @user_id_to_name.key?(user_id)
    
  end
  unless @user_id_to_name.include?(user_id)
    SlackbotFrd::Log.warn("#{self.class}: User id '#{user_id}' not found")
  end
  @user_id_to_name[user_id]
end

#user_ids(_force_refresh = false) ⇒ Object



226
227
228
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 226

def user_ids(_force_refresh = false)
  @user_id_to_name.keys
end

#user_name_to_id(user_name) ⇒ Object



253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 253

def user_name_to_id(user_name)
  return user_name if user_name == :any || user_name == :bot
  unless @user_name_to_id && @user_name_to_id.key?(user_name)
    
  end
  unless @user_name_to_id.include?(user_name)
    SlackbotFrd::Log.warn(
      "#{self.class}: User name '#{user_name}' not found"
    )
  end
  @user_name_to_id[user_name]
end

#user_names(_force_refresh = false) ⇒ Object



230
231
232
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 230

def user_names(_force_refresh = false)
  @user_name_to_id.keys
end

#users_in_channel(channel) ⇒ Object



214
215
216
217
218
219
220
# File 'lib/slackbot_frd/lib/slack_connection.rb', line 214

def users_in_channel(channel)
  a = SlackMethods::ChannelsInfo.members(
    token: @token,
    channel: channel_name_to_id(channel)
  )
  a.map{ |id| user_id_to_name(id) }
end