Class: Lich::DragonRealms::SlackBot

Inherits:
Object
  • Object
show all
Defined in:
documented/dragonrealms/commons/slackbot.rb

Overview

Slack API client for sending direct messages via DragonRealms LNet.

Caches the Slack users list in a shared SQLite store (DB_Store) with a 1-hour TTL. The cache is kept per token, so characters on the same game instance that use the same token share one cached copy, and a character never reads another workspace's users. Entries are never deleted: DB_Store has no delete and the TTL is checked on read, so lich.db keeps one row per token ever used. Randomized startup jitter prevents thundering herd on simultaneous character logins.

Defined Under Namespace

Classes: ApiError, Error, MalformedResponseError, NetworkError, ThrottlingError

Constant Summary collapse

SLACK_UNAVAILABLE_ERRORS =

Errors meaning Slack could not answer a request (as opposed to Slack answering it with a refusal). A token check that fails with one of these neither judges nor replaces the token. A new ApiError subclass for "Slack could not answer" belongs here, or a token check that hits it is treated as a rejected token and starts LNet token discovery.

[NetworkError, ThrottlingError, MalformedResponseError].freeze
API_URL =
'https://slack.com/api/'
LNET_SCRIPT_NAME =
'lnet'
LICHBOTS =

LichBot characters from which to request a Slack token via LNet.

Returns:

See Also:

  • #find_token
  • #request_token
%w[Quilsilgas].freeze
TOKEN_REQUEST_TIMEOUT =
10
MAX_NETWORK_RETRIES =
5
NO_USER_PATTERN =

Matches a game server message indicating a user does not exist in the game.

Examples:

"[server]: \"no user jsmith\"" #=> matches

Returns:

  • (Regexp)

See Also:

  • #request_token
/\[server\]: "no user .*/.freeze
LNET_CONNECTION_TIMEOUT =
30
LNET_ACTIVITY_TIMEOUT =
120
BASE_RETRY_DELAY_SECONDS =
30
MAX_RETRY_DELAY_SECONDS =
300
USERS_CACHE_SCRIPT =
'_slackbot_users_cache'
USERS_CACHE_TTL =
3600
MAX_THROTTLE_RETRIES =
10
SEND_REQUEST_BUDGET =

Hard cap, in seconds, on each Slack API step (token check, users.list) that #direct_message runs when it has to restore the connection. A message is often sent right before an emergency logout, so it must never wait out the full network or rate-limit backoff.

5
STARTUP_REQUEST_BUDGET =

Hard cap, in seconds, on each Slack API step (token check, users.list) while the bot starts. SlackBot.new runs on the calling script's thread, often before that script's own safety checks start, so startup must not wait out the full network or rate-limit backoff either. A bot that gives up here retries on the next message.

10
STARTUP_JITTER_SECONDS =

Most seconds the startup waits before users.list, so characters that log in together let the first one fill the shared cache. Not counted against STARTUP_REQUEST_BUDGET.

5.0
CONNECT_SHARE_OF_BUDGET =

Part of a deadline request's remaining budget that net/http's own connect timeouts share out. The rest is headroom before the hard Timeout on the whole connect, so the two do not fire together.

0.9
USERS_LIST_RETRY_COOLDOWN =

After a failed users.list call, #direct_message makes no new call for this many seconds (or for Slack's Retry-After, if longer, but never more than MAX_RETRY_DELAY_SECONDS), so a burst of messages during an outage neither waits on Slack nor hammers it.

30
USERS_LIST_UNAVAILABLE =
'Slack user list unavailable'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize ⇒ SlackBot

Connects at once: checks (or discovers) the token and loads the users list, capping each Slack API step at STARTUP_REQUEST_BUDGET. If a step fails or runs out of time, the bot is left uninitialized and the next #direct_message tries again. The LNet token discovery keeps its own timeouts.



130
131
132
133
134
135
136
137
138
139
140
# File 'documented/dragonrealms/commons/slackbot.rb', line 130

def initialize
  @initialized = false
  @error_message = nil
  @token_verified = false
  @users_list = nil
  @users_list_retry_at = nil
  @restore_mutex = Mutex.new
  @restore_attempts = 0

  connect(budget: STARTUP_REQUEST_BUDGET, jitter: true)
end

Instance Attribute Details

#error_message ⇒ String? (readonly)

Returns human-readable error from the last failed operation.

