Class: DiscordApi

Inherits:
Object
  • Object
show all
Defined in:
lib/disrb.rb,
lib/disrb/user.rb,
lib/disrb/guild.rb,
lib/disrb/message.rb,
lib/disrb/application_commands.rb

Overview

Class that contains functions that allow interacting with the Discord API.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(authorization_token_type, authorization_token, verbosity_level = nil) ⇒ DiscordApi

Creates a new DiscordApi instance. (required to use most functions)

Set verbosity_level to:

  • ‘all’ or 5 to log all of the below plus debug messages

  • ‘info’, 4 or nil to log all of the below plus info messages [DEFAULT]

  • ‘warning’ or 3 to log all of the below plus warning messages

  • ‘error’ or 2 to log fatal errors and error messages

  • ‘fatal_error’ or 1 to log only fatal errors

  • ‘none’ or 0 for no logging



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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/disrb.rb', line 73

def initialize(authorization_token_type, authorization_token, verbosity_level = nil)
  @api_version = '10'
  @base_url = "https://discord.com/api/v#{@api_version}"
  @authorization_token_type = authorization_token_type
  @authorization_token = authorization_token
  @authorization_header = "#{authorization_token_type} #{authorization_token}"
  if verbosity_level.nil?
    @verbosity_level = 4
  elsif verbosity_level.is_a?(String)
    case verbosity_level.downcase
    when 'all'
      @verbosity_level = 5
    when 'info'
      @verbosity_level = 4
    when 'warning'
      @verbosity_level = 3
    when 'error'
      @verbosity_level = 2
    when 'fatal_error'
      @verbosity_level = 1
    when 'none'
      @verbosity_level = 0
    else
      Logger2.s_error("Unknown verbosity level: #{verbosity_level}. Defaulting to 'info'.")
      @verbosity_level = 4
    end
  elsif verbosity_level.is_a?(Integer)
    if verbosity_level >= 0 && verbosity_level <= 5
      @verbosity_level = verbosity_level
    else
      Logger2.s_error("Unknown verbosity level: #{verbosity_level}. Defaulting to 'info'.")
      @verbosity_level = 4
    end
  else
    Logger2.s_error("Unknown verbosity level: #{verbosity_level}. Defaulting to 'info'.")
    @verbosity_level = 4
  end
  @logger = Logger2.new(@verbosity_level)
  url = "#{@base_url}/applications/@me"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  if response.status == 200
    @application_id = JSON.parse(response.body)['id']
  else
    @logger.fatal_error("Failed to get application ID with response: #{response.body}")
    exit
  end
end

Instance Attribute Details

#application_idInteger



58
# File 'lib/disrb.rb', line 58

attr_accessor(:base_url, :authorization_header, :application_id, :logger)

#authorization_headerString



58
# File 'lib/disrb.rb', line 58

attr_accessor(:base_url, :authorization_header, :application_id, :logger)

#base_urlString



58
59
60
# File 'lib/disrb.rb', line 58

def base_url
  @base_url
end

#loggerObject

Returns the value of attribute logger.



58
59
60
# File 'lib/disrb.rb', line 58

def logger
  @logger
end

Class Method Details

.bitwise_permission_flagsObject

Returns a hash of permission names and their corresponding bitwise values. See discord.com/developers/docs/topics/permissions#permissions-bitwise-permission-flags



373
374
375
376
377
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'lib/disrb.rb', line 373

def self.bitwise_permission_flags
  {
    create_instant_invite: 1 << 0,
    kick_members: 1 << 1,
    ban_members: 1 << 2,
    administrator: 1 << 3,
    manage_channels: 1 << 4,
    manage_guild: 1 << 5,
    add_reactions: 1 << 6,
    view_audit_log: 1 << 7,
    priority_speaker: 1 << 8,
    stream: 1 << 9,
    view_channel: 1 << 10,
    send_messages: 1 << 11,
    send_tts_messages: 1 << 12,
    manage_messages: 1 << 13,
    embed_links: 1 << 14,
    attach_files: 1 << 15,
    read_message_history: 1 << 16,
    mention_everyone: 1 << 17,
    use_external_emojis: 1 << 18,
    view_guild_insights: 1 << 19,
    connect: 1 << 20,
    speak: 1 << 21,
    mute_members: 1 << 22,
    deafen_members: 1 << 23,
    move_members: 1 << 24,
    use_vad: 1 << 25,
    change_nickname: 1 << 26,
    manage_nicknames: 1 << 27,
    manage_roles: 1 << 28,
    manage_webhooks: 1 << 29,
    manage_guild_expressions: 1 << 30,
    use_application_commands: 1 << 31,
    request_to_speak: 1 << 32,
    manage_events: 1 << 33,
    manage_threads: 1 << 34,
    create_public_threads: 1 << 35,
    create_private_threads: 1 << 36,
    use_external_stickers: 1 << 37,
    send_messages_in_threads: 1 << 38,
    use_embedded_activities: 1 << 39,
    moderate_members: 1 << 40,
    view_creator_monetization_analytics: 1 << 41,
    use_soundboard: 1 << 42,
    create_guild_expressions: 1 << 43,
    create_events: 1 << 44,
    use_external_sounds: 1 << 45,
    send_voice_messages: 1 << 46,
    send_polls: 1 << 49,
    use_external_apps: 1 << 50,
    pin_messages: 1 << 51
  }
end

.calculate_gateway_intents(intents) ⇒ Integer

Calculates a gateway intents integer from an array of intent names. See discord.com/developers/docs/topics/gateway#gateway-intents



457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
# File 'lib/disrb.rb', line 457

def self.calculate_gateway_intents(intents)
  bitwise_intent_flags = {
    guilds: 1 << 0,
    guild_members: 1 << 1,
    guild_bans: 1 << 2,
    guild_emojis_and_stickers: 1 << 3,
    guild_integrations: 1 << 4,
    guild_webhooks: 1 << 5,
    guild_invites: 1 << 6,
    guild_voice_states: 1 << 7,
    guild_presences: 1 << 8,
    guild_messages: 1 << 9,
    guild_message_reactions: 1 << 10,
    guild_message_typing: 1 << 11,
    direct_messages: 1 << 12,
    direct_message_reactions: 1 << 13,
    direct_message_typing: 1 << 14,
    message_content: 1 << 15,
    guild_scheduled_events: 1 << 16
  }
  intents = intents.map do |intent|
    bitwise_intent_flags[intent.downcase.to_sym]
  end
  intents.reduce(0) { |acc, n| acc | n }
end

.calculate_permissions_integer(permissions) ⇒ Integer

Calculates a permissions integer from an array of permission names. See discord.com/developers/docs/topics/permissions#permissions-bitwise-permission-flags



433
434
435
436
437
438
# File 'lib/disrb.rb', line 433

def self.calculate_permissions_integer(permissions)
  permissions = permissions.map do |permission|
    DiscordApi.bitwise_permission_flags[permission.downcase.to_sym]
  end
  permissions.reduce(0) { |acc, n| acc | n }
end

.delete(url, headers = nil) ⇒ Faraday::Response

Performs an HTTP DELETE request using Faraday.



504
505
506
507
508
509
510
511
512
513
514
515
# File 'lib/disrb.rb', line 504

def self.delete(url, headers = nil)
  split_url = url.split(%r{(http[^/]+)(/.*)}).reject(&:empty?)
  @logger.error("Empty/invalid URL provided: #{url}. Cannot perform DELETE request.") if split_url.empty?
  host = split_url[0]
  path = split_url[1] if split_url[1]
  conn = Faraday.new(url: host, headers: headers)
  if path
    conn.delete(path)
  else
    conn.delete
  end
end

.get(url, headers = nil) ⇒ Faraday::Response

Performs an HTTP GET request using Faraday.



487
488
489
490
491
492
493
494
495
496
497
498
# File 'lib/disrb.rb', line 487

def self.get(url, headers = nil)
  split_url = url.split(%r{(http[^/]+)(/.*)}).reject(&:empty?)
  @logger.error("Empty/invalid URL provided: #{url}. Cannot perform GET request.") if split_url.empty?
  host = split_url[0]
  path = split_url[1] if split_url[1]
  conn = Faraday.new(url: host, headers: headers)
  if path
    conn.get(path)
  else
    conn.get
  end
end

.handle_query_strings(query_string_hash) ⇒ String

Converts a hash into a valid query string. If the hash is empty, it returns an empty string.

Examples:

Convert a hash into a query string

DiscordApi.handle_query_strings({'key1' => 'value1', 'key2' => 'value2'}) #=> "?key1=value1&key2=value2"


128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/disrb.rb', line 128

def self.handle_query_strings(query_string_hash)
  query_string_array = []
  query_string_hash.each do |key, value|
    if value.nil?
      next
    elsif query_string_array.empty?
      query_string_array << "?#{key}=#{value}"
    else
      query_string_array << "&#{key}=#{value}"
    end
  end
  query_string_array << '' if query_string_array.empty?
  query_string_array.join
end

.patch(url, data, headers = nil) ⇒ Faraday::Response

Performs an HTTP PATCH request using Faraday.



540
541
542
543
544
545
546
547
548
549
550
551
# File 'lib/disrb.rb', line 540

def self.patch(url, data, headers = nil)
  split_url = url.split(%r{(http[^/]+)(/.*)}).reject(&:empty?)
  @logger.error("Empty/invalid URL provided: #{url}. Cannot perform PATCH request.") if split_url.empty?
  host = split_url[0]
  path = split_url[1] if split_url[1]
  conn = Faraday.new(url: host, headers: headers)
  if path
    conn.patch(path, data)
  else
    conn.patch('', data)
  end
end

.post(url, data, headers = nil) ⇒ Faraday::Response

Performs an HTTP POST request using Faraday.



522
523
524
525
526
527
528
529
530
531
532
533
# File 'lib/disrb.rb', line 522

def self.post(url, data, headers = nil)
  split_url = url.split(%r{(http[^/]+)(/.*)}).reject(&:empty?)
  @logger.error("Empty/invalid URL provided: #{url}. Cannot perform POST request.") if split_url.empty?
  host = split_url[0]
  path = split_url[1] if split_url[1]
  conn = Faraday.new(url: host, headers: headers)
  if path
    conn.post(path, data)
  else
    conn.post('', data)
  end
end

.put(url, data, headers = nil) ⇒ Faraday::Response

Performs an HTTP PUT request using Faraday.



558
559
560
561
562
563
564
565
566
567
568
569
# File 'lib/disrb.rb', line 558

def self.put(url, data, headers = nil)
  split_url = url.split(%r{(http[^/]+)(/.*)}).reject(&:empty?)
  @logger.error("Empty/invalid URL provided: #{url}. Cannot perform PUT request.") if split_url.empty?
  host = split_url[0]
  path = split_url[1] if split_url[1]
  conn = Faraday.new(url: host, headers: headers)
  if path
    conn.put(path, data)
  else
    conn.put('', data)
  end
end

.reverse_permissions_integer(permissions_integer) ⇒ Array

Reverses a permissions integer back into an array of permission names. See discord.com/developers/docs/topics/permissions#permissions-bitwise-permission-flags



444
445
446
447
448
449
450
# File 'lib/disrb.rb', line 444

def self.reverse_permissions_integer(permissions_integer)
  permissions = []
  DiscordApi.bitwise_permission_flags.each do |permission, value|
    permissions << permission if (permissions_integer & value) != 0
  end
  permissions
end

Instance Method Details

#add_guild_member(guild_id, user_id, access_token, nick: nil, roles: nil, mute: nil, deaf: nil) ⇒ Faraday::Response

Adds a user to the specified guild. Returns 201 Created with the body being the Guild Member object of the added

user or 204 No Content if the user is already in the guild. See https://discord.com/developers/docs/resources/guild#add-guild-member


343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'lib/disrb/guild.rb', line 343

def add_guild_member(guild_id, user_id, access_token, nick: nil, roles: nil, mute: nil, deaf: nil)
  output = {}
  output[:access_token] = access_token
  output[:nick] = nick unless nick.nil?
  output[:roles] = roles unless roles.nil?
  output[:mute] = mute unless mute.nil?
  output[:deaf] = deaf unless deaf.nil?
  url = "#{@base_url}/guilds/#{guild_id}/members/#{user_id}"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  response = DiscordApi.put(url, data, headers)
  if response.status == 204
    @logger.warn("User with ID #{user_id} is already a member of the guild with ID #{guild_id}.")
  elsif response.status == 201
    @logger.info("Added user with ID #{user_id} to guild with ID #{guild_id}.")
  else
    @logger.error("Could not add user with ID #{user_id} to guild with ID #{guild_id}. Response: #{response.body}")
  end
  response
