Class: Discorb::Client

Inherits:
Object
  • Object
show all
Includes:
ApplicationCommand::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 ApplicationCommand::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, fetch_member: false, title: nil) -> 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.

  • fetch_member (Boolean) (defaults to: false)

    Whether to fetch member on ready. This may slow down the client. Default to false.

  • title (String) (defaults to: nil)

    The title of the process. false to default, nil to discorb: User#0000. Default to nil.



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/discorb/client.rb', line 73

def initialize(
  allowed_mentions: nil, intents: nil, message_caches: 1000,
  log: nil, colorize_log: false, log_level: :info,
  wait_until_ready: true, fetch_member: false,
  title: nil
)
  @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 = []
  @bottom_commands = []
  @status = :initialized
  @fetch_member = fetch_member
  @title = title
  @extensions = {}
  set_default_events
end

Instance Attribute Details

#allowed_mentions -> Discorb::AllowedMentions (readonly)

Returns The allowed mentions that the client is using.

Returns:



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

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.



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

def api_version
  @api_version
end

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

Returns:



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

def application
  @application
end

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

Returns A dictionary of channels.

Returns:



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

def channels
  @channels
end

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

Returns The commands that the client is using.

Returns:



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

def commands
  @commands
end

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

Returns A dictionary of emojis.

Returns:



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

def emojis
  @emojis
end

#extensions -> Hash{String => Discorb::Extension} (readonly)

Returns The loaded extensions.

Returns:



56
57
58
# File 'lib/discorb/client.rb', line 56

def extensions
  @extensions
end

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

Returns A dictionary of guilds.

Returns:



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

def guilds
  @guilds
end

#heartbeat_interval -> Integer (readonly)

Returns The heartbeat interval.

Returns:

  • (Integer)

    The heartbeat interval.



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

def heartbeat_interval
  @heartbeat_interval
end

#http -> Discorb::HTTP (readonly)

Returns The http client.

Returns:

  • (Discorb::HTTP)

    The http client.



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

def http
  @http
end

#intents -> Discorb::Intents

Returns The intents that the client is currently using.

Returns:



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

def intents
  @intents
end

#log -> Discorb::Logger (readonly)

Returns The logger.

Returns:

  • (Discorb::Logger)

    The logger.



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

def log
  @log
end

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

Returns A dictionary of messages.

Returns:



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

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.



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

def ping
  @ping
end

#session_id -> Integer (readonly)

Returns The session ID of connection.

Returns:

  • (Integer)

    The session ID of connection.



54
55
56
# File 'lib/discorb/client.rb', line 54

def session_id
  @session_id
end

#status -> :initialized, ... (readonly)

Returns The status of the client.

Returns:

  • (:initialized, :running, :closed)

    The status of the client.



52
53
54
# File 'lib/discorb/client.rb', line 52

def status
  @status
end

#token -> String (readonly)

Returns The token of the client.

Returns:

  • (String)

    The token of the client.



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

def token
  @token
end

#user -> Discorb::ClientUser (readonly)

Returns The client user.

Returns:



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

def user
  @user
end

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

Returns A dictionary of users.

Returns:



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

def users
  @users
end

Instance Method Details

#close! -> Object

Stops the client.



472
473
474
475
476
477
# File 'lib/discorb/client.rb', line 472

def close!
  @connection.send_close
  @tasks.each(&:stop)
  @status = :closed
  @close_condition.signal
end

#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.



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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/discorb/client.rb', line 153

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
    events = @events[event_name].dup || []
    if respond_to?("on_" + event_name.to_s)
      event_method = method("on_" + event_name.to_s)
      class << event_method
        def id
          "method"
        end
      end
      events << event_method
    end
    if events.nil?
      @log.debug "Event #{event_name} doesn't have any proc, skipping"
      next
    end
    @log.debug "Dispatching event #{event_name}"
    events.each do |block|
      Async do
        Async(annotation: "Discorb event: #{event_name}") do |task|
          if block.is_a?(Discorb::Event)
            @events[event_name].delete(block) if block.[:once]
          end
          block.call(*args)
          @log.debug "Dispatched proc with ID #{block.id.inspect}"
        rescue StandardError, ScriptError => e
          dispatch(:error, event_name, args, e)
        end
      end
    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:



346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/discorb/client.rb', line 346

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

#fetch_application(force: false) -> Async::Task<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:



282
283
284
285
286
287
288
289
290
# File 'lib/discorb/client.rb', line 282

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) -> Async::Task<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:



