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.

Raises:

  • (ArgumentError)


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

def initialize(token, options={})
  raise ArgumentError, "Missing required parameter: 'token'" if token.nil? or token.empty?
  @token = token
  @typing_speed = options.fetch(:typing_speed, 100.0)

  @user_ids_dm_ids = {}
  @users_by_id = {}
  @user_id_by_name = {}
  @conversations_by_id = {}
  @conversation_ids_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



69
70
71
72
73
74
75
76
# File 'lib/slacks/connection.rb', line 69

def add_reaction(emojis, message)
  Array(emojis).each do |emoji|
    api("reactions.add",
      name: emoji.gsub(/^:|:$/, ""),
      channel: message.channel.id,
      timestamp: message.timestamp)
  end
end

#can_see?(channel) ⇒ Boolean

Returns:

  • (Boolean)


161
162
163
164
165
# File 'lib/slacks/connection.rb', line 161

def can_see?(channel)
  to_channel_id(channel).present?
rescue ArgumentError
  false
end

#channelsObject



152
153
154
155
156
157
158
159
# File 'lib/slacks/connection.rb', line 152

def channels
  channels = user_id_by_name.keys + conversation_ids_by_name.keys
  if channels.empty?
    fetch_conversations!
    fetch_users!
  end
  channels
end

#find_channel(id) ⇒ Object



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

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 }
  else
    Slacks::Channel.new(self, conversations_by_id.fetch(id) do
      raise ArgumentError, "Unable to find a conversation with the ID #{id.inspect}"
    end)
  end
end

#find_user(id) ⇒ Object



185
186
187
188
189
# File 'lib/slacks/connection.rb', line 185

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



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

def find_user_by_nickname(nickname)
  find_user to_user_id(nickname)
end

#get_message(channel, ts) ⇒ Object



47
48
49
50
51
52
# File 'lib/slacks/connection.rb', line 47

def get_message(channel, ts)
  params = {
    channel: to_channel_id(channel),
    timestamp: ts }
  api("reactions.get", **params)
end

#listen!Object



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 96

def listen!
  response = api("rtm.start")
  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 NilClass
      # Every event has a `type` property:
      # https://api.slack.com/rtm#events
      # If an event comes across without
      # one, we'll skill it.
      next

    when EVENT_GROUP_JOINED, EVENT_CHANNEL_CREATED
      conversation = data["channel"]
      @conversations_by_id[conversation["id"]] = conversation
      @conversation_ids_by_name[conversation["name"]] = conversation["id"]

    when EVENT_USER_JOINED
      user = data["user"]
      @users_by_id[user["id"]] = user
      @user_id_by_name[user["name"]] = user["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

#listening?Boolean

Returns:

  • (Boolean)


90
91
92
# File 'lib/slacks/connection.rb', line 90

def listening?
  !websocket.nil?
end

#pingObject

Raises:



85
86
87
88
# File 'lib/slacks/connection.rb', line 85

def ping
  raise NotListeningError unless listening?
  websocket.ping
end

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



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

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, _| SEND_MESSAGE_PARAMS.member?(key) })
  api("chat.postMessage", **params)
end

#typing_on(channel) ⇒ Object

Raises:



80
81
82
83
# File 'lib/slacks/connection.rb', line 80

def typing_on(channel)
  raise NotListeningError unless listening?
  websocket.write MultiJson.dump(type: "typing", channel: to_channel_id(channel))
end

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



54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/slacks/connection.rb', line 54

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)
end

#user_exists?(username) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#usersObject



204
205
206
207
# File 'lib/slacks/connection.rb', line 204

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