end

#add_guild_member_role(guild_id, user_id, role_id, audit_reason = nil) ⇒ Faraday::Response

Adds a role to a guild member. Returns 204 No Content on success. See discord.com/developers/docs/resources/guild#add-guild-member-role



479
480
481
482
483
484
485
486
487
488
489
# File 'lib/disrb/guild.rb', line 479

def add_guild_member_role(guild_id, user_id, role_id, audit_reason = nil)
  url = "#{@base_url}/guilds/#{guild_id}/members/#{user_id}/roles/#{role_id}"
  headers = { 'Authorization': @authorization_header }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.put(url, nil, headers)
  return response if response.status == 204

  @logger.error("Could not add role with ID #{role_id}, to user with ID #{user_id} in guild with ID #{guild_id}." \
                 " Response: #{response.body}")
  response
end

#begin_guild_prune(guild_id, days: nil, compute_prune_count: nil, include_roles: nil, reason: nil, audit_reason: nil) ⇒ Faraday::Response

Begins a guild prune operation. Returns 200 OK with a JSON object containing a ‘pruned’ key

(optional, enabled by default) indicating the number of members that were removed on success.
See https://discord.com/developers/docs/resources/guild#begin-guild-prune


850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
# File 'lib/disrb/guild.rb', line 850

def begin_guild_prune(guild_id, days: nil, compute_prune_count: nil, include_roles: nil, reason: nil,
                      audit_reason: nil)
  output = {}
  output[:days] = days unless days.nil?
  output[:compute_prune_count] = compute_prune_count unless compute_prune_count.nil?
  output[:include_roles] = include_roles unless include_roles.nil?
  unless reason.nil?
    @logger.warn('The "reason" parameter has been deprecated and should not be used!')
    output[:reason] = reason
  end
  url = "#{@base_url}/guilds/#{guild_id}/prune"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.post(url, data, headers)
  return response if response.status == 200

  @logger.error("Failed to begin guild prune. Response: #{response.body}")
  response
end

#bulk_delete_messages(channel_id, messages, audit_reason = nil) ⇒ Faraday::Response

Bulk deletes messages. Returns no content on success. See discord.com/developers/docs/resources/message#bulk-delete-messages



305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/disrb/message.rb', line 305

