Class: ESM::Bot

Inherits:
Discordrb::Bot
  • Object
show all
Defined in:
lib/esm/bot.rb,
lib/esm/bot/delivery_overseer.rb

Defined Under Namespace

Classes: DeliveryOverseer

Constant Summary collapse

PERMISSION_BITS =

View Channels Send Messages Embed Links Attach Files Add Reactions

52_288
STATUS_TYPES =
{
  PLAYING: 0,
  STREAMING: 1,
  LISTENING: 2,
  WATCHING: 3
}.freeze
INTENTS =
Discordrb::INTENTS.slice(
  :servers,
  :server_members,
  # :server_bans,
  # :server_emojis,
  # :server_integrations,
  # :server_webhooks,
  # :server_invites,
  # :server_voice_states,
  # :server_presences,
  :server_messages,
  # :server_message_reactions,
  :server_message_typing,
  :direct_messages,
  # :direct_message_reactions,
  :direct_message_typing
).keys.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBot

Returns a new instance of Bot.



39
40
41
42
43
44
45
46
# File 'lib/esm/bot.rb', line 39

def initialize
  @timer = Timer.new
  @waiting_for = {}
  @mutex = Mutex.new
  @delivery_overseer = ESM::Bot::DeliveryOverseer.new

  super(token: ESM.config.token, intents: INTENTS)
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



37
38
39
# File 'lib/esm/bot.rb', line 37

def config
  @config
end

#delivery_overseerObject (readonly)

Returns the value of attribute delivery_overseer.



37
38
39
# File 'lib/esm/bot.rb', line 37

def delivery_overseer
  @delivery_overseer
end

#metadataObject (readonly)

Returns the value of attribute metadata.



37
38
39
# File 'lib/esm/bot.rb', line 37

def 
  @metadata
end

Instance Method Details

#__deliver(message, delivery_channel, embed_message: "", replying_to: nil) ⇒ Object



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/esm/bot.rb', line 251

def __deliver(message, delivery_channel, embed_message: "", replying_to: nil)
  info!(
    channel: "#{delivery_channel.name} (#{delivery_channel.id})",
    message: message.is_a?(ESM::Embed) ? message.to_h : message,
    embed_message:,
    replying_to:
  )

  if message.is_a?(ESM::Embed)
    # Send the embed
    delivery_channel.send_embed(embed_message, nil, nil, false, nil, replying_to) { |embed| message.transfer(embed) }
  else
    # Send the text message
    delivery_channel.send_message(message, false, nil, nil, nil, replying_to)
  end
rescue => e
  warn!(error: e)

  nil
end

#await_response(responding_user, expected:, timeout: nil) ⇒ Object

Also see #wait_for_reply



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/esm/bot.rb', line 273

def await_response(responding_user, expected:, timeout: nil)
  counter = 0
  match = nil
  invalid_response = format_invalid_response(expected)

  responding_user =
    if responding_user.is_a?(String)
      user(responding_user)
    elsif responding_user.is_a?(ESM::User)
      responding_user.discord_user
    else
      responding_user
    end

  while match.nil? && counter < 99
    response =
      if ESM.env.test?
        ESM::Test.wait_for_response(timeout: timeout)
      else
        # Add the await event
        responding_user.await!(timeout: timeout)
      end

    # We timed out
    break if response.nil?

    # Parse the match from the event
    match = response.message.content.match(
      Regexp.new(
        "(#{expected.map(&:downcase).join("|")})",
        Regexp::IGNORECASE
      )
    )

    # We found what we were looking for
    break if !match.nil?

    # Let the user know that was not quite what we were looking for
    deliver(invalid_response, to: responding_user)

    counter += 1
  end

  raise ESM::Exception::CheckFailure, I18n.t("failure_to_communicate") if match.nil?

  # Return the match
  match[1]
end

#bind_events!Object

Discord Events! These all have to have unique-to-ESM names since we are inheriting



86
87
88
89
90
91
92
93
# File 'lib/esm/bot.rb', line 86

def bind_events!
  mention(&method(:esm_mention))
  ready(&method(:esm_ready))
  server_create(&method(:esm_server_create))
  user_ban(&method(:esm_user_ban))
  user_unban(&method(:esm_user_unban))
  member_join(&method(:esm_member_join))
end

#channel_permission?(permission, channel) ⇒ Boolean

Checks if the bot has send permission to the provided channel

Parameters:

  • permission (Symbol)

    The permission to check

  • channel (Discordrb::Channel)

    The channel to check

