Class: Discorb::Client

Inherits:
Object
  • Object
show all
Includes:
Discorb::Command::Handler, Gateway::Handler
Defined in:
lib/discorb/client.rb

Overview

Class for connecting to the Discord server.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Discorb::Command::Handler

#message_command, #setup_commands, #slash, #slash_group, #user_command

Constructor Details

#initialize(allowed_mentions: nil, intents: nil, message_caches: 1000, log: nil, colorize_log: false, log_level: :info, wait_until_ready: true, overwrite_application_commands: true) -> Client

Initializes a new client.

Parameters:

  • allowed_mentions (Discorb::AllowedMentions) (defaults to: nil)

    The allowed mentions that the client is using.

  • intents (Discorb::Intents) (defaults to: nil)

    The intents that the client is currently using.

  • message_caches (Integer) (defaults to: 1000)

    The number of messages to cache.

  • log (#puts) (defaults to: nil)

    The IO object to use for logging.

  • colorize_log (Boolean) (defaults to: false)

    Whether to colorize the log.

  • log_level (:debug, :info, :warn, :error, :critical) (defaults to: :info)

    The log level.

  • wait_until_ready (Boolean) (defaults to: true)

    Whether to delay event dispatch until ready.

  • overwrite_application_commands (Boolean) (defaults to: true)

    Whether to overwrite application commands on ready.



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/discorb/client.rb', line 63

def initialize(
  allowed_mentions: nil, intents: nil, message_caches: 1000,
  log: nil, colorize_log: false, log_level: :info,
  wait_until_ready: true, overwrite_application_commands: true
)
  @allowed_mentions = allowed_mentions || AllowedMentions.new(everyone: true, roles: true, users: true)
  @intents = (intents or Intents.default)
  @events = {}
  @api_version = nil
  @log = Logger.new(log, colorize_log, log_level)
  @user = nil
  @users = Discorb::Dictionary.new
  @channels = Discorb::Dictionary.new
  @guilds = Discorb::Dictionary.new(sort: ->(k) { k[0].to_i })
  @emojis = Discorb::Dictionary.new
  @messages = Discorb::Dictionary.new(limit: message_caches)
  @application = nil
  @last_s = nil
  @identify_presence = nil
  @wait_until_ready = wait_until_ready
  @ready = false
  @tasks = []
  @conditions = {}
  @commands = []
  @overwrite_application_commands = overwrite_application_commands
end

Instance Attribute Details

#allowed_mentions -> Discorb::AllowedMentions (readonly)

Returns The allowed mentions that the client is using.

Returns:



29
30
31
# File 'lib/discorb/client.rb', line 29

def allowed_mentions
  @allowed_mentions
end

#api_version -> Integer? (readonly)

Returns:

  • (Integer)

    The API version of the Discord gateway.

  • (nil)

    If not connected to the gateway.



25
26
27
# File 'lib/discorb/client.rb', line 25

def api_version
  @api_version
end

#application -> Discorb::Application? (readonly)

Returns:



18
19
20
# File 'lib/discorb/client.rb', line 18

def application
  @application
end

#channels -> Discorb::Dictionary{Discorb::Snowflake => Discorb::Channel} (readonly)

Returns A dictionary of channels.

Returns:



37
38
39
# File 'lib/discorb/client.rb', line 37

def channels
  @channels
end

#commands -> Array<Discorb::Command::Command> (readonly)

Returns The commands that the client is using.

Returns:



45
46
47
# File 'lib/discorb/client.rb', line 45

def commands
  @commands
end

#emojis -> Discorb::Dictionary{Discorb::Snowflake => Discorb::Emoji} (readonly)

Returns A dictionary of emojis.

Returns:



39
40
41
# File 'lib/discorb/client.rb', line 39

def emojis
  @emojis
end

#guilds -> Discorb::Dictionary{Discorb::Snowflake => Discorb::Guild} (readonly)

Returns A dictionary of guilds.

Returns:



33
34
35
# File 'lib/discorb/client.rb', line 33

def guilds
  @guilds
end

#heartbeat_interval -> Integer (readonly)

Returns The heartbeat interval.

Returns:

  • (Integer)

    The heartbeat interval.



22
23
24
# File 'lib/discorb/client.rb', line 22

def heartbeat_interval
  @heartbeat_interval
end

#http -> Discorb::HTTP (readonly)

Returns The http client.

Returns:



20
21
22
# File 'lib/discorb/client.rb', line 20

def http
  @http
end

#intents -> Discorb::Intents

Returns The intents that the client is currently using.

Returns:



15
16
17
# File 'lib/discorb/client.rb', line 15

def intents
  @intents
end

#log -> Discorb::Logger (readonly)

Returns The logger.

Returns:

  • (Discorb::Logger)

    The logger.



43
44
45
# File 'lib/discorb/client.rb', line 43

def log
  @log
end

#messages -> Discorb::Dictionary{Discorb::Snowflake => Discorb::Message} (readonly)

Returns A dictionary of messages.

Returns:



41
42
43
# File 'lib/discorb/client.rb', line 41

def messages
  @messages
end

#ping -> Float? (readonly)

Returns:

  • (Float)

    The ping of the client. @note This will be calculated from heartbeat and heartbeat_ack.

  • (nil)

    If not connected to the gateway.



49
50
51
# File 'lib/discorb/client.rb', line 49

def ping
  @ping
end

#token -> String (readonly)

Returns The token of the client.

Returns:

  • (String)

    The token of the client.



27
28
29
# File 'lib/discorb/client.rb', line 27

def token
  @token
end

#user -> Discorb::ClientUser (readonly)

Returns The client user.

Returns:



31
32
33
# File 'lib/discorb/client.rb', line 31

def user
  @user
end

#users -> Discorb::Dictionary{Discorb::Snowflake => Discorb::User} (readonly)

Returns A dictionary of users.

Returns:



35
36
37
# File 'lib/discorb/client.rb', line 35

def users
  @users
end

Instance Method Details

#dispatch(event_name, *args) -> Object

Dispatch an event.

Parameters:

  • event_name (Symbol)

    The name of the event.

  • args (Object)

    The arguments to pass to the event.



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/discorb/client.rb', line 139

def dispatch(event_name, *args)
  Async do
    if (conditions = @conditions[event_name])
      ids = Set[*conditions.map(&:first).map(&:object_id)]
      conditions.delete_if do |condition|
        next unless ids.include?(condition.first.object_id)

        check_result = condition[1].nil? || condition[1].call(*args)
        if check_result
          condition.first.signal(args)
          true
        else
          false
        end
      end
    end
    if @events[event_name].nil?
      @log.debug "Event #{event_name} doesn't have any proc, skipping"
      next
    end
    @log.debug "Dispatching event #{event_name}"
    @events[event_name].each do |block|
      lambda { |event_args|
        Async(annotation: "Discorb event: #{event_name}") do |task|
          @events[event_name].delete(block) if block.discriminator[:once]
          block.call(*event_args)
          @log.debug "Dispatched proc with ID #{block.id.inspect}"
        rescue StandardError, ScriptError => e
          message = "An error occurred while dispatching proc with ID #{block.id.inspect}\n#{e.full_message}"
          dispatch(:error, event_name, event_args, e)
          if @log.out
            @log.error message
          else
            warn message
          end
        end
      }.call(args)
    end
  end
end

#event_lock(event, timeout = nil, &check) -> Object Also known as: await

Method to wait for a event.

Parameters:

  • event (Symbol)

    The name of the event.

  • timeout (Integer) (defaults to: nil)

    The timeout in seconds.

  • check (Proc)

    The check to use.

Returns:

  • (Object)

    The result of the event.

Raises:



330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/discorb/client.rb', line 330

def event_lock(event, timeout = nil, &check)
  Async do |task|
    condition = Async::Condition.new
    @conditions[event] ||= []
    @conditions[event] << [condition, check]
    if timeout.nil?
      value = condition.wait
    else
      timeout_task = task.with_timeout(timeout) do
        condition.wait
      rescue Async::TimeoutError
        @conditions[event].delete_if { |c| c.first == condition }
        raise Discorb::TimeoutError, "Timeout waiting for event #{event}", cause: nil
      end
      value = timeout_task
    end
    value.length <= 1 ? value.first : value
  end
end

#extend(mod) -> Object

Load the extension.

Parameters:

  • mod (Module)

    The extension to load.



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/discorb/client.rb', line 361

def extend(mod)
  if mod.respond_to?(:events)
    @events.each_value do |event|
      event.delete_if { |c| c.discriminator[:extension] == mod.name }
    end
    mod.events.each do |name, events|
      @events[name] = [] if @events[name].nil?
      events.each do |event|
        @events[name] << event
      end
    end
    mod.client = self
  end
  super(mod)
end

#fetch_application(force: false) -> Discorb::Application

Note:

This is an asynchronous method, it will return a Async::Task object. Use Async::Task#wait to get the result.

Note:

This method calls HTTP request.

Fetch webhook from ID. If application was cached, it will be used.

Parameters:

  • force (Boolean) (defaults to: false)

    Whether to force the fetch.

Returns:

Raises:



272
273
274
275
276
277
278
279
280
# File 'lib/discorb/client.rb', line 272

def fetch_application(force: false)
  Async do
    next @application if @application && !force

    _resp, data = http.get("/oauth2/applications/@me").wait
    @application = Application.new(self, data)
    @application
  end
end

#fetch_channel(id) -> Discorb::Channel

Note:

This is an asynchronous method, it will return a Async::Task object. Use Async::Task#wait to get the result.

Note:

This method calls HTTP request.

Fetch channel from ID.

Parameters:

  • id (#to_s)

    The ID of the channel.

Returns:

Raises:



219
220
221
222
223
224
# File 'lib/discorb/client.rb', line 219

def fetch_channel(id)
  Async do
    _resp, data = http.get("/channels/#{id}").wait
    Channel.make_channel(self, data)
  end
end

#fetch_guild(id) -> Discorb::Guild

Note:

This is an asynchronous method, it will return a Async::Task object. Use Async::Task#wait to get the result.

Note:

This method calls HTTP request.

Fetch guild from ID.

Parameters:

  • id (#to_s)

    <description>

Returns:

Raises:



237
238
239
240
241
242
# File 'lib/discorb/client.rb', line 237

def fetch_guild(id)
  Async do
    _resp, data = http.get("/guilds/#{id}").wait
    Guild.new(self, data, false)
  end
end

#fetch_invite(code, with_count: false, with_expiration: false) -> Discorb::Invite

Note:

This is an asynchronous method, it will return a Async::Task object. Use Async::Task#wait to get the result.

Note:

This method calls HTTP request.

Fetch invite from code.

Parameters:

  • code (String)

    The code of the invite.

  • with_count (Boolean) (defaults to: false)

    Whether to include the count of the invite.

  • with_expiration (Boolean) (defaults to: false)

    Whether to include the expiration of the invite.

Returns:

Raises:



255
256
257
258
259
260
# File 'lib/discorb/client.rb', line 255

def fetch_invite(code, with_count: false, with_expiration: false)
  Async do
    _resp, data = http.get("/invites/#{code}?with_count=#{with_count}&with_expiration=#{with_expiration}").wait
    Invite.new(self, data, false)
  end
end

#fetch_nitro_sticker_packs -> Array<Discorb::Sticker::Pack>

Note:

This is an asynchronous method, it will return a Async::Task object. Use Async::Task#wait to get the result.

Note:

This method calls HTTP request.

Fetch nitro sticker pack from ID.

Returns:

Raises:



289
290
291
292
293
294
# File 'lib/discorb/client.rb', line 289

def fetch_nitro_sticker_packs
  Async do
    _resp, data = http.get("/stickers-packs").wait
    data.map { |pack| Sticker::Pack.new(self, pack) }
  end
end

#fetch_user(id) -> Discorb::User

Note:

This is an asynchronous method, it will return a Async::Task object. Use Async::Task#wait to get the result.

Note:

This method calls HTTP request.

Fetch user from ID.

Parameters:

  • id (#to_s)

    <description>

Returns:

Raises:



201
202
203
204
205
206
# File 'lib/discorb/client.rb', line 201

def fetch_user(id)
  Async do
    _resp, data = http.get("/users/#{id}").wait
    User.new(self, data)
  end
end

#inspect -> Object



352
353
354
# File 'lib/discorb/client.rb', line 352

def inspect
  "#<#{self.class} user=\"#{user}\">"
end

#on(event_name, id: nil, **discriminator, &block) -> Discorb::Event

Registers an event handler.

Parameters:

  • event_name (Symbol)

    The name of the event.

  • id (Symbol) (defaults to: nil)

    Custom ID of the event.

  • discriminator (Hash)

    The discriminator of the event.

  • block (Proc)

    The block to execute when the event is triggered.

Returns:

See Also:



101
102
103
104
105
106
# File 'lib/discorb/client.rb', line 101

def on(event_name, id: nil, **discriminator, &block)
  ne = Event.new(block, id, discriminator)
  @events[event_name] ||= []
  @events[event_name] << ne
  ne
end

#once(event_name, id: nil, **discriminator, &block) -> Discorb::Event

Almost same as #on, but only triggers the event once.

Parameters:

  • event_name (Symbol)

    The name of the event.

  • id (Symbol) (defaults to: nil)

    Custom ID of the event.

  • discriminator (Hash)

    The discriminator of the event.

  • block (Proc)

    The block to execute when the event is triggered.

Returns:



115
116
117
118
119
120
121
# File 'lib/discorb/client.rb', line 115

def once(event_name, id: nil, **discriminator, &block)
  discriminator[:once] = true
  ne = Event.new(block, id, discriminator)
  @events[event_name] ||= []
  @events[event_name] << ne
  ne
end

#remove_event(event_name, id) -> Object

Remove event by ID.

Parameters:

  • event_name (Symbol)

    The name of the event.

  • id (Symbol)

    The ID of the event.



129
130
131
# File 'lib/discorb/client.rb', line 129

def remove_event(event_name, id)
  @events[event_name].delete_if { |e| e.id == id }
end

#run(token) -> Object

Starts the client.

Parameters:

  • token (String)

    The token to use.



185
186
187
188
# File 'lib/discorb/client.rb', line 185

def run(token)
  @token = token.to_s
  connect_gateway(true)
end

#update_presence(activity = nil, status: nil) -> Object Also known as: change_presence

Update presence of the client.

Parameters:

  • activity (Discorb::Activity) (defaults to: nil)

    The activity to update.

  • status (:online, :idle, :dnd, :invisible) (defaults to: nil)

    The status to update.



302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/discorb/client.rb', line 302

def update_presence(activity = nil, status: nil)
  payload = {}
  if !activity.nil?
    payload[:activities] = [activity.to_hash]
  end
  payload[:status] = status unless status.nil?
  if @connection
    Async do
      send_gateway(3, **payload)
    end
  else
    @identify_presence = payload
  end
end