def bulk_delete_messages(channel_id, messages, audit_reason = nil)
  output = { messages: messages }
  url = "#{@base_url}/channels/#{channel_id}/messages/bulk-delete"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  headers[:'X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.post(url, data, headers)
  return response if response.status == 204

  @logger.error("Failed to bulk delete messages in channel with ID #{channel_id}. Response: #{response.body}")
  response
end

#bulk_guild_ban(guild_id, user_ids, delete_message_seconds: nil, audit_reason: nil) ⇒ Faraday::Response

Ban up to 200 users from a guild in a single request. Returns 200 OK with an array of the banned user IDs and the users that couldn’t be banned if atleast one user has been banned successfully. See discord.com/developers/docs/resources/guild#bulk-guild-ban



623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
# File 'lib/disrb/guild.rb', line 623

def bulk_guild_ban(guild_id, user_ids, delete_message_seconds: nil, audit_reason: nil)
  output = {}
  output[:user_ids] = user_ids unless user_ids.nil?
  output[:delete_message_seconds] = delete_message_seconds unless delete_message_seconds.nil?
  url = "#{@base_url}/guilds/#{guild_id}/bulk-ban"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.post(url, data, headers)
  return response if response.status == 200

  if response.status == 500_000
    @logger.error("No users were banned in bulk ban in guild with ID #{guild_id}. Response: #{response.body}")
  else
    @logger.error("Could not bulk ban users in guild with ID #{guild_id}. Response: #{response.body}")
  end
  response
end

#bulk_overwrite_global_application_commands(commands) ⇒ Faraday::Response

Overwrites all global application commands. Returns 200 OK with an array of the new command objects. See discord.com/developers/docs/interactions/application-commands#bulk-overwrite-global-application-commands



325
326
327
328
329
330
331
332
333
334
# File 'lib/disrb/application_commands.rb', line 325

def bulk_overwrite_global_application_commands(commands)
  url = "#{@base_url}/applications/#{@application_id}/commands"
  data = JSON.generate(commands)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  response = DiscordApi.put(url, data, headers)
  return response if response.status == 200

  @logger.error("Failed to bulk overwrite global application commands. Response: #{response.body}")
  response
end

#bulk_overwrite_guild_application_commands(guild_id, commands) ⇒ Faraday::Response

Overwrites all guild application commands in a guild. Returns 200 OK with an array of the new command objects. See discord.com/developers/docs/interactions/application-commands#bulk-overwrite-guild-application-commands



341
342
343
344
345
346
347
348
349
350
351
# File 'lib/disrb/application_commands.rb', line 341

def bulk_overwrite_guild_application_commands(guild_id, commands)
  url = "#{@base_url}/applications/#{@application_id}/guilds/#{guild_id}/commands"
  data = JSON.generate(commands)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  response = DiscordApi.put(url, data, headers)
  return response if response.status == 200

  @logger.error("Failed to bulk overwrite guild application commands in guild with ID #{guild_id}. " \
                  "Response: #{response.body}")
  response
end

#connect_gateway(activities: nil, os: nil, browser: nil, device: nil, intents: nil, presence_since: nil, presence_status: nil, presence_afk: nil) {|event| ... } ⇒ void

This method returns an undefined value.

Connects to the Discord Gateway and identifies/resumes the session. This establishes a WebSocket connection, performs Identify/Resume flows, sends/receives heartbeats, and yields gateway events to the provided block. See discord.com/developers/docs/topics/gateway and discord.com/developers/docs/topics/gateway#identify and discord.com/developers/docs/topics/gateway#resume

Yields:

  • (event)

    Yields parsed Gateway events to the block if provided.



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
199
200
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/disrb.rb', line 159

def connect_gateway(activities: nil, os: nil, browser: nil, device: nil, intents: nil, presence_since: nil,
                    presence_status: nil, presence_afk: nil, &block)
  if @authorization_token_type == 'Bearer'
    acceptable_activities_keys = %w[name type url created_at timestamps application_id details state emoji party
                                    assets secrets instance flags buttons]
  elsif @authorization_token_type == 'Bot'
    acceptable_activities_keys = %w[name state type url]
  end
  if activities.is_a?(Hash)
    activities.each_key do |key|
      next if acceptable_activities_keys.include?(key.to_s)

      @logger.error("Unknown activity key: #{key}. Deleting key from hash.")
      activities.delete(key)
    end
    if activities.empty?
      @logger.error('Empty activity hash. No activities will be sent.')
      activities = nil
    else
      activities = [activities]
    end
  elsif activities.is_a?(Array)
    activities.each do |activity|
      if activity.is_a?(Hash)
        activity.each_key do |key|
          next if acceptable_activities_keys.include?(key.to_s)

          @logger.error("Unknown activity key: #{key}. Deleting key from Hash.")
          activity.delete(key)
        end
        if activity.empty?
          @logger.error('Empty activity hash. Deleting from Array.')
          activities.delete(activity)
        end
      else
        @logger.error("Invalid activity: #{activity}. Expected a Hash. Deleting from Array.")
        activities.delete(activity)
      end
    end
    if activities.empty?
      @logger.error('Empty activities Array. No activities will be sent.')
      activities = nil
    end
  elsif !activities.nil?
    @logger.error("Invalid activities: #{activities}. Expected a Hash or an Array of Hashes.")
    activities = nil
  end
  unless os.is_a?(String) || os.nil?
    @logger.error("Invalid OS: #{os}. Expected a String. Defaulting to #{RbConfig::CONFIG['host_os']}.")
    os = nil
  end
  unless browser.is_a?(String) || browser.nil?
    @logger.error("Invalid browser: #{browser}. Expected a String. Defaulting to 'discord.rb'.")
    browser = nil
  end
  unless device.is_a?(String) || device.nil?
    @logger.error("Invalid device: #{device}. Expected a String. Defaulting to 'discord.rb'.")
    device = nil
  end
  unless (intents.is_a?(Integer) && intents >= 0 && intents <= 131_071) || intents.nil?
    @logger.error("Invalid intents: #{intents}. Expected an Integer between 0 and 131.071. Defaulting to 513" \
                  ' (GUILD_MESSAGES, GUILDS).')
    intents = nil
  end
  unless presence_since.is_a?(Integer) || presence_since == true || presence_since.nil?
    @logger.error("Invalid presence since: #{presence_since}. Expected an Integer or true. Defaulting to nil.")
    presence_since = nil
  end
  unless presence_status.is_a?(String) || presence_status.nil?
    @logger.error("Invalid presence status: #{presence_status}. Expected a String. Defaulting to nil.")
    presence_status = nil
  end
  unless [true, false].include?(presence_afk) || presence_afk.nil?
    @logger.error("Invalid presence afk: #{presence_afk}. Expected a Boolean. Defaulting to nil.")
    presence_afk = nil
  end
  Async do |_task|
    rescue_connection, sequence, resume_gateway_url, session_id = nil
    loop do
      recieved_ready = false
      url = if rescue_connection.nil?
              response = DiscordApi.get("#{@base_url}/gateway")
              if response.status == 200
                "#{JSON.parse(response.body)['url']}/?v=#{@api_version}&encoding=json"
              else
                @logger.fatal_error("Failed to get gateway URL. Response: #{response.body}")
                exit
              end
            else
              "#{rescue_connection[:resume_gateway_url]}/?v=#{@api_version}&encoding=json"
            end
      endpoint = Async::HTTP::Endpoint.parse(url, alpn_protocols: Async::HTTP::Protocol::HTTP11.names)
      Async::WebSocket::Client.connect(endpoint) do |connection|
        if rescue_connection.nil?
          identify = {}
          identify[:op] = 2
          identify[:d] = {}
          identify[:d][:token] = @authorization_header
          identify[:d][:intents] = intents || 513
          identify[:d][:properties] = {}
          identify[:d][:properties][:os] = os || RbConfig::CONFIG['host_os']
          identify[:d][:properties][:browser] = browser || 'discord.rb'
          identify[:d][:properties][:device] = device || 'discord.rb'
          if !activities.nil? || !presence_since.nil? || !presence_status.nil? || !presence_afk.nil?
            identify[:d][:presence] = {}
            identify[:d][:presence][:activities] = activities unless activities.nil?
            if presence_since == true
              identify[:d][:presence][:since] = (Time.now.to_f * 1000).floor
            elsif presence_since.is_a?(Integer)
              identify[:d][:presence][:since] = presence_since
            end
            identify[:d][:presence][:status] = presence_status unless presence_status.nil?
            identify[:d][:presence][:afk] = presence_afk unless presence_afk.nil?
          end
          @logger.debug("Identify payload: #{JSON.generate(identify)}")
          connection.write(JSON.generate(identify))
        else
          @logger.info('Resuming connection...')
          resume = {}
          resume[:op] = 6
          resume[:d] = {}
          resume[:d][:token] = @authorization_header
          resume[:d][:session_id] = rescue_connection[:session_id]
          resume[:d][:seq] = rescue_connection[:sequence]
          @logger.debug("Resume payload: #{JSON.generate(resume)}")
          connection.write(JSON.generate(resume))
          rescue_connection, sequence, resume_gateway_url, session_id = nil
        end
        connection.flush

        loop do
          message = connection.read
          next if message.nil?

          @logger.debug("Raw gateway message: #{message.buffer}")
          message = JSON.parse(message, symbolize_names: true)
          @logger.debug("JSON parsed gateway message: #{message}")

          block.call(message)
          case message
          in { op: 10 }
            @logger.info('Received Hello')
            @heartbeat_interval = message[:d][:heartbeat_interval]
          in { op: 1 }
            @logger.info('Received Heartbeat Request')
            connection.write JSON.generate({ op: 1, d: nil })
            connection.flush
          in { op: 11 }
            @logger.info('Received Heartbeat ACK')
          in { op: 0, t: 'READY' }
            @logger.info('Recieved Ready')
            session_id = message[:d][:session_id]
            resume_gateway_url = message[:d][:resume_gateway_url]
            sequence = message[:s]
            recieved_ready = true
          in { op: 0 }
            @logger.info('An event was dispatched')
            sequence = message[:s]
          in { op: 7 }
            if recieved_ready
              rescue_connection = { session_id: session_id, resume_gateway_url: resume_gateway_url,
                                    sequence: sequence }
              @logger.warn('Received Reconnect. A rescue will be attempted....')
            else
              @logger.warn('Received Reconnect. A rescue cannot be attempted.')
            end
          in { op: 9 }
            if message[:d] && recieved_ready
              rescue_connection = { session_id: session_id, resume_gateway_url: resume_gateway_url,
                                    sequence: sequence }
              @logger.warn('Recieved Invalid Session. A rescue will be attempted...')
            else
              @logger.warn('Recieved Invalid Session. A rescue cannot be attempted.')
            end
          else
            @logger.error("Unimplemented event type with opcode #{message[:op]}")
          end
        end
      end
    rescue Protocol::WebSocket::ClosedError
      @logger.warn('WebSocket connection closed. Attempting reconnect and rescue.')
      if rescue_connection
        @logger.info('Rescue possible. Reconnecting and rescuing...')
      else
        @logger.info('Rescue not possible. Reconnecting...')
      end
      next
    end
  end
end

#create_dm(recipient_id) ⇒ Faraday::Response

Creates a DM channel with the specified user. Returns a DM channel object (if one already exists, it will return that channel). See discord.com/developers/docs/resources/user#create-dm



123
124
125
126
127
128
129
130
131
132
# File 'lib/disrb/user.rb', line 123

def create_dm(recipient_id)
  url = "#{@base_url}/users/@me/channels"
  data = JSON.generate({ recipient_id: recipient_id })
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  response = DiscordApi.post(url, data, headers)
  return response if response.status == 200

  @logger.error("Failed to create DM with recipient ID #{recipient_id}. Response: #{response.body}")
  response
end

#create_global_application_command(name, description, name_localizations: nil, description_localizations: nil, options: nil, default_member_permissions: nil, dm_permission: nil, default_permission: nil, integration_types: nil, contexts: nil, type: nil, nsfw: nil) ⇒ Faraday::Response



88
89
90
91
92
93
94
95
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
# File 'lib/disrb/application_commands.rb', line 88

def create_global_application_command(name, description, name_localizations: nil,
                                      description_localizations: nil, options: nil,
                                      default_member_permissions: nil, dm_permission: nil, default_permission: nil,
                                      integration_types: nil, contexts: nil, type: nil, nsfw: nil)
  output = {}
  output[:name] = name
  output[:description] = description
  output[:name_localizations] = name_localizations unless name_localizations.nil?
  output[:description_localizations] = description_localizations unless description_localizations.nil?
  output[:options] = options unless options.nil?
  output[:type] = type unless type.nil?
  output[:nsfw] = nsfw unless nsfw.nil?
  output[:default_member_permissions] = default_member_permissions unless default_member_permissions.nil?
  unless dm_permission.nil?
    @logger.warn('The "dm_permission" parameter has been deprecated and "contexts" should be used instead!')
    output[:dm_permission] = dm_permission
  end
  unless default_permission.nil?
    @logger.warn('The "default_permission" parameter has been replaced by "default_member_permissions" ' \
                   'and will be deprecated in the future.')
    output[:default_permission] = default_permission
  end
  output[:integration_types] = integration_types unless integration_types.nil?
  output[:contexts] = contexts unless contexts.nil?
  url = "#{@base_url}/applications/#{@application_id}/commands"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  response = DiscordApi.post(url, data, headers)
  return response if response.status == 201 || response.status == 200

  @logger.error("Failed to create global application command. Response: #{response.body}")
  response
end

#create_global_application_commands(application_commands_array) ⇒ Array

Mass-creates application commands globally.



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/disrb/application_commands.rb', line 129

def create_global_application_commands(application_commands_array)
  response = []
  if application_commands_array.is_a?(Array)
    application_commands_array.each do |parameter_array|
      if parameter_array.is_a?(Array)
        response << create_global_application_command(*parameter_array[0..1], **parameter_array[2] || {})
      else
        @logger.error("Invalid parameter array: #{parameter_array}. Expected an array of parameters.")
      end
    end
  else
    @logger.error("Invalid application commands array: #{application_commands_array}. Expected an array of arrays.")
  end
  response
end

#create_group_dm(access_tokens, nicks) ⇒ Faraday::Response

Creates a group DM channel with the specified users. Returns a group DM channel object. See discord.com/developers/docs/resources/user#create-group-dm



140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/disrb/user.rb', line 140

def create_group_dm(access_tokens, nicks)
  output = {}
  output[:access_tokens] = access_tokens
  output[:nicks] = nicks
  url = "#{@base_url}/users/@me/channels"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  response = DiscordApi.post(url, data, headers)
  return response if response.status == 200

  @logger.error("Failed to create group DM. Response: #{response.body}")
  response
end

#create_guild_application_command(guild_id, name, description, name_localizations: nil, description_localizations: nil, options: nil, default_member_permissions: nil, default_permission: nil, type: nil, nsfw: nil) ⇒ Faraday::Response

Creates an application command specifically for one guild. See discord.com/developers/docs/interactions/application-commands#create-guild-application-command



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/disrb/application_commands.rb', line 20

def create_guild_application_command(guild_id, name, description, name_localizations: nil,
                                     description_localizations: nil, options: nil, default_member_permissions: nil,
                                     default_permission: nil, type: nil, nsfw: nil)
  output = {}
  output[:name] = name
  output[:description] = description
  output[:name_localizations] = name_localizations unless name_localizations.nil?
  output[:description_localizations] = description_localizations unless description_localizations.nil?
  output[:options] = options unless options.nil?
  unless default_permission.nil?
    @logger.warn('The "default_permission" parameter has been replaced by "default_member_permissions" ' \
                   'and will be deprecated in the future.')
    output[:default_permission] = default_permission
  end
  output[:type] = type unless type.nil?
  output[:nsfw] = nsfw unless nsfw.nil?
  output[:default_member_permissions] = default_member_permissions unless default_member_permissions.nil?
  url = "#{@base_url}/applications/#{@application_id}/guilds/#{guild_id}/commands"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  response = DiscordApi.post(url, data, headers)
  return response if response.status == 201 || response.status == 200

  @logger.error("Failed to create guild application command in guild with ID #{guild_id}. Response: #{response.body}")
  response
end

#create_guild_application_commands(application_commands_array) ⇒ Array

Mass-creates application commands for guild(s).



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

def create_guild_application_commands(application_commands_array)
  response = []
  if application_commands_array.is_a?(Array)
    application_commands_array.each do |parameter_array|
      if parameter_array.is_a?(Array)
        response << create_guild_application_command(*parameter_array[0..2], **parameter_array[3] || {})
      else
        @logger.error("Invalid parameter array: #{parameter_array}. Expected an array of parameters.")
      end
    end
  else
    @logger.error("Invalid application commands array: #{application_commands_array}. Expected an array of arrays.")
  end
  response
end

#create_guild_ban(guild_id, user_id, delete_message_days: nil, delete_message_seconds: nil, audit_reason: nil) ⇒ Faraday::Response

Bans the specified user from the specified guild. Returns 204 No Content on success. See discord.com/developers/docs/resources/guild#create-guild-ban



578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
# File 'lib/disrb/guild.rb', line 578

def create_guild_ban(guild_id, user_id, delete_message_days: nil, delete_message_seconds: nil, audit_reason: nil)
  output = {}
  unless delete_message_days.nil?
    @logger.warn('The "delete_message_days" parameter has been deprecated and should not be used!')
    output[:delete_message_days] = delete_message_days
  end
  output[:delete_message_seconds] = delete_message_seconds unless delete_message_seconds.nil?
  url = "#{@base_url}/guilds/#{guild_id}/bans/#{user_id}"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.put(url, data, headers)
  return response if response.status == 204

  @logger.error("Could not create guild ban for user with ID #{user_id} in guild with ID #{guild_id}." \
                 " Response: #{response.body}")
  response
end

#create_guild_channel(guild_id, name, type: nil, topic: nil, bitrate: nil, user_limit: nil, rate_limit_per_user: nil, position: nil, permission_overwrites: nil, parent_id: nil, nsfw: nil, rtc_region: nil, video_quality_mode: nil, default_auto_archive_duration: nil, default_reaction_emoji: nil, available_tags: nil, default_sort_order: nil, default_forum_layout: nil, default_thread_rate_limit_per_user: nil, audit_reason: nil) ⇒ Faraday::Response

Creates a new channel in the specified guild. Returns the created channel object. See discord.com/developers/docs/resources/guild#create-guild-channel



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
199
200
201
202
203
204
205
206
207
# File 'lib/disrb/guild.rb', line 166

def create_guild_channel(guild_id, name, type: nil, topic: nil, bitrate: nil, user_limit: nil,
                         rate_limit_per_user: nil, position: nil, permission_overwrites: nil, parent_id: nil,
                         nsfw: nil, rtc_region: nil, video_quality_mode: nil, default_auto_archive_duration: nil,
                         default_reaction_emoji: nil, available_tags: nil, default_sort_order: nil,
                         default_forum_layout: nil, default_thread_rate_limit_per_user: nil, audit_reason: nil)
  output = {}
  output[:name] = name
  output[:type] = type unless type.nil?
  output[:topic] = topic unless topic.nil?
  output[:bitrate] = bitrate unless bitrate.nil?
  output[:user_limit] = user_limit unless user_limit.nil?
  output[:rate_limit_per_user] = rate_limit_per_user unless rate_limit_per_user.nil?
  output[:position] = position unless position.nil?
  output[:permission_overwrites] = permission_overwrites unless permission_overwrites.nil?
  output[:parent_id] = parent_id unless parent_id.nil?
  output[:nsfw] = nsfw unless nsfw.nil?
  unless rtc_region.nil?
    output[:rtc_region] = if rtc_region == 'auto'
                            nil
                          else
                            rtc_region
                          end
  end
  output[:video_quality_mode] = video_quality_mode unless video_quality_mode.nil?
  output[:default_auto_archive_duration] = default_auto_archive_duration unless default_auto_archive_duration.nil?
  output[:default_reaction_emoji] = default_reaction_emoji unless default_reaction_emoji.nil?
  output[:available_tags] = available_tags unless available_tags.nil?
  output[:default_sort_order] = default_sort_order unless default_sort_order.nil?
  output[:default_forum_layout] = default_forum_layout unless default_forum_layout.nil?
  unless default_thread_rate_limit_per_user.nil?
    output[:default_thread_rate_limit_per_user] = default_thread_rate_limit_per_user
  end
  url = "#{@base_url}/guilds/#{guild_id}/channels"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.post(url, data, headers)
  return response if response.status == 200

  @logger.error("Could not create guild channel in Guild ID #{guild_id}. Response: #{response.body}")
  response
end

#create_guild_role(guild_id, name: nil, permissions: nil, color: nil, colors: nil, hoist: nil, icon: nil, unicode_emoji: nil, mentionable: nil, audit_reason: nil) ⇒ Faraday::Response

Creates a new role in the specified guild. Returns 200 OK with the new role object. See discord.com/developers/docs/resources/guild#create-guild-role



686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
# File 'lib/disrb/guild.rb', line 686

def create_guild_role(guild_id, name: nil, permissions: nil, color: nil, colors: nil, hoist: nil, icon: nil,
                      unicode_emoji: nil, mentionable: nil, audit_reason: nil)
  output = {}
  output[:name] = name unless name.nil?
  output[:permissions] = permissions unless permissions.nil?
  unless color.nil?
    @logger.warn('The "color" parameter has been deprecated and should not be used!')
    output[:color] = color
  end
  output[:colors] = colors unless colors.nil?
  output[:hoist] = hoist unless hoist.nil?
  output[:icon] = icon unless icon.nil?
  output[:unicode_emoji] = unicode_emoji unless unicode_emoji.nil?
  output[:mentionable] = mentionable unless mentionable.nil?
  url = "#{@base_url}/guilds/#{guild_id}/roles"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.post(url, data, headers)
  return response if response.status == 200

  @logger.error("Could not create guild role in guild with ID #{guild_id}. Response: #{response.body}")
  response
end

#create_message(channel_id, content: nil, nonce: nil, tts: nil, embeds: nil, allowed_mentions: nil, message_reference: nil, components: nil, sticker_ids: nil, _files: nil, attachments: nil, flags: nil, enforce_nonce: nil, poll: nil) ⇒ Faraday::Response?

Creates a message in a channel. Returns the created message object on success. See discord.com/developers/docs/resources/message#create-message One of content, embeds, sticker_ids, components or poll must be provided. If none of these are provided, the function will log a warning (depends on the verbosity level set) and return nil



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/disrb/message.rb', line 83

def create_message(channel_id, content: nil, nonce: nil, tts: nil, embeds: nil, allowed_mentions: nil,
                   message_reference: nil, components: nil, sticker_ids: nil, _files: nil, attachments: nil,
                   flags: nil, enforce_nonce: nil, poll: nil)
  if content.nil? && embeds.nil? && sticker_ids.nil? && components.nil? && poll.nil?
    @logger.warn('No content, embeds, sticker_ids, components or poll provided. Skipping function.')
    return
  end
  output = {}
  output[:content] = content unless content.nil?
  output[:nonce] = nonce unless nonce.nil?
  output[:tts] = tts unless tts.nil?
  output[:embeds] = embeds unless embeds.nil?
  output[:allowed_mentions] = allowed_mentions unless allowed_mentions.nil?
  output[:message_reference] = message_reference unless message_reference.nil?
  output[:components] = components unless components.nil?
  output[:sticker_ids] = sticker_ids unless sticker_ids.nil?
  # output[:files] = files unless files.nil?
  output[:attachments] = attachments unless attachments.nil?
  output[:flags] = flags unless flags.nil?
  output[:enforce_nonce] = enforce_nonce unless enforce_nonce.nil?
  output[:poll] = poll unless poll.nil?
  url = "#{@base_url}/channels/#{channel_id}/messages"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  response = DiscordApi.post(url, data, headers)
  return response if response.status == 200

  @logger.error("Failed to create message in channel #{channel_id}. Response: #{response.body}")
  response
end

#create_reaction(channel_id, message_id, emoji) ⇒ Faraday::Response

Create a reaction for the specified message. Returns no content on success. See discord.com/developers/docs/resources/message#create-reaction



136
137
138
139
140
141
142
143
144
145
# File 'lib/disrb/message.rb', line 136

def create_reaction(channel_id, message_id, emoji)
  url = "#{@base_url}/channels/#{channel_id}/messages/#{message_id}/reactions/#{emoji}/@me"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.put(url, nil, headers)
  return response if response.status == 204

  @logger.error("Failed to create reaction with emoji ID #{emoji} in channel with ID #{channel_id} " \
                  "for message with ID #{message_id}. Response: #{response.body}")
  response
end

#crosspost_message(channel_id, message_id) ⇒ Faraday::Response

Crossposts a message in an Announcement Channel to all following channels. Returns the crossposted message object on success. See discord.com/developers/docs/resources/message#crosspost-message



119
120
121
122
123
124
125
126
127
128
# File 'lib/disrb/message.rb', line 119

def crosspost_message(channel_id, message_id)
  url = "#{@base_url}/channels/#{channel_id}/messages/#{message_id}/crosspost"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.post(url, nil, headers)
  return response if response.status == 200

  @logger.error("Failed to crosspost message with ID #{message_id} in channel with ID #{channel_id}. " \
                  "Response: #{response.body}")
  response
end

#delete_all_reactions(channel_id, message_id) ⇒ Faraday::Response

Deletes all reactions on a message. Returns no content on success. See discord.com/developers/docs/resources/message#delete-all-reactions



212
213
214
215
216
217
218
219
220
# File 'lib/disrb/message.rb', line 212

def delete_all_reactions(channel_id, message_id)
  url = "#{@base_url}/channels/#{channel_id}/messages/#{message_id}/reactions"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.delete(url, headers)
  return response if response.status == 204

  @logger.error("Failed to delete all reactions in channel with ID #{channel_id} for message with ID #{message_id}" \
                  ". Response: #{response.body}")
end

#delete_all_reactions_for_emoji(channel_id, message_id, emoji) ⇒ Faraday::Response

Deletes all reactions with the specified emoji on a message. Returns no content on success. See discord.com/developers/docs/resources/message#delete-all-reactions-for-emoji



228
229
230
231
232
233
234
235
236
# File 'lib/disrb/message.rb', line 228

def delete_all_reactions_for_emoji(channel_id, message_id, emoji)
  url = "#{@base_url}/channels/#{channel_id}/messages/#{message_id}/reactions/#{emoji}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.delete(url, headers)
  return response if response.status == 204

  @logger.error("Failed to delete all reactions for emoji with ID #{emoji} in channel with ID #{channel_id} for " \
                  "message with ID #{message_id}. Response: #{response.body}")
end

#delete_global_application_command(command_id) ⇒ Faraday::Response

Deletes a global application command. Returns 204 No Content on success. See discord.com/developers/docs/interactions/application-commands#delete-global-application-command



232
233
234
235
236
237
238
239
240
# File 'lib/disrb/application_commands.rb', line 232

def delete_global_application_command(command_id)
  url = "#{@base_url}/applications/#{@application_id}/commands/#{command_id}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.delete(url, headers)
  return response if response.status == 204

  @logger.error("Failed to delete global application command with ID #{command_id}. Response: #{response.body}")
  response
end

#delete_guild(guild_id) ⇒ Object



116
117
118
119
120
121
122
123
124
# File 'lib/disrb/guild.rb', line 116

def delete_guild(guild_id)
  url = "#{@base_url}/guilds/#{guild_id}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.delete(url, headers)
  return response if response.status == 204

  @logger.error("Could not delete guild with Guild ID #{guild_id}. Response: #{response.body}")
  response
end

#delete_guild_application_command(guild_id, command_id) ⇒ Faraday::Response

Deletes a guild application command. Returns 204 No Content on success. See discord.com/developers/docs/interactions/application-commands#delete-guild-application-command



247
248
249
250
251
252
253
254
255
# File 'lib/disrb/application_commands.rb', line 247

def delete_guild_application_command(guild_id, command_id)
  url = "#{@base_url}/applications/#{@application_id}/guilds/#{guild_id}/commands/#{command_id}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.delete(url, headers)
  return response if response.status == 204

  @logger.error("Failed to delete guild application command with ID #{command_id} in guild with ID #{guild_id}. " \
                "Response: #{response.body}")
end

#delete_guild_integration(guild_id, integration_id, audit_reason = nil) ⇒ Faraday::Response

Deletes a guild integration. Returns 204 No Content on success. See discord.com/developers/docs/resources/guild#delete-guild-integration



924
925
926
927
928
929
930
931
932
933
# File 'lib/disrb/guild.rb', line 924

def delete_guild_integration(guild_id, integration_id, audit_reason = nil)
  url = "#{@base_url}/guilds/#{guild_id}/integrations/#{integration_id}"
  headers = { 'Authorization': @authorization_header }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.delete(url, headers)
  return response if response.status == 204

  @logger.error("Failed to delete guild integration. Response: #{response.body}")
  response
end

#delete_guild_role(guild_id, role_id, audit_reason = nil) ⇒ Faraday::Response

Deletes a guild role. Returns 204 No Content on success. See discord.com/developers/docs/resources/guild#delete-guild-role



806
807
808
809
810
811
812
813
814
815
# File 'lib/disrb/guild.rb', line 806

def delete_guild_role(guild_id, role_id, audit_reason = nil)
  url = "#{@base_url}/guilds/#{guild_id}/roles/#{role_id}"
  headers = { 'Authorization': @authorization_header }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.delete(url, headers)
  return response if response.status == 204

  @logger.error("Failed to delete guild role. Response: #{response.body}")
  response
end

#delete_message(channel_id, message_id, audit_reason = nil) ⇒ Faraday::Response

Deletes a message. Returns no content on success. See discord.com/developers/docs/resources/message#delete-message



287
288
289
290
291
292
293
294
295
296
297
# File 'lib/disrb/message.rb', line 287

def delete_message(channel_id, message_id, audit_reason = nil)
  url = "#{@base_url}/channels/#{channel_id}/messages/#{message_id}"
  headers = { 'Authorization': @authorization_header }
  headers[:'X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.delete(url, headers)
  return response if response.status == 204

  @logger.error("Failed to delete message with ID #{message_id} in channel with ID #{channel_id}. " \
                  "Response: #{response.body}")
  response
end

#delete_own_reaction(channel_id, message_id, emoji) ⇒ Faraday::Response

Deletes a reaction with the specified emoji for the current user in the specified message. Returns no content on success. See discord.com/developers/docs/resources/message#delete-own-reaction



153
154
155
156
157
158
159
160
161
162
# File 'lib/disrb/message.rb', line 153

def delete_own_reaction(channel_id, message_id, emoji)
  url = "#{@base_url}/channels/#{channel_id}/messages/#{message_id}/reactions/#{emoji}/@me"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.delete(url, headers)
  return response if response.status == 204

  @logger.error("Failed to delete own reaction with emoji ID #{emoji} in channel with ID #{channel_id} " \
                  "for message with ID #{message_id}. Response: #{response.body}")
  response
end

#delete_user_reaction(channel_id, message_id, emoji, user_id) ⇒ Faraday::Response

Deletes a reaction with the specified emoji for a user in the specified message. Returns no content on success. See discord.com/developers/docs/resources/message#delete-user-reaction



171
172
173
174
175
176
177
178
179
180
# File 'lib/disrb/message.rb', line 171

def delete_user_reaction(channel_id, message_id, emoji, user_id)
  url = "#{@base_url}/channels/#{channel_id}/messages/#{message_id}/reactions/#{emoji}/#{user_id}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.delete(url, headers)
  return response if response.status == 204

  @logger.error("Failed to delete user reaction with emoji ID #{emoji} in channel with ID #{channel_id} " \
                  "for message with ID #{message_id} by user with ID #{user_id}. Response: #{response.body}")
  response
end

#edit_application_command_permissions(guild_id, command_id, permissions) ⇒ Faraday::Response

Edits command permissions for a specific guild command. Returns 200 OK with the updated permissions. See discord.com/developers/docs/interactions/application-commands#edit-application-command-permissions



390
391
392
393
394
395
396
397
398
399
400
# File 'lib/disrb/application_commands.rb', line 390

def edit_application_command_permissions(guild_id, command_id, permissions)
  url = "#{@base_url}/applications/#{@application_id}/guilds/#{guild_id}/commands/#{command_id}/permissions"
  data = JSON.generate(permissions)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  response = DiscordApi.put(url, data, headers)
  return response if response.status == 200

  @logger.error("Failed to edit application command permissions for command with ID #{command_id} in guild with ID " \
                  "#{guild_id}. Response: #{response.body}")
  response
end

#edit_global_application_command(command_id, name: nil, name_localizations: nil, description: nil, description_localizations: nil, options: nil, default_member_permissions: nil, default_permission: nil, integration_types: nil, contexts: nil, nsfw: nil) ⇒ Faraday::Response?

Edits a global application command. Returns 200 OK with the updated command object on success. If none of the optional parameters are specified (modifications), the function logs a warning and returns nil. See discord.com/developers/docs/interactions/application-commands#edit-global-application-command



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
# File 'lib/disrb/application_commands.rb', line 160

def edit_global_application_command(command_id, name: nil, name_localizations: nil, description: nil,
                                    description_localizations: nil, options: nil, default_member_permissions: nil,
                                    default_permission: nil, integration_types: nil, contexts: nil, nsfw: nil)
  if args[1..].all?(&:nil?)
    @logger.warn("No modifications provided for global application command with ID #{command_id}. Skipping.")
    return nil
  end
  output = {}
  output[:name] = name
  output[:name_localizations] = name_localizations unless name_localizations.nil?
  output[:description] = description unless description.nil?
  output[:description_localizations] = description_localizations unless description_localizations.nil?
  output[:options] = options unless options.nil?
  output[:default_permission] = default_permission unless default_permission.nil?
  output[:nsfw] = nsfw unless nsfw.nil?
  output[:default_member_permissions] = default_member_permissions unless default_member_permissions.nil?
  output[:integration_types] = integration_types unless integration_types.nil?
  output[:contexts] = contexts unless contexts.nil?
  url = "#{@base_url}/applications/#{@application_id}/commands/#{command_id}"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  response = DiscordApi.patch(url, data, headers)
  return response if response.status == 200

  @logger.error("Failed to edit global application command with ID #{command_id}. Response: #{response.body}")
  response
end

#edit_guild_application_command(guild_id, command_id, name: nil, name_localizations: nil, description: nil, description_localizations: nil, options: nil, default_member_permissions: nil, default_permission: nil, nsfw: nil) ⇒ Faraday::Response?

Edits a guild application command. Returns 200 OK with the updated command object on success. If none of the optional parameters are specified (modifications), the function logs a warning and returns nil. See discord.com/developers/docs/interactions/application-commands#edit-guild-application-command



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
# File 'lib/disrb/application_commands.rb', line 202

def edit_guild_application_command(guild_id, command_id, name: nil, name_localizations: nil, description: nil,
                                   description_localizations: nil, options: nil, default_member_permissions: nil,
                                   default_permission: nil, nsfw: nil)
  if args[2..].all?(&:nil?)
    @logger.warn("No modifications provided for guild application command with command ID #{command_id}. Skipping.")
    return nil
  end
  output = {}
  output[:name] = name
  output[:name_localizations] = name_localizations unless name_localizations.nil?
  output[:description] = description unless description.nil?
  output[:description_localizations] = description_localizations unless description_localizations.nil?
  output[:options] = options unless options.nil?
  output[:default_permission] = default_permission unless default_permission.nil?
  output[:nsfw] = nsfw unless nsfw.nil?
  output[:default_member_permissions] = default_member_permissions unless default_member_permissions.nil?
  url = "#{@base_url}/applications/#{@application_id}/guilds/#{guild_id}/commands/#{command_id}"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  response = DiscordApi.patch(url, data, headers)
  return response if response.status == 200

  @logger.error("Failed to edit guild application command with ID #{command_id}. Response: #{response.body}")
  response
end

#edit_message(channel_id, message_id, content: nil, embeds: nil, flags: nil, allowed_mentions: nil, components: nil, files: nil, attachments: nil) ⇒ Faraday::Response?

Edits a message. Returns the edited message object on success. See discord.com/developers/docs/resources/message#edit-message

If none of the optional parameters are provided (modifications), the function will not proceed and return nil. Since the files parameter is WIP, providing only files will also cause the function to not proceed.



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/disrb/message.rb', line 255

def edit_message(channel_id, message_id, content: nil, embeds: nil, flags: nil, allowed_mentions: nil,
                 components: nil, files: nil, attachments: nil)
  if args[2..].all?(&:nil?) || (args[2..].delete(:files).all?(&:nil?) && !files.nil?)
    @logger.warn("No modifications provided for message with ID #{message_id} in channel with ID #{channel_id}. " \
                   'The files parameter is WIP. Skipping function.')
    return
  end
  output = {}
  output[:content] = content unless content.nil?
  output[:embeds] = embeds unless embeds.nil?
  output[:flags] = flags unless flags.nil?
  output[:allowed_mentions] = allowed_mentions unless allowed_mentions.nil?
  output[:components] = components unless components.nil?
  # output[:files] = files unless files.nil?
  output[:attachments] = attachments unless attachments.nil?
  url = "#{@base_url}/channels/#{channel_id}/messages/#{message_id}"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  response = DiscordApi.patch(url, data, headers)
  return response if response.status == 200

  @logger.error("Failed to edit message with ID #{message_id} in channel with ID #{channel_id}. " \
                  "Response: #{response.body}")
  response
end

#get_application_command_permissions(guild_id, command_id) ⇒ Faraday::Response

Returns command permissions for a specific guild command. Returns 200 OK with the permission object. See discord.com/developers/docs/interactions/application-commands#get-application-command-permissions



373
374
375
376
377
378
379
380
381
382
# File 'lib/disrb/application_commands.rb', line 373

def get_application_command_permissions(guild_id, command_id)
  url = "#{@base_url}/applications/#{@application_id}/guilds/#{guild_id}/commands/#{command_id}/permissions"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get appliaction command permissions for command with ID #{command_id} in guild with ID " \
                  "#{guild_id}. Response: #{response.body}")
  response
end

#get_channel_message(channel_id, message_id) ⇒ Faraday::Response

Gets a specific message from a channel. Returns a message object on success. See discord.com/developers/docs/resources/message#get-channel-message



48
49
50
51
52
53
54
55
56
57
# File 'lib/disrb/message.rb', line 48

def get_channel_message(channel_id, message_id)
  url = "#{@base_url}/channels/#{channel_id}/messages/#{message_id}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get message with ID #{message_id} from channel with ID #{channel_id}. " \
                  "Response: #{response.body}")
  response