Returns:

  • (Boolean)


178
179
180
# File 'lib/esm/bot.rb', line 178

def channel_permission?(permission, channel)
  profile.on(channel.server)&.permission?(permission, channel) || false
end

#deliver(message, to:, embed_message: "", replying_to: nil, block: false) ⇒ Discordrb::Message?

Sends a message via the bot to a channel

Parameters:

  • message (String, ESM::Embed)

    A message or embed to send

  • to (String, Discordrb::Commands::CommandEvent, Discordrb::Channel, Discordrb::Member, Discordrb::User)

    Where should the message be sent? This ultimately will end up as a channel

  • embed_message (String) (defaults to: "")

    An optional message to attach with an embed. Only works if message is an embed

  • replying_to (Discordrb::Message) (defaults to: nil)

    A message to "reply" to. Discord will reference the previous message

  • block (true/false) (defaults to: false)

    Controls if this should block and wait for the message to send and discord to reply, or send it and immediately return

Returns:

  • (Discordrb::Message, nil)


201
202
203
204
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
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/esm/bot.rb', line 201

def deliver(message, to:, embed_message: "", replying_to: nil, block: false)
  return if message.blank?

  replying_to = nil if replying_to.present? && !replying_to.is_a?(Discordrb::Message)
  message = message.join("\n") if message.is_a?(Array)

  delivery_channel = determine_delivery_channel(to)
  raise ESM::Exception::ChannelNotFound.new(message, to) if delivery_channel.nil?

  if !delivery_channel.pm?
    if !channel_permission?(:read_messages, delivery_channel)
      raise ESM::Exception::ChannelAccessDenied
    end

    if !channel_permission?(:send_messages, delivery_channel)
      raise ESM::Exception::ChannelAccessDenied
    end
  end

  promise = @delivery_overseer.add(
    message,
    delivery_channel,
    embed_message: embed_message,
    replying_to: replying_to,
    wait: block
  )

  # A "promise" is returned only if block is true.
  # If block is false, this will be nil and immediately return
  promise&.wait_for_delivery
rescue ESM::Exception::ChannelAccessDenied
  embed = ESM::Embed.build(
    :error,
    description: I18n.t(
      "exceptions.deliver_failure",
      channel_name: delivery_channel.name,
      message:
    )
  )

  community = ESM::Community.find_by_guild_id(delivery_channel.server.id)
  community.log_event(:error, embed)

  nil
rescue => e
  warn!(error: e)

  nil
end

#determine_delivery_channel(channel) ⇒ Object

Channel can be any of the following: An CommandEvent, a Channel, a User/Member, or a String (Channel, or user)



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/esm/bot.rb', line 323

def determine_delivery_channel(channel)
  return if channel.nil?

  case channel
  when Discordrb::Commands::CommandEvent
    channel.channel
  when Discordrb::Channel
    channel
  when ESM::User
    channel.discord_user.pm
  when Discordrb::Member, Discordrb::User
    channel.pm
  when String, Numeric
    # Try checking if it's a text channel
    temp_channel = self.channel(channel)

    # Okay, it might be a PM channel, just go with it regardless (it returns nil)
    if temp_channel.nil?
      pm_channel(channel)
    else
      temp_channel
    end
  end
end

#esm_member_join(event) ⇒ Object

Fires when a member joins a Discord server



160
161
162
163
164
# File 'lib/esm/bot.rb', line 160

def esm_member_join(event)
  return if ESM.env.development? && ESM.config.dev_user_allowlist.include?(event.user.id.to_s)

  ESM::Event::MemberJoin.new(event).run!
end

#esm_mention(_event) ⇒ Object



95
96
97
# File 'lib/esm/bot.rb', line 95

def esm_mention(_event)
  # This event is raised when the bot is mentioned in a message.
end

#esm_ready(_event) ⇒ Object



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/esm/bot.rb', line 99

def esm_ready(_event)
  @metadata = ESM::BotAttribute.first_or_create

  if .present?
    update_status(
      # status
      "online",
      # activity
      .status_message,
      # url
      nil,
      # since: 0
      # afk: 0
      activity_type: STATUS_TYPES[.status_type]
    )
  end

  # Sometimes the bot loses connection with Discord. Upon reconnect, the ready event will be triggered again.
  # Don't restart the websocket server again.
  if ready?
    warn!("ESM::Bot#esm_ready called after bot was ready")
    return
  end

  # Once everything is set up, the commands can be hooked
  ESM::Command.setup_event_hooks!

  @esm_status = :ready

  info!(
    status: @esm_status,
    invite_url: invite_url(permission_bits: ESM::Bot::PERMISSION_BITS),
    started_in: "#{@timer.stop!}s"
  )

  ESM::API.run

  # V1
  ESM::Websocket.start!
  ESM::Request::Overseer.watch
  # V1

  # Wait until after the bot is connected before allowing servers to connect
  ESM::Connection::Server.start