229
230
231
232
233
234
# File 'lib/discorb/client.rb', line 229

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

#fetch_guild(id) -> Async::Task<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:



247
248
249
250
251
252
# File 'lib/discorb/client.rb', line 247

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) -> Async::Task<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:



265
266
267
268
269
270
# File 'lib/discorb/client.rb', line 265

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 -> Async::Task<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:



299
300
301
302
303
304
# File 'lib/discorb/client.rb', line 299

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) -> Async::Task<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:



211
212
213
214
215
216
# File 'lib/discorb/client.rb', line 211

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

#inspect -> Object



368
369
370
# File 'lib/discorb/client.rb', line 368

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

#load_extension(ext) -> Object

Load the extension.

Parameters:

  • ext (Class, Discorb::Extension)

    The extension to load.

  • ... (Object)

    The arguments to pass to the ext#initialize.



378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/discorb/client.rb', line 378

def load_extension(ext, ...)
  if ext.is_a?(Class)
    raise ArgumentError, "#{ext} is not a extension" unless ext < Discorb::Extension
    ins = ext.new(self, ...)
  elsif ext.is_a?(Discorb::Extension)
    ins = ext
  else
    raise ArgumentError, "#{ext} is not a extension"
  end

  @events.each_value do |event|
    event.delete_if { |c| c.[:extension] == ins.class.name }
  end
  ins.events.each do |name, events|
    @events[name] ||= []
    events.each do |event|
      @events[name] << event
    end
  end
  @commands.delete_if do |cmd|
    cmd.respond_to? :extension and cmd.extension == ins.name
  end
  ins.class.commands.each do |cmd|
    cmd.define_singleton_method(:extension) { ins.name }
    @commands << cmd
  end

  cls = ins.class
  cls.loaded(self, ...) if cls.respond_to? :loaded
  @bottom_commands += ins.class.bottom_commands
  @extensions[ins.class.name] = ins
  ins
end

#on(event_name, id: nil, **metadata, &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.

  • metadata (Hash)

    The metadata of the event.

  • block (Proc)

    The block to execute when the event is triggered.

Returns:

See Also:



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

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

#once(event_name, id: nil, **metadata, &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.

  • metadata (Hash)

    The metadata of the event.

  • block (Proc)

    The block to execute when the event is triggered.

Returns:



132
133
134
135
# File 'lib/discorb/client.rb', line 132

def once(event_name, id: nil, **, &block)
  [:once] = true
  on(event_name, id: id, **, &block)
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.



143
144
145
# File 'lib/discorb/client.rb', line 143

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

#run(token = nil) -> Object

Note:

This method behavior will change by CLI.

Note:

If the token is nil, you should use discorb run with the -t or --token option.

Starts the client.

Parameters:

  • token (String, nil) (defaults to: nil)

    The token to use.

See Also:



424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
# File 'lib/discorb/client.rb', line 424

def run(token = nil)
  token ||= ENV["DISCORB_CLI_TOKEN"]
  raise ArgumentError, "Token is not specified, and -t/--token is not specified" if token.nil?
  case ENV["DISCORB_CLI_FLAG"]
  when nil
    start_client(token)
  when "run"
    require "json"
    options = JSON.parse(ENV["DISCORB_CLI_OPTIONS"], symbolize_names: true)
    @daemon = options[:daemon]

    setup_commands(token) if options[:setup]
    if options[:log_level]
      if options[:log_level] == "none"
        @log.out = nil
      else
        @log.out = case options[:log_file]
          when nil, "stderr"
            $stderr
          when "stdout"
            $stdout
          else
            ::File.open(options[:log_file], "a")
          end
        @log.level = options[:log_level].to_sym
        @log.colorize_log = options[:log_color] == nil ? @log.out.isatty : options[:log_color]
      end
    end
    start_client(token)
  when "setup"
    guild_ids = "global"
    if guilds = ENV["DISCORB_SETUP_GUILDS"]
      guild_ids = guilds.split(",")
    end
    if guild_ids == ["global"]
      guild_ids = false
    end
    setup_commands(token, guild_ids: guild_ids).wait
    @events[:setup]&.each do |event|
      event.call
    end
    self.on_setup if respond_to? :on_setup
  end
end

#update_presence(activity = nil, status: nil, afk: false) -> 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.

  • afk (String) (defaults to: false)

    Whether to set the client as AFK.



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/discorb/client.rb', line 313

def update_presence(activity = nil, status: nil, afk: false)
  payload = {
    activities: [],
    status: status,
    afk: nil,
    since: nil,
  }
  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