end

#get_channel_messages(channel_id, around: nil, before: nil, after: nil, limit: nil) ⇒ Faraday::Response

Gets the messages in a channel. Returns an array of message objects from newest to oldest on success. See discord.com/developers/docs/resources/message#get-channel-messages

The before, after, and around parameters are mutually exclusive. Only one of them can be specified. If more than one of these are specified, all of these will be set to nil and an error will be logged (depends on the verbosity level set).



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/disrb/message.rb', line 17

def get_channel_messages(channel_id, around: nil, before: nil, after: nil, limit: nil)
  options = { around: around, before: before, after: after }
  specified_keys = options.reject { |_k, v| v.nil? }.keys

  if specified_keys.size > 1
    @logger.error('You can only specify one of around, before or after. Setting all to nil.')
    around, before, after = nil
  elsif specified_keys.size == 1
    instance_variable_set("@#{specified_keys.first}", options[specified_keys.first])
  end

  query_string_hash = {}
  query_string_hash[:around] = around unless around.nil?
  query_string_hash[:before] = before unless before.nil?
  query_string_hash[:after] = after unless after.nil?
  query_string_hash[:limit] = limit unless limit.nil?
  query_string = DiscordApi.handle_query_strings(query_string_hash)
  url = "#{@base_url}/channels/#{channel_id}/messages#{query_string}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get messages from channel with ID #{channel_id}. Response: #{response.body}")
  response