end

#esm_server_create(event) ⇒ Object



145
146
147
148
# File 'lib/esm/bot.rb', line 145

def esm_server_create(event)
  # This event is raised when a server is created respective to the bot
  ESM::Event::ServerCreate.new(event.server).run!
end

#esm_user_ban(event) ⇒ Object



150
151
152
153
# File 'lib/esm/bot.rb', line 150

def esm_user_ban(event)
  # This event is raised when a user is banned from a server.
  # IDEA: Ask the banning admin if they would also like to ban the user on the server
end

#esm_user_unban(event) ⇒ Object



155
156
157
# File 'lib/esm/bot.rb', line 155

def esm_user_unban(event)
  # This event is raised when a user is unbanned from a server.
end

#log_error(error_hash) ⇒ Object



392
393
394
395
396
397
398
# File 'lib/esm/bot.rb', line 392

def log_error(error_hash)
  error!(error_hash)
  return if ESM.config.error_logging_channel_id.blank?

  error_message = JSON.pretty_generate(error_hash).tr("`", "\\\\`")
  ESM.bot.deliver("```#{error_message}```", to: ESM.config.error_logging_channel_id)
end

#ready?Boolean

Returns:

  • (Boolean)


186
187
188
# File 'lib/esm/bot.rb', line 186

def ready?
  @esm_status == :ready
end

#run(async: false, skip_initialization: false) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/esm/bot.rb', line 48

def run(async: false, skip_initialization: false)
  @timer.start!

  ESM::Command.load

  # This is needed for console. Otherwise the console's connection would start receiving events
  # such as server connections
  if skip_initialization
    warn!("skip_initialization is set! ESM will not connect to Discord, bind to any events, or start any services")
    return
  end

  # Binds the Discord Events
  bind_events!

  # Start the bot
  super(async)
end

#stopObject



67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/esm/bot.rb', line 67

def stop
  return if stopping?

  @esm_status = :stopping

  ESM::API.stop
  ESM::Connection::Server.stop

  # V1
  ESM::Websocket::Server.stop
  ESM::Request::Overseer.die

  super
end

#stopping?Boolean

Returns:

  • (Boolean)


182
183
184
# File 'lib/esm/bot.rb', line 182

def stopping?
  @esm_status == :stopping
end

#wait_for_reply(user_id:, channel_id:, expires_at: 5.minutes.from_now) {|event| ... } ⇒ true

Successor to #await_response. Waits for an event from user_id and channel_id

Parameters:

  • user_id (Integer/String)

    The ID of the user who sends the message

  • channel_id (Integer/String)

    The ID of the channel where the message is sent to. The bot must be a member of said channel

  • expires_at (DateTime, Time) (defaults to: 5.minutes.from_now)

    When this time is reached, the callback will be called with nil for the event

  • &callback (Proc)

    The code to execute once the message has been received

Yields:

  • (event)

Returns:

  • (true)


358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'lib/esm/bot.rb', line 358

def wait_for_reply(user_id:, channel_id:, expires_at: 5.minutes.from_now, &callback)
  @mutex.synchronize do
    @waiting_for[user_id] ||= []
    @waiting_for[user_id] << channel_id
  end

  # Event will be nil if it times out
  timeout = expires_at - ::Time.zone.now
  event =
    if ESM.env.test?
      ESM::Test.wait_for_response(timeout: timeout)
    else
      add_await!(Discordrb::Events::MessageEvent, {from: user_id, in: channel_id, timeout: timeout})
    end

  @mutex.synchronize do
    @waiting_for[user_id]&.delete_if { |id| id == channel_id }
  end

  return event unless callback

  yield(event)
  nil
end

#waiting_for_reply?(user_id:, channel_id:) ⇒ Boolean

Returns:

  • (Boolean)


383
384
385
386
387
388
389
390
# File 'lib/esm/bot.rb', line 383

def waiting_for_reply?(user_id:, channel_id:)
  @mutex.synchronize do
    channel_ids = @waiting_for[user_id]
    return false if channel_ids.blank?

    channel_ids.include?(channel_id)
  end
end