Returns:

  • (String, nil) —

    human-readable error from the last failed operation



64
65
66
# File 'documented/dragonrealms/commons/slackbot.rb', line 64

def error_message
  @error_message
end

Instance Method Details

#authed?(token, budget: nil) ⇒ Boolean

Tests whether a Slack API token is valid.

Answers false both when Slack rejects the token and when Slack cannot be asked (a network failure, a rate limit or a reply that is not JSON); the cause of the latter is logged.

Parameters:

  • token (String, nil) —

    the token to test

  • budget (Numeric, nil) (defaults to: nil) —

    seconds allowed for the check, or nil for the full retry policy

Returns:

  • (Boolean)


192
193
194
195
196
197
# File 'documented/dragonrealms/commons/slackbot.rb', line 192

def authed?(token, budget: nil)
  token_accepted?(token, budget)
rescue *SLACK_UNAVAILABLE_ERRORS => e
  Lich.log "SlackBot: Could not check a Slack token: #{e.message}"
  false
end

#direct_message(username, message) ⇒ Hash?

Sends a direct message to a Slack user. Validates the username first, then reconnects if needed.

Parameters:

  • username (String, nil) —

    Slack username to message

  • message (String) —

    message body

Returns:

  • (Hash, nil) —

    Slack API response, or nil on failure



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'documented/dragonrealms/commons/slackbot.rb', line 205

def direct_message(username, message)
  if username.nil? || username.to_s.strip.empty?
    Lich::Messaging.msg('bold', 'SlackBot: Cannot send message - no username provided. Check your slackbot_username setting.')
    return nil
  end

  restore_connection unless initialized?

  unless initialized?
    Lich::Messaging.msg('bold', 'SlackBot: Cannot send message - not connected. Will retry on next attempt.')
    return nil
  end

  dm_channel = get_dm_channel(username)
  dm_channel = get_dm_channel(username) if dm_channel.nil? && reload_users_cache(username)
  unless dm_channel
    Lich::Messaging.msg('bold', "SlackBot: Cannot send message - user '#{username}' not found in Slack workspace.")
    return nil
  end

  params = {
    'token'   => UserVars.slack_token,
    'channel' => dm_channel,
    'text'    => "#{checkname}: #{message}",
    'as_user' => 'true'
  }
  post('chat.postMessage', params)
rescue Error => e
  Lich.log "SlackBot: Failed to send Slack message to #{username}: #{e.message}"
  Lich::Messaging.msg('bold', "SlackBot: Failed to send Slack message to #{username}: #{e.message}")
  nil
end

#initialized? ⇒ Boolean

Returns true if the bot has a valid token and a non-empty users list.

Returns:

  • (Boolean) —

    true if the bot has a valid token and a non-empty users list



143
144
145
# File 'documented/dragonrealms/commons/slackbot.rb', line 143

def initialized?
  @initialized
end

#lnet_connected? ⇒ Boolean

Checks whether the LNet connection is alive and responsive.

Returns:

  • (Boolean)


168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'documented/dragonrealms/commons/slackbot.rb', line 168

def lnet_connected?
  return false unless defined?(LNet)
  return false unless LNet.server
  return false if LNet.server.closed?

  if LNet.respond_to?(:last_recv) && LNet.last_recv
    return false if (Time.now - LNet.last_recv) > LNET_ACTIVITY_TIMEOUT
  end

  true
rescue IOError, Errno::EBADF, Errno::EPIPE, NoMethodError
  false
end

#reconnect!(budget: nil, jitter: true) ⇒ Boolean

Reinitializes the bot by re-checking the token and re-loading the users list. A failed users-list load keeps any list loaded earlier.

Parameters:

  • budget (Numeric, nil) (defaults to: nil) —

    seconds allowed for each Slack API step (token check, users.list), or nil for the full retry policy. The LNet token discovery keeps its own timeouts.

  • jitter (Boolean) (defaults to: true) —

    wait a random moment before calling users.list (on for a manual reconnect; the in-send reconnect turns it off)

Returns:

  • (Boolean) —

    true if the token is valid and a non-empty users list (fresh, cached, or the one loaded earlier) is available



157
158
159
160
161
162
163
# File 'documented/dragonrealms/commons/slackbot.rb', line 157

def reconnect!(budget: nil, jitter: true)
  @error_message = nil
  @initialized = false
  @token_verified = false

  connect(budget: budget, jitter: jitter)
end