end

#get_channel_pins(channel_id, before: nil, limit: nil) ⇒ Faraday::Response

Gets pinned messages in a channel. See discord.com/developers/docs/resources/message#get-channel-pins for

more info and response structure.


324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/disrb/message.rb', line 324

def get_channel_pins(channel_id, before: nil, limit: nil)
  query_string_hash = {}
  query_string_hash[:before] = before unless before.nil?
  query_string_hash[:limit] = limit unless limit.nil?
  query_string = DiscordApi.handle_query_strings(query_string_hash)
  url = "#{@base_url}/channels/#{channel_id}/messages/pins#{query_string}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get pinned messages in channel with ID #{channel_id}. Response: #{response.body}")
  response
end

#get_current_userFaraday::Response

Returns the user object of the current user. See discord.com/developers/docs/resources/user#get-current-user



9
10
11
12
13
14
15
16
17
# File 'lib/disrb/user.rb', line 9

def get_current_user
  url = "#{@base_url}/users/@me"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get current user. Response: #{response.body}")
  response
end

#get_current_user_application_role_connection(application_id) ⇒ Faraday::Response

Returns the application role connection object for the user. Requires the role_connections.write OAuth2 scope for the application specified. See discord.com/developers/docs/resources/user#get-current-user-application-role-connection



172
173
174
175
176
177
178
179
180
181
# File 'lib/disrb/user.rb', line 172

def get_current_user_application_role_connection(application_id)
  url = "#{@base_url}/users/@me/applications/#{application_id}/role-connection"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get current user's application role connection for application ID #{application_id}. " \
                "Response: #{response.body}")
  response
end

#get_current_user_connectionsFaraday::Response

Returns an array of connection objects for the current user. Requires the connections OAuth2 scope. See discord.com/developers/docs/resources/user#get-current-user-connections



157
158
159
160
161
162
163
164
165
# File 'lib/disrb/user.rb', line 157

def get_current_user_connections
  url = "#{@base_url}/users/@me/connections"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get current user's connections. Response: #{response.body}")
  response
end

#get_current_user_guild_member(guild_id) ⇒ Faraday::Response

Returns a guild member object for the current user in the specified guild. See discord.com/developers/docs/resources/user#get-current-user-guild-member



92
93
94
95
96
97
98
99
100
101
# File 'lib/disrb/user.rb', line 92

def get_current_user_guild_member(guild_id)
  url = "#{@base_url}/users/@me/guilds/#{guild_id}/member"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response unless response.status != 200

  @logger.error("Failed to get current user's guild member for guild ID with ID #{guild_id}. Response: " \
                  "#{response.body}")
  response
end

#get_current_user_guilds(before: nil, after: nil, limit: nil, with_counts: nil) ⇒ Faraday::Response

Returns an array of (partial) guild objects that the current user is a member of. See discord.com/developers/docs/resources/user#get-current-user-guilds



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/disrb/user.rb', line 67

def get_current_user_guilds(before: nil, after: nil, limit: nil, with_counts: nil)
  query_string_hash = {}
  query_string_hash[:before] = before unless before.nil?
  query_string_hash[:after] = after unless after.nil?
  query_string_hash[:limit] = limit unless limit.nil?
  query_string_hash[:with_counts] = with_counts unless with_counts.nil?
  query_string = DiscordApi.handle_query_strings(query_string_hash)
  url = "#{@base_url}/users/@me/guilds#{query_string}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  if response.status == 200 && @authorization_token_type == 'Bot' && JSON.parse(response.body).count == 200
    @logger.warn('A bot can be in more than 200 guilds, however 200 guilds were returned.' \
                  'Discord API doesn\'t allow you to fetch more than 200 guilds. Some guilds might not be listed.')
    return response
  end
  return response if response.status == 200

  @logger.error("Failed to get current user's guilds. Response: #{response.body}")
  response
end

#get_global_application_command(command_id) ⇒ Faraday::Response

Returns a single global application command by ID. Returns 200 OK with the command object. See discord.com/developers/docs/interactions/application-commands#get-global-application-command



296
297
298
299
300
301
302
303
304
# File 'lib/disrb/application_commands.rb', line 296

def get_global_application_command(command_id)
  url = "#{@base_url}/applications/#{@application_id}/commands/#{command_id}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get global application command with ID #{command_id}. Response: #{response.body}")
  response
end

#get_global_application_commands(with_localizations: false) ⇒ Faraday::Response

Returns a list of global application commands for the current application. Returns 200 OK on success. See discord.com/developers/docs/interactions/application-commands#get-global-application-commands



279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/disrb/application_commands.rb', line 279

def get_global_application_commands(with_localizations: false)
  query_string_hash = {}
  query_string_hash[:with_localizations] = with_localizations unless with_localizations.nil?
  query_string = DiscordApi.handle_query_strings(query_string_hash)
  url = "#{@base_url}/applications/#{@application_id}/commands#{query_string}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get global application commands. Response: #{response.body}")
  response
end

#get_guild(guild_id, with_counts = nil) ⇒ Faraday::Response

Gets a guild object with the specified guild ID. See discord.com/developers/docs/resources/guild#get-guild



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/disrb/guild.rb', line 9

def get_guild(guild_id, with_counts = nil)
  query_string_hash = {}
  query_string_hash[:with_counts] = with_counts unless with_counts.nil?
  query_string = DiscordApi.handle_query_strings(query_string_hash)
  url = "#{@base_url}/guilds/#{guild_id}#{query_string}"
  headers = { 'Authorization' => @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Could not get guild with Guild ID #{guild_id}. Response: #{response.body}")
  response
end

#get_guild_application_command(guild_id, command_id) ⇒ Faraday::Response

Returns a single guild application command by ID. Returns 200 OK with the command object. See discord.com/developers/docs/interactions/application-commands#get-guild-application-command



311
312
313
314
315
316
317
318
319
# File 'lib/disrb/application_commands.rb', line 311

def get_guild_application_command(guild_id, command_id)
  url = "#{@base_url}/applications/#{@application_id}/guilds/#{guild_id}/commands/#{command_id}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get guild application command with ID #{command_id}. Response: #{response.body}")
  response
end

#get_guild_application_command_permissions(guild_id) ⇒ Faraday::Response

Returns all application command permissions for a guild. Returns 200 OK with an array of permissions. See discord.com/developers/docs/interactions/application-commands#get-guild-application-command-permissions



357
358
359
360
361
362
363
364
365
366
# File 'lib/disrb/application_commands.rb', line 357

def get_guild_application_command_permissions(guild_id)
  url = "#{@base_url}/applications/#{@application_id}/guilds/#{guild_id}/commands/permissions"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get guild application command permissions for guild with ID #{guild_id}. " \
                  "Response: #{response.body}")
  response
end

#get_guild_application_commands(guild_id, with_localizations: nil) ⇒ Faraday::Response

Returns a list of application commands for a guild. Returns 200 OK with an array of command objects. See discord.com/developers/docs/interactions/application-commands#get-guild-application-commands



262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/disrb/application_commands.rb', line 262

def get_guild_application_commands(guild_id, with_localizations: nil)
  query_string_hash = {}
  query_string_hash[:with_localizations] = with_localizations unless with_localizations.nil?
  query_string = DiscordApi.handle_query_strings(query_string_hash)
  url = "#{@base_url}/applications/#{@application_id}/guilds/#{guild_id}/commands#{query_string}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get guild application commands for guild with ID #{guild_id}. Response: #{response.body}")
  response
end

#get_guild_ban(guild_id, user_id) ⇒ Faraday::Response

Returns a ban object for the specified user in the specified guild. Returns 404 Not Found if the user is not banned. See discord.com/developers/docs/resources/guild#get-guild-ban



554
555
556
557
558
559
560
561
562
563
564
565
566
567
# File 'lib/disrb/guild.rb', line 554

def get_guild_ban(guild_id, user_id)
  url = "#{@base_url}/guilds/#{guild_id}/bans/#{user_id}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  if response.status == 404
    @logger.warn("No ban found for user with ID #{user_id} in guild with ID #{guild_id}.")
  else
    @logger.error("Could not get guild ban for user with ID #{user_id} in guild with ID #{guild_id}." \
                   " Response: #{response.body}")
  end
  response
end

#get_guild_bans(guild_id, limit: nil, before: nil, after: nil) ⇒ Faraday::Response

Returns a list of ban objects for users banned from the specified guild. See discord.com/developers/docs/resources/guild#get-guild-bans



534
535
536
537
538
539
540
541
542
543
544
545
546
547
# File 'lib/disrb/guild.rb', line 534

def get_guild_bans(guild_id, limit: nil, before: nil, after: nil)
  query_string_hash = {}
  query_string_hash[:limit] = limit unless limit.nil?
  query_string_hash[:before] = before unless before.nil?
  query_string_hash[:after] = after unless after.nil?
  query_string = DiscordApi.handle_query_strings(query_string_hash)
  url = "#{@base_url}/guilds/#{guild_id}/bans#{query_string}"
  headers = { 'Authorization' => @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Could not get guild bans with Guild ID #{guild_id}. Response: #{response.body}")
  response
end

#get_guild_channels(guild_id) ⇒ Faraday::Response

Returns a list of guild channel objects for every channel in the specified guild. Doesn’t include threads. See discord.com/developers/docs/resources/guild#get-guild-channels



130
131
132
133
134
135
136
137
138
# File 'lib/disrb/guild.rb', line 130

def get_guild_channels(guild_id)
  url = "#{@base_url}/guilds/#{guild_id}/channels"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Could not get guild channels with Guild ID #{guild_id}. Response: #{response.body}")
  response
end

#get_guild_integrations(guild_id) ⇒ Faraday::Response

Returns a list of integration objects for the specified guild with status code 200 OK on success. See discord.com/developers/docs/resources/guild#get-guild-integrations



903
904
905
906
907
908
909
910
911
912
913
914
915
916
# File 'lib/disrb/guild.rb', line 903

def get_guild_integrations(guild_id)
  url = "#{@base_url}/guilds/#{guild_id}/integrations"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  if response.status == 200
    if JSON.parse(response.body).length == 50
      @logger.warn('The endpoint returned 50 integrations, which means there could be more integrations not shown.')
    end
    return response
  end

  @logger.error("Failed to get guild integrations. Response: #{response.body}")
  response
end

#get_guild_invites(guild_id) ⇒ Faraday::Response

Returns a list of invite objects for the specified guild with status code 200 OK on success. See discord.com/developers/docs/resources/guild#get-guild-invites



889
890
891
892
893
894
895
896
897
# File 'lib/disrb/guild.rb', line 889

def get_guild_invites(guild_id)
  url = "#{@base_url}/guilds/#{guild_id}/invites"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get guild invites. Response: #{response.body}")
  response
end

#get_guild_member(guild_id, user_id) ⇒ Faraday::Response

Returns a guild member object for the specified user in the specified guild. See discord.com/developers/docs/resources/guild#get-guild-member



283
284
285
286
287
288
289
290
291
292
# File 'lib/disrb/guild.rb', line 283

def get_guild_member(guild_id, user_id)
  url = "#{@base_url}/guilds/#{guild_id}/members/#{user_id}"
  headers = { 'Authorization' => @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Could not get guild member with Guild ID #{guild_id} and User ID #{user_id}. Response:" \
                 "#{response.body}")
  response
end

#get_guild_onboarding(guild_id) ⇒ Faraday::Response

Returns the onboarding object for the specified guild. See discord.com/developers/docs/resources/guild#get-guild-onboarding



1088
1089
1090
1091
1092
1093
1094
1095
1096
# File 'lib/disrb/guild.rb', line 1088

def get_guild_onboarding(guild_id)
  url = "#{@base_url}/guilds/#{guild_id}/onboarding"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get guild onboarding. Response: #{response.body}")
  response
end

#get_guild_preview(guild_id) ⇒ Faraday::Response

Gets the guild preview object for the specified guild ID. See discord.com/developers/docs/resources/guild#get-guild-preview



26
27
28
29
30
31
32
33
34
# File 'lib/disrb/guild.rb', line 26

def get_guild_preview(guild_id)
  url = URI("#{@base_url}/guilds/#{guild_id}/preview")
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Could not get guild preview with Guild ID #{guild_id}. Response: #{response.body}")
  response
end

#get_guild_prune_count(guild_id, days: nil, include_roles: nil) ⇒ Faraday::Response

Returns a JSON object with a ‘pruned’ key indicating the number of members that would be removed in a prune operation with status code 200 OK. See discord.com/developers/docs/resources/guild#get-guild-prune-count



824
825
826
827
828
829
830
831
832
833
834
835
836
# File 'lib/disrb/guild.rb', line 824

def get_guild_prune_count(guild_id, days: nil, include_roles: nil)
  query_string_hash = {}
  query_string_hash[:days] = days unless days.nil?
  query_string_hash[:include_roles] = include_roles unless include_roles.nil?
  query_string = DiscordApi.handle_query_strings(query_string_hash)
  url = "#{@base_url}/guilds/#{guild_id}/prune#{query_string}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get guild prune count. Response: #{response.body}")
  response
end

#get_guild_role(guild_id, role_id) ⇒ Faraday::Response

Returns the role object for the specified role in the specified guild. See discord.com/developers/docs/resources/guild#get-guild-role



661
662
663
664
665
666
667
668
669
# File 'lib/disrb/guild.rb', line 661

def get_guild_role(guild_id, role_id)
  url = "#{@base_url}/guilds/#{guild_id}/roles/#{role_id}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Could not get role with ID #{role_id} in guild with ID #{guild_id}. Response: #{response.body}")
  response
end

#get_guild_roles(guild_id) ⇒ Faraday::Response

Returns a list of role objects for the specified guild. See discord.com/developers/docs/resources/guild#get-guild-roles



646
647
648
649
650
651
652
653
654
# File 'lib/disrb/guild.rb', line 646

def get_guild_roles(guild_id)
  url = "#{@base_url}/guilds/#{guild_id}/roles"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Could not get guild roles with Guild ID #{guild_id}. Response: #{response.body}")
  response
end

#get_guild_vanity_url(guild_id) ⇒ Faraday::Response

Returns a partial invite object for guilds with that feature enabled with status code 200 OK on success. See discord.com/developers/docs/resources/guild#get-guild-vanity-url



990
991
992
993
994
995
996
997
998
# File 'lib/disrb/guild.rb', line 990

def get_guild_vanity_url(guild_id)
  url = "#{@base_url}/guilds/#{guild_id}/vanity-url"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get guild vanity URL. Response: #{response.body}")
  response
end

#get_guild_voice_regions(guild_id) ⇒ Faraday::Response

Returns a list of voice region objects for the specified guild with status code 200 OK on success. See discord.com/developers/docs/resources/guild#get-guild-voice-regions



875
876
877
878
879
880
881
882
883
# File 'lib/disrb/guild.rb', line 875

def get_guild_voice_regions(guild_id)
  url = "#{@base_url}/guilds/#{guild_id}/regions"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get guild voice regions. Response: #{response.body}")
  response
end

#get_guild_welcome_screen(guild_id) ⇒ Faraday::Response

Returns the welcome screen object for the specified guild. See discord.com/developers/docs/resources/guild#get-guild-welcome-screen



1041
1042
1043
1044
1045
1046
1047
1048
1049
# File 'lib/disrb/guild.rb', line 1041

def get_guild_welcome_screen(guild_id)
  url = "#{@base_url}/guilds/#{guild_id}/welcome-screen"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get guild welcome screen. Response: #{response.body}")
  response
end

#get_guild_widget(guild_id) ⇒ Faraday::Response

Returns the widget object for the specified guild with status code 200 OK on success. See discord.com/developers/docs/resources/guild#get-guild-widget



976
977
978
979
980
981
982
983
984
# File 'lib/disrb/guild.rb', line 976

def get_guild_widget(guild_id)
  url = "#{@base_url}/guilds/#{guild_id}/widget.json"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get guild widget. Response: #{response.body}")
  response
end

#get_guild_widget_image(guild_id, shield: false, banner1: false, banner2: false, banner3: false, banner4: false) ⇒ Faraday::Response?

Returns the widget image (PNG) for the specified guild. Only one of the style convenience booleans (shield, banner1, banner2, banner3, banner4) can be true; if more than one is specified the function logs an error and returns nil. If none are true, the default style is used (shield). See discord.com/developers/docs/resources/guild#get-guild-widget-image



1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
# File 'lib/disrb/guild.rb', line 1012

def get_guild_widget_image(guild_id, shield: false, banner1: false, banner2: false, banner3: false, banner4: false)
  options = { shield: shield, banner1: banner1, banner2: banner2, banner3: banner3, banner4: banner4 }
  true_keys = options.select { |_k, v| v }.keys

  if true_keys.size > 1
    @logger.error('You can only specify one of shield, banner1, banner2, banner3, or banner4 as true.')
    nil
  elsif true_keys.size == 1
    style = true_keys.first.to_s
  else
    style = nil
  end

  query_string_hash = {}
  query_string_hash[:style] = style unless style.nil?
  query_string = DiscordApi.handle_query_strings(query_string_hash)

  url = "#{@base_url}/guilds/#{guild_id}/widget.png#{query_string}"
  response = DiscordApi.get(url)
  return unless response.status != 200

  @logger.error("Failed to get guild widget image. Response: #{response.body}")
  response
end

#get_guild_widget_settings(guild_id) ⇒ Faraday::Response

Returns the guild widget settings object for the specified guild with status code 200 OK on success. See discord.com/developers/docs/resources/guild#get-guild-widget-settings



939
940
941
942
943
944
945
946
947
# File 'lib/disrb/guild.rb', line 939

def get_guild_widget_settings(guild_id)
  url = "#{@base_url}/guilds/#{guild_id}/widget"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get guild widget settings. Response: #{response.body}")
  response
end

#get_reactions(channel_id, message_id, emoji, type: nil, after: nil, limit: nil) ⇒ Faraday::Response

Gets a list of users that reacted with the specified emoji to the specified message. Returns an array of user objects on success. See discord.com/developers/docs/resources/message#get-reactions



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/disrb/message.rb', line 191

def get_reactions(channel_id, message_id, emoji, type: nil, after: nil, limit: nil)
  query_string_hash = {}
  query_string_hash[:type] = type unless type.nil?
  query_string_hash[:after] = after unless after.nil?
  query_string_hash[:limit] = limit unless limit.nil?
  query_string = DiscordApi.handle_query_strings(query_string_hash)
  url = "#{@base_url}/channels/#{channel_id}/messages/#{message_id}/reactions/#{emoji}#{query_string}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get reactions for emoji with ID #{emoji} in channel with ID #{channel_id} " \
                  "for message with ID #{message_id}. Response: #{response.body}")
  response
end

#get_user(user_id) ⇒ Faraday::Response

Returns the user object of the specified user. See discord.com/developers/docs/resources/user#get-user



22
23
24
25
26
27
28
29
30
# File 'lib/disrb/user.rb', line 22

def get_user(user_id)
  url = "#{@base_url}/users/#{user_id}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Failed to get user with ID #{user_id}. Response: #{response.body}")
  response
end

#leave_guild(guild_id) ⇒ Faraday::Response

Leaves a guild for the current user. If it succeeds, the response will have a status code of 204 (Empty Response), and thus the response body will be empty. See discord.com/developers/docs/resources/user#leave-guild



108
109
110
111
112
113
114
115
116
# File 'lib/disrb/user.rb', line 108

def leave_guild(guild_id)
  url = "#{@base_url}/users/@me/guilds/#{guild_id}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.delete(url, headers)
  return response if response.status == 204

  @logger.error("Failed to leave guild with ID #{guild_id}. Response: #{response.body}")
  response
end

#list_active_guild_threads(guild_id) ⇒ Faraday::Response

Returns a list of active threads in the specified guild.See discord.com/developers/docs/resources/guild#list-active-guild-threads



269
270
271
272
273
274
275
276
277
# File 'lib/disrb/guild.rb', line 269

def list_active_guild_threads(guild_id)
  url = "#{@base_url}/guilds/#{guild_id}/threads/active"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Could not list active guild threads with Guild ID #{guild_id}. Response: #{response.body}")
  response
end

#list_guild_members(guild_id, limit: nil, after: nil) ⇒ Faraday::Response

Returns an array of guild member objects for the specified guild. See discord.com/developers/docs/resources/guild#list-guild-members



299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/disrb/guild.rb', line 299

def list_guild_members(guild_id, limit: nil, after: nil)
  query_string_hash = {}
  query_string_hash[:limit] = limit unless limit.nil?
  query_string_hash[:after] = after unless after.nil?
  query_string = DiscordApi.handle_query_strings(query_string_hash)
  url = "#{@base_url}/guilds/#{guild_id}/members#{query_string}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Could not list members with Guild ID #{guild_id}. Response: #{response.body}")
  response
end

#modify_current_member(guild_id, nick: nil, banner: nil, avatar: nil, bio: nil, audit_reason: nil) ⇒ Faraday::Response?

Modifies the current member in the specified guild. Returns 200 OK with the new Guild Member object. See discord.com/developers/docs/resources/guild#modify-current-member

If none of the optional parameters are provided (member modifications), the function will log a warning, no request will be made to Discord, and the function will return nil. (note that audit_reason doesn’t count)



429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/disrb/guild.rb', line 429

def modify_current_member(guild_id, nick: nil, banner: nil, avatar: nil, bio: nil, audit_reason: nil)
  output = {}
  output[:nick] = nick unless nick.nil?
  output[:banner] = banner unless banner.nil?
  output[:avatar] = avatar unless avatar.nil?
  output[:bio] = bio unless bio.nil?
  url = "#{@base_url}/guilds/#{guild_id}/members/@me"
  data = JSON.generate(output)
  if data.empty?
    @logger.warn("No modifications for current member in guild ID #{guild_id} provided. Skipping.")
    return nil
  end
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.patch(url, data, headers)
  return response if response.status == 200

  @logger.error("Could not modify current member in guild with Guild ID #{guild_id}. Response: #{response.body}")
  response
end

#modify_current_user(username: nil, avatar: nil, banner: nil) ⇒ Faraday::Response?

Modifies the current user. See discord.com/developers/docs/resources/user#modify-current-user

If none of the parameters are provided, the function will not proceed and return nil.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/disrb/user.rb', line 40

def modify_current_user(username: nil, avatar: nil, banner: nil)
  output = {}
  output[:username] = username unless username.nil?
  output[:avatar] = avatar unless avatar.nil?
  output[:banner] = banner unless banner.nil?
  if output.empty?
    @logger.warn('No current user modifications provided. Skipping function.')
    return
  end
  url = "#{@base_url}/users/@me"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  response = DiscordApi.patch(url, data, headers)
  return response if response.status == 200

  @logger.error("Failed to modify current user. Response: #{response.body}")
  response
end

#modify_current_user_nick(guild_id, nick, audit_reason: nil) ⇒ Faraday::Response

THIS ENDPOINT HAS BEEN DEPRECATED AND SHOULD NOT BE USED, PLEASE USE #modify_current_member INSTEAD! Modifies the current user’s nickname in the specified guild. Returns 200 OK with the new nickname. See discord.com/developers/docs/resources/guild#modify-current-user-nick



457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/disrb/guild.rb', line 457

def modify_current_user_nick(guild_id, nick, audit_reason: nil)
  @logger.warn('The "Modify Current User Nick" endpoint has been deprecated and should not be used!')
  output = {}
  output[:nick] = nick unless nick.nil?
  url = "#{@base_url}/guilds/#{guild_id}/users/@me/nick"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.patch(url, data, headers)
  return response if response.status == 200

  @logger.error("Could not modify current user nick in guild with ID #{guild_id}. Response: #{response.body}")
  response
end

#modify_guild(guild_id, name: nil, region: nil, verification_level: nil, default_message_notifications: nil, explicit_content_filter: nil, afk_channel_id: nil, afk_timeout: nil, icon: nil, owner_id: nil, splash: nil, discovery_splash: nil, banner: nil, system_channel_id: nil, system_channel_flags: nil, rules_channel_id: nil, public_updates_channel_id: nil, preferred_locale: nil, features: nil, description: nil, premium_progress_bar_enabled: nil, safety_alerts_channel_id: nil, audit_reason: nil) ⇒ Faraday::Response?

Modifies a guild with the specified guild ID. See discord.com/developers/docs/resources/guild#modify-guild

If none of the optional parameters are provided (guild modifications), the function will log a warning and return nil.



70
71
72
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
105
106
107
108
109
110
111
112
113
114
# File 'lib/disrb/guild.rb', line 70

def modify_guild(guild_id, name: nil, region: nil, verification_level: nil, default_message_notifications: nil,
                 explicit_content_filter: nil, afk_channel_id: nil, afk_timeout: nil, icon: nil, owner_id: nil,
                 splash: nil, discovery_splash: nil, banner: nil, system_channel_id: nil,
                 system_channel_flags: nil, rules_channel_id: nil, public_updates_channel_id: nil,
                 preferred_locale: nil, features: nil, description: nil, premium_progress_bar_enabled: nil,
                 safety_alerts_channel_id: nil, audit_reason: nil)
  if args[1..-2].all?(&:nil?)
    @logger.warn("No modifications for guild with ID #{guild_id} provided. Skipping.")
    return nil
  end
  output = {}
  output[:name] = name unless name.nil?
  unless region.nil?
    @logger.warn('The "region" parameter has been deprecated and should not be used!')
    output[:region] = region
  end
  output[:verification_level] = verification_level unless verification_level.nil?
  output[:default_message_notifications] = default_message_notifications unless default_message_notifications.nil?
  output[:explicit_content_filter] = explicit_content_filter unless explicit_content_filter.nil?
  output[:afk_channel_id] = afk_channel_id unless afk_channel_id.nil?
  output[:afk_timeout] = afk_timeout unless afk_timeout.nil?
  output[:icon] = icon unless icon.nil?
  output[:owner_id] = owner_id unless owner_id.nil?
  output[:splash] = splash unless splash.nil?
  output[:discovery_splash] = discovery_splash unless discovery_splash.nil?
  output[:banner] = banner unless banner.nil?
  output[:system_channel_id] = system_channel_id unless system_channel_id.nil?
  output[:system_channel_flags] = system_channel_flags unless system_channel_flags.nil?
  output[:rules_channel_id] = rules_channel_id unless rules_channel_id.nil?
  output[:public_updates_channel_id] = public_updates_channel_id unless public_updates_channel_id.nil?
  output[:preferred_locale] = preferred_locale unless preferred_locale.nil?
  output[:features] = features unless features.nil?
  output[:description] = description unless description.nil?
  output[:premium_progress_bar_enabled] = premium_progress_bar_enabled unless premium_progress_bar_enabled.nil?
  output[:safety_alerts_channel_id] = safety_alerts_channel_id unless safety_alerts_channel_id.nil?
  url = "#{@base_url}/guilds/#{guild_id}"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.patch(url, headers, data)
  return response if response.status == 200

  @logger.error("Could not modify guild with Guild ID #{guild_id}. Response: #{response.body}")
  response
end

#modify_guild_channel_positions(guild_id, data) ⇒ Faraday::Response?

Modify the positions of a set of channel objects for the guild. Returns 204 No Content on success. See discord.com/developers/docs/resources/guild#modify-guild-channel-positions



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/disrb/guild.rb', line 230

def modify_guild_channel_positions(guild_id, data)
  output = []
  data.each do |channel_id, modification|
    channel_modification = {}
    channel_modification[:id] = channel_id
    channel_modification[:position] = modification[:position] if modification.include?(:position)
    channel_modification[:lock_permissions] = modification[:lock_permissions] if modification
                                                                                 .include?(:lock_permissions)
    channel_modification[:parent_id] = modification[:parent_id] if modification.include?(:parent_id)
    if (channel_modification.keys - i[id lock_permissions position]).empty? &&
       !channel_modification.key?(:parent_id)
      @logger.warn('lock_permissions has been specified, but parent_id hasn\'t. Dropping lock_permissions from ' \
                     'data.')
      channel_modification.delete(:lock_permissions)
    end
    if channel_modification.empty?
      @logger.warn("No channel position modifications provided for channel with ID #{channel_id}. Skipping channel" \
                   ' position modification.')
    else
      output << channel_modification
    end
  end
  if output.empty?
    @logger.warn("No channel position modifications provided for guild with ID #{guild_id}. Skipping function.")
    return nil
  end
  url = "#{@base_url}/guilds/#{guild_id}/channels"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  response = DiscordApi.patch(url, headers, data)
  return response if response.status == 200

  @logger.error("Could not modify guild channel positions with Guild ID #{guild_id}. Response: #{response.body}")
  response
end

#modify_guild_incident_actions(guild_id, invites_disabled_until: nil, dms_disabled_until: nil) ⇒ Faraday::Response?

Modifies the incident actions for a guild (e.g. temporarily disabling invites or direct messages). If none of the optional parameters are specified (modifications), the function logs a warning and returns nil. See discord.com/developers/docs/resources/guild#modify-guild-incident-actions



1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
# File 'lib/disrb/guild.rb', line 1143

def modify_guild_incident_actions(guild_id, invites_disabled_until: nil, dms_disabled_until: nil)
  if args[1..].all?(&:nil?)
    @logger.warn("No modifications for guild incident actions with guild ID #{guild_id} provided. " \
                   'Skipping.')
    return nil
  end
  output = {}
  if invites_disabled_until == false
    output[:invites_disabled_until] = nil
  elsif !invites_disabled_until.nil?
    output[:invites_disabled_until] = invites_disabled_until
  end
  if dms_disabled_until == false
    output[:dms_disabled_until] = nil
  elsif !dms_disabled_until.nil?
    output[:dms_disabled_until] = dms_disabled_until
  end
  url = "#{@base_url}/guilds/#{guild_id}/incident-actions"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  response = DiscordApi.put(url, data, headers)
  return response if response.status == 200

  @logger.error("Failed to modify guild incident actions. Response: #{response.body}")
  response
end

#modify_guild_member(guild_id, user_id, nick: nil, roles: nil, mute: nil, deaf: nil, channel_id: nil, communication_disabled_until: nil, flags: nil, audit_reason: nil) ⇒ Faraday::Response?

Modifies a user in the specified guild. Returns 200 OK with the new Guild Member object. See discord.com/developers/docs/resources/guild#modify-guild-member

If none of the optional parameters are provided (member modifications), the function will log a warning, no request

will be made to Discord, and the function will return nil. (note that audit_reason doesn't count)


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
411
412
# File 'lib/disrb/guild.rb', line 383

def modify_guild_member(guild_id, user_id, nick: nil, roles: nil, mute: nil, deaf: nil, channel_id: nil,
                        communication_disabled_until: nil, flags: nil, audit_reason: nil)
  if args[2..-2].all?(&:nil?)
    @logger.warn("No modifications for guild member with guild ID #{guild_id} and user ID #{user_id} provided. " \
                   'Skipping.')
    return nil
  end
  output = {}
  output[:nick] = nick unless nick.nil?
  output[:roles] = roles unless roles.nil?
  output[:mute] = mute unless mute.nil?
  output[:deaf] = deaf unless deaf.nil?
  output[:channel_id] = channel_id unless channel_id.nil?
  if communication_disabled_until == false
    output[:communication_disabled_until] = nil
  elsif !communication_disabled_until.nil?
    output[:communication_disabled_until] = communication_disabled_until
  end
  output[:flags] = flags unless flags.nil?
  url = "#{@base_url}/guilds/#{guild_id}/members/#{user_id}"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.patch(url, data, headers)
  return response if response.status == 200

  @logger.error("Could not modify guild member with Guild ID #{guild_id} and User ID #{user_id}. " \
  "Response: #{response.body}")
  response
end

#modify_guild_mfa_level(guild_id, level, audit_reason = nil) ⇒ Faraday::Response

Modifies the MFA level required for a guild. Returns 200 OK on success.



786
787
788
789
790
791
792
793
794
795
796
797
798
# File 'lib/disrb/guild.rb', line 786

def modify_guild_mfa_level(guild_id, level, audit_reason = nil)
  output = {}
  output[:level] = level
  url = "#{@base_url}/guilds/#{guild_id}/mfa"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.post(url, data, headers)
  return unless response.status != 200

  @logger.error("Failed to modify guild MFA level. Response: #{response.body}")
  response
end

#modify_guild_onboarding(guild_id, prompts: nil, default_channel_ids: nil, enabled: nil, mode: nil, audit_reason: nil) ⇒ Faraday::Response?

Modifies the onboarding configuration for the specified guild. Returns the updated onboarding object on success. If none of the optional parameters are specified (modifications, except audit_reason), the function logs a warning and returns nil. See discord.com/developers/docs/resources/guild#modify-guild-onboarding



1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
# File 'lib/disrb/guild.rb', line 1110

def modify_guild_onboarding(guild_id, prompts: nil, default_channel_ids: nil, enabled: nil, mode: nil,
                            audit_reason: nil)
  if args[1..-2].all?(&:nil?)
    @logger.warn("No modifications for guild onboarding with guild ID #{guild_id} provided. " \
                   'Skipping.')
    return nil
  end
  output = {}
  output[:prompts] = prompts unless prompts.nil?
  output[:default_channel_ids] = default_channel_ids unless default_channel_ids.nil?
  output[:enabled] = enabled unless enabled.nil?
  output[:mode] = mode unless mode.nil?
  url = "#{@base_url}/guilds/#{guild_id}/onboarding"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.put(url, data, headers)
  return response if response.status == 200

  @logger.error("Failed to modify guild onboarding. Response: #{response.body}")
  response
end

#modify_guild_role(guild_id, role_id, name: nil, permissions: nil, color: nil, hoist: nil, icon: nil, unicode_emoji: nil, mentionable: nil, audit_reason: nil) ⇒ Faraday::Response?

Modifies a guild role. Returns 200 OK with the modified role object, or nil if no modifications were provided. See discord.com/developers/docs/resources/guild#modify-guild-role



753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
# File 'lib/disrb/guild.rb', line 753

def modify_guild_role(guild_id, role_id, name: nil, permissions: nil, color: nil, hoist: nil, icon: nil,
                      unicode_emoji: nil, mentionable: nil, audit_reason: nil)
  if args[2..-2].all?(&:nil?)
    @logger.warn("No modifications for guild role with ID #{role_id} in guild with ID #{guild_id} provided. " \
                   'Skipping.')
    return nil
  end
  output = {}
  output[:name] = name unless name.nil?
  output[:permissions] = permissions unless permissions.nil?
  output[:color] = color unless color.nil?
  output[:hoist] = hoist unless hoist.nil?
  output[:icon] = icon unless icon.nil?
  output[:unicode_emoji] = unicode_emoji unless unicode_emoji.nil?
  output[:mentionable] = mentionable unless mentionable.nil?
  url = "#{@base_url}/guilds/#{guild_id}/roles/#{role_id}"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.patch(url, data, headers)
  return response if response.status == 200

  @logger.error("Could not modify guild role with ID #{role_id} in guild with ID #{guild_id}." \
               " Response: #{response.body}")
  response
end

#modify_guild_role_positions(guild_id, role_positions, audit_reason: nil) ⇒ Faraday::Response?

Modifies the position of a set of role objects in the specified guild. Returns 200 OK with an array of all of the modified role objects on success. See discord.com/developers/docs/resources/guild#modify-guild-role-positions



722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
# File 'lib/disrb/guild.rb', line 722

def modify_guild_role_positions(guild_id, role_positions, audit_reason: nil)
  if role_positions.empty?
    @logger.warn("No role positions provided for guild with ID #{guild_id}. Skipping function.")
    return nil
  end
  url = "#{@base_url}/guilds/#{guild_id}/roles"
  data = JSON.generate(role_positions)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.patch(url, data, headers)
  return response if response.status == 200

  @logger.error("Could not modify guild role positions in guild with ID #{guild_id}. Response: #{response.body}")
  response
end

#modify_guild_welcome_screen(guild_id, enabled: nil, welcome_channels: nil, description: nil, audit_reason: nil) ⇒ Faraday::Response?

Modifies the welcome screen for the specified guild. Returns the updated welcome screen object on success. If none of the optional parameters are specified (modifications, except audit_reason), the function logs a warning and returns nil. See discord.com/developers/docs/resources/guild#modify-guild-welcome-screen



1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
# File 'lib/disrb/guild.rb', line 1062

def modify_guild_welcome_screen(guild_id, enabled: nil, welcome_channels: nil, description: nil,
                                audit_reason: nil)
  if args[1..-2].all?(&:nil?)
    @logger.warn("No modifications for guild welcome screen with guild ID #{guild_id} provided. " \
                   'Skipping.')
    return nil
  end
  output = {}
  output[:enabled] = enabled unless enabled.nil?
  output[:welcome_channels] = welcome_channels unless welcome_channels.nil?
  output[:description] = description unless description.nil?
  url = "#{@base_url}/guilds/#{guild_id}/welcome-screen"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.patch(url, data, headers)
  return response if response.status == 200

  @logger.error("Failed to modify guild welcome screen. Response: #{response.body}")
  response
end

#modify_guild_widget(guild_id, enabled, channel_id, audit_reason: nil) ⇒ Faraday::Response

Modifies the guild widget settings for the specified guild. Returns the updated guild widget settings object with status code 200 OK on success. See discord.com/developers/docs/resources/guild#modify-guild-widget



957
958
959
960
961
962
963
964
965
966
967
968
969
970
# File 'lib/disrb/guild.rb', line 957

def modify_guild_widget(guild_id, enabled, channel_id, audit_reason: nil)
  output = {}
  output[:enabled] = enabled
  output[:channel_id] = channel_id
  url = "#{@base_url}/guilds/#{guild_id}/widget"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.patch(url, data, headers)
  return response if response.status == 200

  @logger.error("Failed to modify guild widget. Response: #{response.body}")
  response
end

#pin_message(channel_id, message_id, audit_reason = nil) ⇒ Faraday::Response

Pins a message in a channel. Returns no content on success. See discord.com/developers/docs/resources/message#pin-message



344
345
346
347
348
349
350
351
352
353
354
# File 'lib/disrb/message.rb', line 344

def pin_message(channel_id, message_id, audit_reason = nil)
  url = "#{@base_url}/channels/#{channel_id}/messages/pins/#{message_id}"
  headers = { 'Authorization': @authorization_header }
  headers[:'X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.put(url, nil, headers)
  return response if response.status == 204

  @logger.error("Failed to pin message with ID #{message_id} in channel with ID #{channel_id}. " \
                  "Response: #{response.body}")
  response
end

#remove_guild_ban(guild_id, user_id, audit_reason = nil) ⇒ Faraday::Response

Unbans the specified user from the specified guild. Returns 204 No Content on success. See discord.com/developers/docs/resources/guild#remove-guild-ban



603
604
605
606
607
608
609
610
611
612
613
# File 'lib/disrb/guild.rb', line 603

def remove_guild_ban(guild_id, user_id, audit_reason = nil)
  url = "#{@base_url}/guilds/#{guild_id}/bans/#{user_id}"
  headers = { 'Authorization': @authorization_header }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.delete(url, headers)
  return response if response.status == 204

  @logger.error("Could not remove guild ban for user with ID #{user_id} in guild with ID #{guild_id}" \
                " Response: #{response.body}")
  response
end

#remove_guild_member(guild_id, user_id, audit_reason = nil) ⇒ Faraday::Response

Removes a member from a guild. Returns 204 No Content on success. See discord.com/developers/docs/resources/guild#remove-guild-member



516
517
518
519
520
521
522
523
524
525
# File 'lib/disrb/guild.rb', line 516

def remove_guild_member(guild_id, user_id, audit_reason = nil)
  url = "#{@base_url}/guilds/#{guild_id}/members/#{user_id}"
  headers = { 'Authorization' => @authorization_header }
  headers['X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.delete(url, headers)
  return response if response.status == 204

  @logger.error("Could not remove user with ID #{user_id} from guild with ID #{guild_id}. Response: #{response.body}")
  response
end

#remove_guild_member_role(guild_id, user_id, role_id, audit_reason = nil) ⇒ Faraday::Response

Removes a role from a guild member. Returns 204 No Content on success. See discord.com/developers/docs/resources/guild#remove-guild-member-role



498
499
500
501
502
503
504
505
506
507
508
# File 'lib/disrb/guild.rb', line 498

def remove_guild_member_role(guild_id, user_id, role_id, audit_reason = nil)
  url = "#{@base_url}/guilds/#{guild_id}/members/#{user_id}/roles/#{role_id}"
  headers = { 'Authorization': @authorization_header }
  headers['x-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.delete(url, headers)
  return response if response.status == 204

  @logger.error("Could not remove role with ID #{role_id}, from user with ID #{user_id}" \
                " in guild with ID #{guild_id}. Response: #{response.body}")
  response
end

#respond_interaction(interaction, response, with_response: false) ⇒ Faraday::Response

Creates a response to an interaction. Returns 204 No Content by default, or 200 OK with the created message if ‘with_response` is true and the response type expects it. See discord.com/developers/docs/interactions/receiving-and-responding#create-interaction-response



357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/disrb.rb', line 357

def respond_interaction(interaction, response, with_response: false)
  query_string_hash = {}
  query_string_hash[:with_response] = with_response
  query_string = DiscordApi.handle_query_strings(query_string_hash)
  url = "#{@base_url}/interactions/#{interaction[:d][:id]}/#{interaction[:d][:token]}/callback#{query_string}"
  data = JSON.generate(response)
  headers = { 'content-type': 'application/json' }
  response = DiscordApi.post(url, data, headers)
  return response if (response.status == 204 && !with_response) || (response.status == 200 && with_response)

  @logger.error("Failed to respond to interaction. Response: #{response.body}")
  response
end

#search_guild_members(guild_id, query, limit = nil) ⇒ Faraday::Response

Returns an array of guild member objects whose username/nickname match the query. See discord.com/developers/docs/resources/guild#search-guild-members



318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/disrb/guild.rb', line 318

def search_guild_members(guild_id, query, limit = nil)
  query_string_hash = {}
  query_string_hash[:query] = query
  query_string_hash[:limit] = limit unless limit.nil?
  query_string = DiscordApi.handle_query_strings(query_string_hash)
  url = "#{@base_url}/guilds/#{guild_id}/members/search#{query_string}"
  headers = { 'Authorization': @authorization_header }
  response = DiscordApi.get(url, headers)
  return response if response.status == 200

  @logger.error("Could not search members with Guild ID #{guild_id}. Response: #{response.body}")
  response
end

#unpin_message(channel_id, message_id, audit_reason = nil) ⇒ Faraday::Response

Unpins a message in a channel. Returns no content on success. See discord.com/developers/docs/resources/message#unpin-message



362
363
364
365
366
367
368
369
370
371
372
# File 'lib/disrb/message.rb', line 362

def unpin_message(channel_id, message_id, audit_reason = nil)
  url = "#{@base_url}/channels/#{channel_id}/messages/pins/#{message_id}"
  headers = { 'Authorization': @authorization_header }
  headers[:'X-Audit-Log-Reason'] = audit_reason unless audit_reason.nil?
  response = DiscordApi.delete(url, headers)
  return response if response.status == 204

  @logger.error("Failed to unpin message with ID #{message_id} in channel with ID #{channel_id}. " \
                  "Response: #{response.body}")
  response
end

#update_current_user_application_role_connection(application_id, platform_name: nil, platform_username: nil, metadata: nil) ⇒ Faraday::Response?

Updates and returns the application role connection object for the user. Requires the role_connections.write OAuth2 scope for the application specified. See discord.com/developers/docs/resources/user#update-current-user-application-role-connection

If none of the optional parameters are provided (modifications), the function will not proceed and return nil.



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/disrb/user.rb', line 195

def update_current_user_application_role_connection(application_id, platform_name: nil, platform_username: nil,
                                                    metadata: nil)
  output = {}
  output[:platform_name] = platform_name if platform_name
  output[:platform_username] = platform_username if platform_username
  output[:metadata] =  if 
  if output.empty?
    @logger.warn('No current user application role connection modifications provided. Skipping function.')
    return
  end
  url = "#{@base_url}/users/@me/applications/#{application_id}/role-connection"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  response = DiscordApi.put(url, data, headers)
  return response if response.status == 200

  @logger.error("Failed to update current user's application role connection for application ID #{application_id}. " \
                  "Response: #{response.body}")
  response
end