Class: DiscordApi

Inherits:
Object
  • Object
show all
Defined in:
lib/disrb.rb,
lib/version.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.

Constant Summary collapse

VERSION =
'0.1.4.1'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(authorization_token_type, authorization_token, verbosity_level = nil, user_agent = 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

Parameters:

  • authorization_token_type (String)

    The type of authorization token provided by Discord, ‘Bot’ or ‘Bearer’.

  • authorization_token (String)

    The value of the authorization token provided by Discord.

  • verbosity_level (String, Integer, nil) (defaults to: nil)

    The verbosity level of the logger.

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

    When sending a request to Discord’s HTTP API, a valid User-Agent header must be set. By setting this parameter, the value of the User-Agent header sent will be equal to the value of this parameter. Defaults to ‘discord.rb (github.com/hoovad/discord.rb, [discord.rb version])’



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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/disrb.rb', line 79

def initialize(authorization_token_type, authorization_token, verbosity_level = nil, user_agent = 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)
  default_user_agent = "discord.rb (https://github.com/hoovad/discord.rb, #{DiscordApi::VERSION})"
  if user_agent.is_a?(String) && !user_agent.empty?
    @user_agent = user_agent
  elsif user_agent.nil?
    @user_agent = default_user_agent
  else
    @logger.warn("Invalid user_agent parameter. It must be a valid non-empty string. \
                 Defaulting to #{default_user_agent}.")
    @user_agent = default_user_agent
  end
  url = "#{@base_url}/applications/@me"
  headers = { 'Authorization': @authorization_header }
  response = get(url, headers)
  if response.is_a?(Faraday::Response) && response.status == 200
    @application_id = JSON.parse(response.body)['id']
  else
    @logger.fatal_error("Failed to get application ID with response: #{response_error_body(response)}")
    exit
  end
end

Instance Attribute Details

#application_idInteger

Returns the application ID of the bot that has been assigned to the provided authorization token.

Returns:

  • (Integer)

    the application ID of the bot that has been assigned to the provided authorization token.



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

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

#authorization_headerString

Returns the authorization header that is used to authenticate requests to the Discord API.

Returns:

  • (String)

    the authorization header that is used to authenticate requests to the Discord API.



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

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

#base_urlString

Returns the base URL that is used to access the Discord API. ex: “discord.com/api/v10”.

Returns:

  • (String)

    the base URL that is used to access the Discord API. ex: “discord.com/api/v10



61
62
63
# File 'lib/disrb.rb', line 61

def base_url
  @base_url
end

#loggerObject

Returns the value of attribute logger.



61
62
63
# File 'lib/disrb.rb', line 61

def logger
  @logger
end

#user_agentObject

Returns the value of attribute user_agent.



61
62
63
# File 'lib/disrb.rb', line 61

def user_agent
  @user_agent
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



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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
# File 'lib/disrb.rb', line 396

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

Parameters:

  • intents (Array)

    Array of gateway intent names as strings or symbols, case insensitive, use underscores between spaces.

Returns:

  • (Integer)

    Bitwise OR of all intents flags.



480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
# File 'lib/disrb.rb', line 480

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

Parameters:

  • permissions (Array)

    Array of permission names as strings or symbols, case insensitive, use underscores between spaces.

Returns:

  • (Integer)

    Bitwise OR of all permission flags.



456
457
458
459
460
461
# File 'lib/disrb.rb', line 456

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

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

Parameters:

  • query_string_hash (Hash)

    The hash to convert into a query string.

Returns:

  • (String)

    The query string.



144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/disrb.rb', line 144

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

.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

Parameters:

  • permissions_integer (Integer)

    Bitwise permissions integer.

Returns:

  • (Array)

    Array of permission names present (as symbols) in the integer.



467
468
469
470
471
472
473
# File 'lib/disrb.rb', line 467

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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to add the user to

  • user_id (String)

    ID (as a string) of the user to add to the guild

  • access_token (String)

    A valid OAuth2 access token with the guilds.join scope created by the user you want to add to the guild for the bot that is adding the user

  • roles (Array, nil) (defaults to: nil)

    Array of role IDs (as strings) the user will be assigned

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

    String to set the user’s nickname to

  • mute (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether the user is muted in voice channels

  • deaf (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether the user is deafened in voice channels

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/disrb/guild.rb', line 350

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 = put(url, data, headers)
  if response.is_a?(Faraday::Response) && response.status == 204
    @logger.warn("User with ID #{user_id} is already a member of the guild with ID #{guild_id}.")
  elsif response.is_a?(Faraday::Response) && 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_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to add the role to the member in

  • user_id (String)

    ID (as a string) of the user to add the role to

  • role_id (String)

    ID (as a string) of the role to add to the user

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

    Reason for the modification, shows up on the audit log entry.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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 = put(url, nil, headers)
  return response if response.is_a?(Faraday::Response) && 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_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to start the guild prune in

  • days (Integer, nil) (defaults to: nil)

    Number of days to prune for (1-30)

  • compute_prune_count (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether to return the ‘pruned’ key in the response

  • include_roles (Array, nil) (defaults to: nil)

    Array of role IDs (as strings), these roles will also be included in the prune operation

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

    (DEPRECATED, use audit_reason instead) Reason for the prune, shows up on the audit log entry.

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

    Reason for the prune, shows up on the audit log entry.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
# File 'lib/disrb/guild.rb', line 865

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 = post(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to begin guild prune. Response: #{response_error_body(response)}")
  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

Parameters:

  • channel_id (String)

    The ID of the channel the messages are located in

  • messages (Array)

    An array of message IDs (as strings) to delete. (2-100 IDs)

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

    The reason for deleting the messages. Shows up on the audit log.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/disrb/message.rb', line 329

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 = post(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 204

  @logger.error("Failed to bulk delete messages in channel with ID #{channel_id}." \
                " Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to bulk ban users from

  • user_ids (Array)

    Array of user IDs (as strings) to ban from the specified guild (max 200)

  • delete_message_seconds (Integer, nil) (defaults to: nil)

    Number of seconds to delete messages for (0-604800) (604800s=7d)

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

    Reason for the bulk ban, shows up on the audit log entry.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object



634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
# File 'lib/disrb/guild.rb', line 634

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 = post(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  if response.is_a?(Faraday::Response) && response.status == 500_000
    @logger.error("No users were banned in bulk ban in guild with ID #{guild_id}." \
                  " Response: #{response_error_body(response)}")
  else
    @logger.error("Could not bulk ban users in guild with ID #{guild_id}. Response: #{response_error_body(response)}")
  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

Parameters:

  • commands (Array)

    Array of command objects (hashes) to set globally.

Returns:

  • (Faraday::Response)

    The response from the Discord API.



333
334
335
336
337
338
339
340
341
342
# File 'lib/disrb/application_commands.rb', line 333

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 = put(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to bulk overwrite global application commands. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    The ID of the guild to overwrite commands for.

  • commands (Array)

    Array of command objects (hashes) to set for the guild.

Returns:

  • (Faraday::Response)

    The response from the Discord API.



349
350
351
352
353
354
355
356
357
358
359
# File 'lib/disrb/application_commands.rb', line 349

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 = put(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to bulk overwrite guild application commands in guild with ID #{guild_id}. " \
                  "Response: #{response_error_body(response)}")
  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

Parameters:

  • activities (Hash, Array, nil) (defaults to: nil)

    Activity or list of activities to set in presence.

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

    OS name reported to the Gateway. Host OS if nil.

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

    Browser/client name reported to the Gateway. “discord.rb” if nil.

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

    Device name reported to the Gateway. “discord.rb” if nil

  • intents (Integer, nil) (defaults to: nil)

    Bitwise Gateway intents integer.

  • presence_since (Integer, TrueClass, nil) (defaults to: nil)

    Unix ms timestamp or true for since value in presence.

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

    Presence status (e.g., “online”, “idle”, “dnd”).

  • presence_afk (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether the client is AFK.

Yields:

  • (event)

    Yields parsed Gateway events to the block if provided.



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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/disrb.rb', line 175

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 = get("#{@base_url}/gateway")
              if response.is_a?(Faraday::Response) && response.status == 200
                "#{JSON.parse(response.body)['url']}/?v=#{@api_version}&encoding=json"
              else
                @logger.fatal_error("Failed to get gateway URL. Response: #{response_error_body(response)}")
                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

Parameters:

  • recipient_id (String)

    The ID of the user to create a DM channel with.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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 = post(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to create DM with recipient ID #{recipient_id}. Response: #{response_error_body(response)}")
  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

Parameters:

  • name (String)

    The name of the command.

  • description (String)

    The description of the command.

  • name_localizations (Hash, nil) (defaults to: nil)

    Localized names for the command.

  • description_localizations (Hash, nil) (defaults to: nil)

    Localized descriptions for the command.

  • options (Array, nil) (defaults to: nil)

    Options for the command.

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

    Sets the default permission(s) that members need to run the command. (must be set to a bitwise permission flag as a string)

  • dm_permission (TrueClass, FalseClass, nil) (defaults to: nil)

    (deprecated, use contexts instead) Whether the command is available in DMs.

  • default_permission (TrueClass, FalseClass, nil) (defaults to: nil)

    (replaced by default_member_permissions) Whether the command is enabled by default when the app is added to a guild.

  • integration_types (Array, nil) (defaults to: nil)

    Installation context(s) where the command is available.

  • contexts (Array, nil) (defaults to: nil)

    Interaction context(s) where the command can be used

  • type (Integer, nil) (defaults to: nil)

    The type of the command.

  • nsfw (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether the command is NSFW.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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 = post(url, data, headers)
  return response if response.is_a?(Faraday::Response) && (response.status == 201 || response.status == 200)

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

#create_global_application_commands(application_commands_array) ⇒ Array

Mass-creates application commands globally.

Parameters:

  • application_commands_array (Array)

    An array of arrays, where the first two elements (of the inner array) are the values for for the first two parameters (which are required) in the create_global_application_command method in order. The third element is a Hash that contains the rest of the parameters for the command, the key must be the name of the parameter as a symbol (e.g. :description, :options, etc.) and the value must be the value

    for that parameter.
    

Returns:

  • (Array)

    An array of Faraday::Response objects, one for each command creation request.



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

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

Parameters:

  • access_tokens (Array)

    An array of access tokens (as strings) of users that have granted your app the gdm.join OAuth2 scope

  • nicks (Hash)

    “a dictionary of user ids to their respective nicknames” (whatever that means)

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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 = post(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to create group DM. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (Integer)

    The ID of the guild where the command will be created.

  • name (String)

    The name of the command.

  • name_localizations (Hash, nil) (defaults to: nil)

    Localized names for the command.

  • description (String, nil)

    The description of the command.

  • description_localizations (Hash, nil) (defaults to: nil)

    Localized descriptions for the command.

  • options (Array, nil) (defaults to: nil)

    Options for the command.

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

    Sets the default permission(s) that members need to run the command. (must be set to a bitwise permission flag as a string)

  • default_permission (TrueClass, FalseClass, nil) (defaults to: nil)

    (replaced by default_member_permissions) Whether the command is enabled by default when the app is added to a guild.

  • type (Integer, nil) (defaults to: nil)

    The type of the command.

  • nsfw (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether the command is NSFW.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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
46
# 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 = post(url, data, headers)
  return response if response.is_a?(Faraday::Response) && (response.status == 201 || response.status == 200)

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

#create_guild_application_commands(application_commands_array) ⇒ Array

Mass-creates application commands for guild(s).

Parameters:

  • application_commands_array (Array)

    An array of arrays, where the first three elements (of the inner array) are the values for for the first three parameters (which are required) in the create_guild_application_command method in order. The fourth element is a Hash that contains the rest of the parameters for the command, the key must be the name of the parameter as a symbol (e.g. :description, :options, etc.) and the value must be the value

    for that parameter.
    

Returns:

  • (Array)

    An array of Faraday::Response objects, one for each command creation request.



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

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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to ban the user from

  • user_id (String)

    ID (as a string) of the user to ban from the guild

  • delete_message_days (Integer, nil) (defaults to: nil)

    Number of days to delete messages for (0-7) (DEPRECATED, use delete_message_seconds instead)

  • delete_message_seconds (Integer, nil) (defaults to: nil)

    Number of seconds to delete messages for (0-604800) (604800s=7d)

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

    Reason for the ban, shows up on the audit log entry.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
# File 'lib/disrb/guild.rb', line 589

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 = put(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 204

  @logger.error("Could not create guild ban for user with ID #{user_id} in guild with ID #{guild_id}." \
                 " Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to create the channel in.

  • name (String)

    Name of the new channel (1-100 characters)

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

    The channel topic (a.k.a. description) (0-1024 characters)

  • bitrate (Integer, nil) (defaults to: nil)

    Bitrate of the voice or stage channel in bits, min 8000

  • user_limit (Integer, nil) (defaults to: nil)

    User limit of the voice channel

  • rate_limit_per_user (Integer, nil) (defaults to: nil)

    Amount of seconds a user has to wait before sending another message (0-21600)

  • position (Integer, nil) (defaults to: nil)

    Sorting position of the channel (Channels with the same position are sorted by ID)

  • permission_overwrites (Array, nil) (defaults to: nil)

    Array of partial overwrite objects; the channel’s permission overwrites

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

    ID (as a string) of the parent category for a channel

  • nsfw (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether the channel is NSFW

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

    Channel voice region ID (as string) of the voice or stage channel, set to "auto" for automatic region selection

  • video_quality_mode (Integer, nil) (defaults to: nil)

    The camera video quality mode of the voice channel

  • default_auto_archive_duration (Integer, nil) (defaults to: nil)

    The default duration that the clients use for newly created threads in the channel, in minutes, to automatically archive the thread after recent activity

  • default_reaction_emoji (Hash, nil) (defaults to: nil)

    Default reaction object; Emoji to show in the add reaction button on a thread in a forum or media channel

  • available_tags (Array, nil) (defaults to: nil)

    Array of tag objects; set of tags that can be used in a forum or media channel

  • default_sort_order (Integer, nil) (defaults to: nil)

    The default sort order type used to order posts in forum and media channels

  • default_forum_layout (Integer, nil) (defaults to: nil)

    The default forum layout view used to display posts in forum channels

  • default_thread_rate_limit_per_user (Integer, nil) (defaults to: nil)

    The initial rate_limit_per_user to set on newly created threads in a channel. This field is copied to the thread at creation time and does not live update.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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 = post(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Could not create guild channel in Guild ID #{guild_id}. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to create the role in

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

    Name of the role (default: “new role”)

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

    Bitwise value of the permissions for the role (default: @everyone permissions)

  • color (Integer, nil) (defaults to: nil)

    (DEPRECATED, USE colors INSTEAD) RGB color value for the role (default: 0)

  • colors (Hash, nil) (defaults to: nil)

    Role colors object

  • hoist (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether the role should be displayed separately in the sidebar (default: false)

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

    URI-encoded base64 image data for the role icon (default: nil)

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

    The role’s unicode emoji as a standard emoji (default: nil)

  • mentionable (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether the role should be able to be mentioned by @everyone (default: false)

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

    Reason for the creation, shows up on the audit log entry.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
# File 'lib/disrb/guild.rb', line 699

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 = post(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Could not create guild role in guild with ID #{guild_id}." \
                "Response: #{response_error_body(response)}")
  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, shared_client_theme: 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

Parameters:

  • channel_id (String)

    The ID of the channel to create the message in

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

    Message contents (up to 2000 characters)

  • nonce (String, Integer, nil) (defaults to: nil)

    Can be used to verify if a message was sent (up to 25 characters). The value will appear in the message object,

  • tts (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether the message is a TTS message

  • embeds (Array, nil) (defaults to: nil)

    Up to 10 rich embeds (up to 6000 characters)

  • allowed_mentions (Hash, nil) (defaults to: nil)

    Allowed mentions object

  • message_reference (Hash, nil) (defaults to: nil)

    Message reference object for replies/forwards

  • components (Array, nil) (defaults to: nil)

    An array of Components to include with the message

  • sticker_ids (Array, nil) (defaults to: nil)

    IDs of up to 3 stickers in the server to send in the message

  • files (Array, nil) (defaults to: nil)

    An array of arrays, each inner-array first has its filename (index 0), raw file data as a string (index 1), and then the MIME type of the file (index 2).

  • attachments (Array, nil) (defaults to: nil)

    Array of partial attachment objects, if left empty but the files parameter is not empty, this will be automatically generated.

  • flags (Integer, nil) (defaults to: nil)

    Message flags combined as a bitfield.

  • enforce_nonce (TrueClass, FalseClass, nil) (defaults to: nil)

    If true and a nonce is set, the nonce’s uniqueness will be checked, if a message with the same nonce already exists from the same author, that message will be returned and no new message will be created.

  • poll (Hash, nil) (defaults to: nil)

    A poll object

  • shared_client_theme (Hash, nil) (defaults to: nil)

    THe custom client-side theme to share via the message; shared client theme object

Returns:

  • (Faraday::Response, nil)

    The response from the Discord API as a Faraday::Response object, or nil if none of content, embeds, sticker_ids, components or poll were provided.



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
121
122
123
124
125
126
127
# File 'lib/disrb/message.rb', line 87

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, shared_client_theme: nil)
  if content.nil? && embeds.nil? && sticker_ids.nil? && components.nil? && files.nil? && poll.nil? &&
     shared_client_theme.nil?
    @logger.warn('No content, embeds, sticker_ids, components, files, poll or shared client theme 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?
  if attachments.nil? && !files.nil?
    output[:attachments] = generate_attachment_object_array(files)
  elsif attachments
    output[:attachments] = attachments
  end
  output[:flags] = flags unless flags.nil?
  output[:enforce_nonce] = enforce_nonce unless enforce_nonce.nil?
  output[:poll] = poll unless poll.nil?
  output[:shared_client_theme] = shared_client_theme unless shared_client_theme.nil?
  url = "#{@base_url}/channels/#{channel_id}/messages"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header }
  if files
    response = file_upload(url, files, payload_json: data, headers: headers)
  else
    headers['Content-Type'] = 'application/json'
    response = post(url, data, headers)
  end
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to create message in channel #{channel_id}. Response: #{response_error_body(response)}")
  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

Parameters:

  • channel_id (String)

    The ID of the channel the message is located in

  • message_id (String)

    The ID of the message to create the reaction for

  • emoji (String)

    URL encoded emoji to react with, or name:id format for custom emojis

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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 = put(url, nil, headers)
  return response if response.is_a?(Faraday::Response) && 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_error_body(response)}")
  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

Parameters:

  • channel_id (String)

    The ID of the channel the message to crosspost is located

  • message_id (String)

    The ID of the message to crosspost

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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

  @logger.error("Failed to crosspost message with ID #{message_id} in channel with ID #{channel_id}. " \
                  "Response: #{response_error_body(response)}")
  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

Parameters:

  • channel_id (String)

    The ID of the channel the message is located in

  • message_id (String)

    The ID of the message to delete reactions for

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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

  @logger.error("Failed to delete all reactions in channel with ID #{channel_id} for message with ID #{message_id}" \
                  ". Response: #{response_error_body(response)}")
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

Parameters:

  • channel_id (String)

    The ID of the channel the message is located in

  • message_id (String)

    The ID of the message to delete reactions for

  • emoji (String)

    URL encoded emoji to delete, or name:id format for custom emojis

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



244
245
246
247
248
249
250
251
252
# File 'lib/disrb/message.rb', line 244

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 = delete(url, headers)
  return response if response.is_a?(Faraday::Response) && 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_error_body(response)}")
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

Parameters:

  • command_id (String)

    The ID of the global command to delete.

Returns:

  • (Faraday::Response)

    The response from the Discord API.



235
236
237
238
239
240
241
242
243
244
# File 'lib/disrb/application_commands.rb', line 235

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

  @logger.error("Failed to delete global application command with ID #{command_id}." \
                "Response: #{response_error_body(response)}")
  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 = delete(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 204

  @logger.error("Could not delete guild with Guild ID #{guild_id}. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    The ID of the guild containing the command.

  • command_id (String)

    The ID of the guild command to delete.

Returns:

  • (Faraday::Response)

    The response from the Discord API.



251
252
253
254
255
256
257
258
259
260
# File 'lib/disrb/application_commands.rb', line 251

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 = delete(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 204

  @logger.error("Failed to delete guild application command with ID #{command_id} in guild with ID #{guild_id}. " \
                "Response: #{response_error_body(response)}")
  response
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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild containing the integration to delete

  • integration_id (String)

    ID (as a string) of the integration to delete

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

    Reason for the deletion, shows up on the audit log entry.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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 = delete(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 204

  @logger.error("Failed to delete guild integration. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild the role to delete is in

  • role_id (String)

    ID (as a string) of the role to delete

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

    Reason for the deletion of the role, shows up in the audit log

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



821
822
823
824
825
826
827
828
829
830
# File 'lib/disrb/guild.rb', line 821

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 = delete(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 204

  @logger.error("Failed to delete guild role. Response: #{response_error_body(response)}")
  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

Parameters:

  • channel_id (String)

    The ID of the channel the message is located in

  • message_id (String)

    The ID of the message to delete

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

    The reason for deleting the message. Shows up on the audit log.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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 = delete(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 204

  @logger.error("Failed to delete message with ID #{message_id} in channel with ID #{channel_id}. " \
                  "Response: #{response_error_body(response)}")
  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

Parameters:

  • channel_id (String)

    The ID of the channel the message is located in

  • message_id (String)

    The ID of the message to delete the reaction for

  • emoji (String)

    URL encoded emoji to delete, or name:id format for custom emojis

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



168
169
170
171
172
173
174
175
176
177
# File 'lib/disrb/message.rb', line 168

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 = delete(url, headers)
  return response if response.is_a?(Faraday::Response) && 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_error_body(response)}")
  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

Parameters:

  • channel_id (String)

    The ID of the channel the message is located in

  • message_id (String)

    The ID of the message to delete the reaction for

  • emoji (String)

    URL encoded emoji to delete, or name:id format for custom emojis

  • user_id (String)

    The ID of the user to delete the reaction for

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



186
187
188
189
190
191
192
193
194
195
196
# File 'lib/disrb/message.rb', line 186

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 = delete(url, headers)
  return response if response.is_a?(Faraday::Response) && 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_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    The ID of the guild containing the command.

  • command_id (String)

    The ID of the command to edit permissions for.

  • permissions (Hash)

    The permissions payload to set.

Returns:

  • (Faraday::Response)

    The response from the Discord API.



398
399
400
401
402
403
404
405
406
407
408
# File 'lib/disrb/application_commands.rb', line 398

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 = put(url, data, headers)
  return response if response.is_a?(Faraday::Response) && 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_error_body(response)}")
  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

Parameters:

  • command_id (String)

    The ID of the global command to edit.

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

    New name of the command.

  • name_localizations (Hash, nil) (defaults to: nil)

    Localized names for the command.

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

    New description of the command.

  • description_localizations (Hash, nil) (defaults to: nil)

    Localized descriptions for the command.

  • options (Array, nil) (defaults to: nil)

    New options for the command.

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

    New default permissions bitwise string for the command.

  • default_permission (TrueClass, FalseClass, nil) (defaults to: nil)

    (deprecated) Whether the command is enabled by default.

  • integration_types (Array, nil) (defaults to: nil)

    Installation context(s) where the command is available.

  • contexts (Array, nil) (defaults to: nil)

    Interaction context(s) where the command can be used.

  • nsfw (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether the command is NSFW.

Returns:

  • (Faraday::Response, nil)

    The response from the Discord API, or nil if no modifications were provided.



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

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 = patch(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to edit global application command with ID #{command_id}." \
                " Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    The ID of the guild containing the command.

  • command_id (String)

    The ID of the guild command to edit.

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

    New name of the command.

  • name_localizations (Hash, nil) (defaults to: nil)

    Localized names for the command.

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

    New description of the command.

  • description_localizations (Hash, nil) (defaults to: nil)

    Localized descriptions for the command.

  • options (Array, nil) (defaults to: nil)

    New options for the command.

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

    New default permissions bitwise string for the command.

  • default_permission (TrueClass, FalseClass, nil) (defaults to: nil)

    (deprecated) Whether the command is enabled by default.

  • nsfw (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether the command is NSFW.

Returns:

  • (Faraday::Response, nil)

    The response from the Discord API, or nil if no modifications were provided.



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

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 = patch(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to edit guild application command with ID #{command_id}." \
                " Response: #{response_error_body(response)}")
  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.

Parameters:

  • channel_id (String)

    The ID of the channel the message is located in

  • message_id (String)

    The ID of the message to edit

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

    Message contents (up to 2000 characters)

  • embeds (Array, nil) (defaults to: nil)

    Up to 10 rich embeds (up to 6000 characters)

  • flags (Integer, nil) (defaults to: nil)

    Message flags combined as an integer.

  • allowed_mentions (Hash, nil) (defaults to: nil)

    Allowed mentions object

  • components (Array, nil) (defaults to: nil)

    An array of Components to include with the message

  • files (Array) (defaults to: nil)

    An array of arrays, each inner-array first has its filename (index 0), raw file data as a string (index 1), and then the MIME type of the file (index 2).

  • attachments (Array, nil) (defaults to: nil)

    Array of partial attachment objects, if left empty but the files parameter is not empty, this will be automatically generated.

Returns:

  • (Faraday::Response, nil)

    The response from the Discord API as a Faraday::Response object, or nil if no modifications were provided.



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

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?)
    @logger.warn("No modifications provided for message with ID #{message_id} in channel with ID #{channel_id}. " \
                  '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?
  if attachments.nil? && !files.nil?
    output[:attachments] = generate_attachment_object_array(files)
  elsif attachments
    output[:attachments] = attachments
  end
  url = "#{@base_url}/channels/#{channel_id}/messages/#{message_id}"
  data = JSON.generate(output)
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
  if files
    response = file_upload(url, files, headers: headers, payload_json: data, request_type: :patch)
  else
    headers['Content-Type'] = 'application/json'
    response = patch(url, data, headers)
  end
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to edit message with ID #{message_id} in channel with ID #{channel_id}. " \
                  "Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    The ID of the guild containing the command.

  • command_id (String)

    The ID of the command to get permissions for.

Returns:

  • (Faraday::Response)

    The response from the Discord API.



381
382
383
384
385
386
387
388
389
390
# File 'lib/disrb/application_commands.rb', line 381

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 = get(url, headers)
  return response if response.is_a?(Faraday::Response) && 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_error_body(response)}")
  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

Parameters:

  • channel_id (String)

    The ID of the channel to get the message from.

  • message_id (String)

    The ID of the message to get.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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

  @logger.error("Failed to get message with ID #{message_id} from channel with ID #{channel_id}. " \
                  "Response: #{response_error_body(response)}")
  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).

Parameters:

  • channel_id (String)

    The ID of the channel to get messages from.

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

    Gets messages around the specified message ID.

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

    Gets messages before the specified message ID.

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

    Gets messages after the specified message ID.

  • limit (Integer, nil) (defaults to: nil)

    The maximum number of messages to return. Default 50.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Farday::Response object.



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
42
# 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 = get(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to get messages from channel with ID #{channel_id}." \
                " Response: #{response_error_body(response)}")
  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.

Parameters:

  • channel_id (String)

    The ID of the channel to get pinned messages from

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

    Get messages pinned before this ISO8601 timestamp

  • limit (Integer, nil) (defaults to: nil)

    The maximum number of messages to return. (1-50, default 50)

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



349
350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'lib/disrb/message.rb', line 349

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 = get(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

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

#get_current_userFaraday::Response

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

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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 = get(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to get current user. Response: #{response_error_body(response)}")
  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

Parameters:

  • application_id (String)

    The ID of the application to get the role connection for.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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

  @logger.error("Failed to get current user's application role connection for application ID #{application_id}. " \
                "Response: #{response_error_body(response)}")
  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

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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

  @logger.error("Failed to get current user's connections. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    The ID of the guild to get the current user’s guild member for.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

def get_current_user_guild_member(guild_id)
  url = "#{@base_url}/users/@me/guilds/#{guild_id}/member"
  headers = { 'Authorization': @authorization_header }
  response = get(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to get current user's guild member for guild ID with ID #{guild_id}. Response: " \
                  "#{response_error_body(response)}")
  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

Parameters:

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

    Get guilds before this guild ID.

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

    Get guilds after this guild ID.

  • limit (Integer, nil) (defaults to: nil)

    Maximum number of guilds to return. 1-200 allowed, 200 default.

  • with_counts (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether to include approximate member and presence counts in response.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# 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 = get(url, headers)
  if response.is_a?(Faraday::Response) && response.status == 200 && @authorization_token_type == 'Bot' &&
     JSON.parse(response.body).count == 200
    @logger.info('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.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to get current user's guilds. Response: #{response_error_body(response)}")
  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

Parameters:

  • command_id (String)

    The ID of the global command to retrieve.

Returns:

  • (Faraday::Response)

    The response from the Discord API.



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

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

  @logger.error("Failed to get global application command with ID #{command_id}." \
                " Response: #{response_error_body(response)}")
  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

Parameters:

  • with_localizations (TrueClass, FalseClass, nil) (defaults to: false)

    Whether to include full localization dictionaries.

Returns:

  • (Faraday::Response)

    The response from the Discord API.



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

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 = get(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to get global application commands. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get.

  • with_counts (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether to include approximate member and presence counts.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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 = get(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Could not get guild with Guild ID #{guild_id}. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    The ID of the guild containing the command.

  • command_id (String)

    The ID of the guild command to retrieve.

Returns:

  • (Faraday::Response)

    The response from the Discord API.



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

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 = get(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to get guild application command with ID #{command_id}." \
                " Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    The ID of the guild to get command permissions for.

Returns:

  • (Faraday::Response)

    The response from the Discord API.



365
366
367
368
369
370
371
372
373
374
# File 'lib/disrb/application_commands.rb', line 365

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

  @logger.error("Failed to get guild application command permissions for guild with ID #{guild_id}. " \
                  "Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    The ID of the guild to list commands for.

  • with_localizations (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether to include full localization dictionaries.

Returns:

  • (Faraday::Response)

    The response from the Discord API.



267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/disrb/application_commands.rb', line 267

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 = get(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to get guild application commands for guild with ID #{guild_id}." \
                " Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get the ban from

  • user_id (String)

    ID (as a string) of the user to get the ban object for

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



565
566
567
568
569
570
571
572
573
574
575
576
577
578
# File 'lib/disrb/guild.rb', line 565

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

  if response.is_a?(Faraday::Response) && 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_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get the bans from.

  • limit (Integer, nil) (defaults to: nil)

    Maximum number of bans to return (1-1000)

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

    Get bans before this user ID (as a string)

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

    Get bans after this user ID (as a string)

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



545
546
547
548
549
550
551
552
553
554
555
556
557
558
# File 'lib/disrb/guild.rb', line 545

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 = get(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Could not get guild bans with Guild ID #{guild_id}. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get the channels for.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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 = get(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Could not get guild channels with Guild ID #{guild_id}. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get the integrations from

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



918
919
920
921
922
923
924
925
926
927
928
929
930
931
# File 'lib/disrb/guild.rb', line 918

def get_guild_integrations(guild_id)
  url = "#{@base_url}/guilds/#{guild_id}/integrations"
  headers = { 'Authorization': @authorization_header }
  response = get(url, headers)
  if response.is_a?(Faraday::Response) && 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_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get the invites from

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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

  @logger.error("Failed to get guild invites. Response: #{response_error_body(response)}")
  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 https://discord.com/developers/docs/resources/guild#get-guild-member

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get the member from.

  • user_id (String)

    ID (as a string) of the user to get the member object for.

Returns:

  • (Faraday::Response)

    The response from the DiscordApi as a Faraday::Response object.



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

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

  @logger.error("Could not get guild member with Guild ID #{guild_id} and User ID #{user_id}. Response:" \
                 "#{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get onboarding for.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



1103
1104
1105
1106
1107
1108
1109
1110
1111
# File 'lib/disrb/guild.rb', line 1103

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

  @logger.error("Failed to get guild onboarding. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get the preview for.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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 = get(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Could not get guild preview with Guild ID #{guild_id}. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get the prune count for

  • days (Integer, nil) (defaults to: nil)

    Number of days to count prune for (1-30)

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

    Comma-delimited list of role IDs (as strings), these roles will also be included in the prune count

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



839
840
841
842
843
844
845
846
847
848
849
850
851
# File 'lib/disrb/guild.rb', line 839

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 = get(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to get guild prune count. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get the role from.

  • role_id (String)

    ID (as a string) of the role to get.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



673
674
675
676
677
678
679
680
681
682
# File 'lib/disrb/guild.rb', line 673

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

  @logger.error("Could not get role with ID #{role_id} in guild with ID #{guild_id}." \
                " Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get the roles from.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



658
659
660
661
662
663
664
665
666
# File 'lib/disrb/guild.rb', line 658

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

  @logger.error("Could not get guild roles with Guild ID #{guild_id}. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get the vanity URL from

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



1005
1006
1007
1008
1009
1010
1011
1012
1013
# File 'lib/disrb/guild.rb', line 1005

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

  @logger.error("Failed to get guild vanity URL. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get the voice regions from

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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

  @logger.error("Failed to get guild voice regions. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get the welcome screen for.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



1056
1057
1058
1059
1060
1061
1062
1063
1064
# File 'lib/disrb/guild.rb', line 1056

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

  @logger.error("Failed to get guild welcome screen. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get the widget from

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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

  @logger.error("Failed to get guild widget. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get the widget image for.

  • shield (TrueClass, FalseClass) (defaults to: false)

    Whether to request the “shield” style widget image.

  • banner1 (TrueClass, FalseClass) (defaults to: false)

    Whether to request the “banner1” style widget image.

  • banner2 (TrueClass, FalseClass) (defaults to: false)

    Whether to request the “banner2” style widget image.

  • banner3 (TrueClass, FalseClass) (defaults to: false)

    Whether to request the “banner3” style widget image.

  • banner4 (TrueClass, FalseClass) (defaults to: false)

    Whether to request the “banner4” style widget image.

Returns:

  • (Faraday::Response, nil)

    The response from the Discord API as a Faraday::Response object containing the PNG image data, or nil if more than one style was specified.



1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
# File 'lib/disrb/guild.rb', line 1027

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 = get(url)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to get guild widget image. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to get the widget settings from

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



954
955
956
957
958
959
960
961
962
# File 'lib/disrb/guild.rb', line 954

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

  @logger.error("Failed to get guild widget settings. Response: #{response_error_body(response)}")
  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

Parameters:

  • channel_id (String)

    The ID of the channel the message is located in

  • message_id (String)

    The ID of the message to get reactions for

  • emoji (String)

    URL encoded emoji to get reactions for, or name:id format for custom emojis

  • type (Integer, nil) (defaults to: nil)

    Type of reaction to return.

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

    Get users after this user ID

  • limit (Integer, nil) (defaults to: nil)

    Maximum number of users to return (1-100).

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/disrb/message.rb', line 207

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 = get(url, headers)
  return response if response.is_a?(Faraday::Response) && 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_error_body(response)}")
  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

Parameters:

  • user_id (String)

    The ID of the user.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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 = get(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to get user with ID #{user_id}. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    The ID of the guild to leave.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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

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

#list_active_guild_threads(guild_id) ⇒ Faraday::Response

Returns a list of active threads in the specified guild.

See https://discord.com/developers/docs/resources/guild#list-active-guild-threads

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to list active threads for.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



271
272
273
274
275
276
277
278
279
280
# File 'lib/disrb/guild.rb', line 271

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

  @logger.error("Could not list active guild threads with Guild ID #{guild_id}." \
                " Response: #{response_error_body(response)}")
  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 https://discord.com/developers/docs/resources/guild#list-guild-members

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to list the members for.

  • limit (Integer, nil) (defaults to: nil)

    Maximum number of members to return (1-100). Default: 1

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

    Get users after this user ID (as a string)

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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 = get(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Could not list members with Guild ID #{guild_id}. Response: #{response_error_body(response)}")
  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)

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to modify the current member in

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

    Value to set the user’s name to in the guild.

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

    Data URI scheme with BASE64-encoded image data to set as the user’s banner in the guild. See discord.com/developers/docs/reference#image-data

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

    Data URI scheme with BASE64-encoded image data to set as the user’s avatar in the guild. See discord.com/developers/docs/reference#image-data

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

    Value to set the user’s bio to in the guild.

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

    Reason for the modification, shows up on the audit log entry.

Returns:

  • (Faraday::Response, nil)

    The response from the Discord API as a Faraday::Response object, or nil if no modifications were provided.



437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
# File 'lib/disrb/guild.rb', line 437

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 = patch(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Could not modify current member in guild with Guild ID #{guild_id}." \
                " Response: #{response_error_body(response)}")
  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.

Parameters:

Returns:

  • (Faraday::Response, nil)

    The response from the Discord API as a Faraday::Response object or nil if no modifications were provided.



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 = patch(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to modify current user. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to modify the current user’s nickname in

  • nick (String)

    Value to set the user’s nickname to in the specified guild.

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

    Reason for the modification, shows up on the audit log entry.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
# File 'lib/disrb/guild.rb', line 466

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 = patch(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Could not modify current user nick in guild with ID #{guild_id}." \
                " Response: #{response_error_body(response)}")
  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.

Parameters:

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

    The new name of the guild.

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

    Guild voice region ID. [DEPRECATED]

  • verification_level (Integer, nil) (defaults to: nil)

    The new verification level of the guild.

  • default_message_notifications (Integer, nil) (defaults to: nil)

    Default message notification level.

  • explicit_content_filter (Integer, nil) (defaults to: nil)

    Explicit content filter level.

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

    ID (as a string) of the afk channel.

  • afk_timeout (Integer, nil) (defaults to: nil)

    AFK timeout in seconds. Can be set to; 60, 300, 900, 1800 or 3600.

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

    BASE64-encoded image data to be set as the guild icon. See discord.com/developers/docs/reference#image-data. Set this parameter as the Data URI scheme (as a string).

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

    BASE64-encoded image data to be set as the guild splash. See discord.com/developers/docs/reference#image-data. Set this parameter as the Data URI scheme (as a string).

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

    BASE64-encoded image data to be set as the guild discovery splash. See discord.com/developers/docs/reference#image-data. Set this parameter as the Data URI scheme (as a string).

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

    BASE64-encoded image data to be set as the guild banner. See discord.com/developers/docs/reference#image-data. Set this parameter as the Data URI scheme (as a string).

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

    ID (as a string) of the channel to be used for guild system messages.

  • system_channel_flags (Integer, nil) (defaults to: nil)

    System channel flags.

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

    ID (as a string) of the channel to be used for rules and/or guidelines.

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

    ID (as a string) of the channel to be used for public updates.

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

    The preferred locale of a Community guild, default “en-US”.

  • features (Array, nil) (defaults to: nil)

    An array of enabled guild features (strings).

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

    The description of the guild.

  • premium_progress_bar_enabled (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether the guild’s boost progress bar is enabled.

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

    ID (as a string) of the channel to be used for safety alerts.

Returns:

  • (Faraday::Response, nil)

    The response from the Discord API as a Faraday::Response object, or nil if no modifications were provided.



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 = patch(url, headers, data)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Could not modify guild with Guild ID #{guild_id}. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to modify the channel positions for.

  • data (Hash)

    A hash where the keys are channel IDs (as symbols) and the values are another hash formed of keys that are either:

    • :position (Integer) sorting position of the channel (channels with the same position are sorted by ID)

    • :lock_permissions (TrueClass, FalseClass) whether to sync the permission overwrites with the new parent category, if moving to a different one. If this is provided but :parent_id isnt, this will be dropped from the request

    • :parent_id (String) ID (as a string) of the new parent category for a channel

    Example: { :1395365491005980814 => { :position => 0, :lock_permissions => false, :parent_id => “1395365491005980825” }, 1389464920227319879 => { :position => 1 }}

    If no modifications are provided for a channel, that channel will be dropped, please note that :lock_permissions can be dropped, and this affects if it gets dropped

    And if the entire data hash is empty (after dropping channels with no modifications), the entire function will be skipped and will return nil

Returns:

  • (Faraday::Response, nil)

    The response from the Discord API as a Faraday::Response object, or nil if no modifications were provided



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
# 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 = patch(url, headers, data)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Could not modify guild channel positions with Guild ID #{guild_id}." \
                " Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to modify incident actions for.

  • invites_disabled_until (String, FalseClass, nil) (defaults to: nil)

    ISO8601 timestamp until which invites are disabled, false to clear, or nil to leave unchanged.

  • dms_disabled_until (String, FalseClass, nil) (defaults to: nil)

    ISO8601 timestamp until which DMs are disabled, false to clear, or nil to leave unchanged.

Returns:

  • (Faraday::Response, nil)

    The response from the Discord API as a Faraday::Response object, or nil if no modifications were provided.



1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
# File 'lib/disrb/guild.rb', line 1158

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 = put(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to modify guild incident actions. Response: #{response_error_body(response)}")
  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)

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to modify the member in

  • user_id (String)

    ID (as a string) of the user to modify

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

    Value to set the user’s nickname to.

  • roles (Array, nil) (defaults to: nil)

    Array of role IDs (as strings) the user will be assigned.

  • mute (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether the user is muted in voice channels.

  • deaf (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether the user is deafened in voice channels.

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

    ID (as a string) of the ID of a voice channel to move the user to (if the user is in a voice channel).

  • communication_disabled_until (String, FalseClass, nil) (defaults to: nil)

    When the user’s timeout will expire (up to 28 days in the future) in ISO8601 format, or false to remove timeout.

  • flags (Integer, nil) (defaults to: nil)

    New guild member flags.

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

    Reason for the modification, shows up on the audit log entry.

Returns:

  • (Faraday::Response, nil)

    The response from the Discord API as a Faraday::Response object, or nil if no modifications were provided.



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

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 = patch(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Could not modify guild member with Guild ID #{guild_id} and User ID #{user_id}. " \
  "Response: #{response_error_body(response)}")
  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.

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to modify the MFA level for

  • level (Integer)

    The MFA level to set for the guild, can be 0 (no MFA required) or 1 (MFA required for administrative actions)

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

    Reason for the modification, shows up on the audit log entry.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



801
802
803
804
805
806
807
808
809
810
811
812
813
# File 'lib/disrb/guild.rb', line 801

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 = post(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to modify guild MFA level. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to modify onboarding for.

  • prompts (Array, nil) (defaults to: nil)

    Array of prompt objects to set.

  • default_channel_ids (Array, nil) (defaults to: nil)

    Array of channel IDs (as strings) considered default for onboarding.

  • enabled (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether onboarding is enabled in the guild.

  • mode (Integer, nil) (defaults to: nil)

    The onboarding mode to set.

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

    Reason for the modification (appears in audit log entry).

Returns:

  • (Faraday::Response, nil)

    The response from the Discord API as a Faraday::Response object, or nil if no modifications were provided.



1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
# File 'lib/disrb/guild.rb', line 1125

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 = put(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to modify guild onboarding. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild the role to modify is in

  • role_id (String)

    ID (as a string) of the role to modify

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

    New name of the role

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

    New bitwise value of the permissions for the role

  • color (Integer, nil) (defaults to: nil)

    (DEPRECATED, USE colors INSTEAD) New RGB color value for the role

  • colors (Hash, nil)

    New role colors object

  • hoist (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether the role should be displayed separately in the sidebar

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

    URI-encoded base64 image data for the role icon

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

    The role’s unicode emoji as a standard emoji

  • mentionable (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether the role should be able to be mentioned by @everyone

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

    Reason for the modification, shows up on the audit log entry.

Returns:

  • (Faraday::Response, nil)

    The response from the Discord API as a Faraday::Response object, or nil if no modifications were provided.



768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
# File 'lib/disrb/guild.rb', line 768

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 = patch(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Could not modify guild role with ID #{role_id} in guild with ID #{guild_id}." \
               " Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to modify the role positions in

  • role_positions (Array)

    Array of objects (hashes) with “id” and “position” keys with “id” being the role ID (as a string) and “position” being the sorting position of the role (roles with the same position are sorted by id), if this array is empty, a warning will be logged and the function will be skipped, return nil. (no request will be made to discord)

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

    Reason for the modification, shows up on the audit log entry.

Returns:

  • (Faraday::Response, nil)

    The response from the Discord API as a Faraday::Response object, or nil if role_positions was empty.



736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
# File 'lib/disrb/guild.rb', line 736

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 = patch(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Could not modify guild role positions in guild with ID #{guild_id}." \
                " Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to modify the welcome screen for.

  • enabled (TrueClass, FalseClass, nil) (defaults to: nil)

    Whether the welcome screen is enabled.

  • welcome_channels (Array, nil) (defaults to: nil)

    Array of welcome channel objects (hashes) to set.

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

    Description text for the welcome screen.

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

    Reason for the modification (appears in audit log entry).

Returns:

  • (Faraday::Response, nil)

    The response from the Discord API as a Faraday::Response object, or nil if no modifications were provided.



1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
# File 'lib/disrb/guild.rb', line 1077

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 = patch(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to modify guild welcome screen. Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to modify the widget settings for

  • enabled (TrueClass, FalseClass)

    Whether the guild widget is enabled

  • channel_id (String)

    ID (as a string) of the channel to show in the widget

  • audit_reason (String) (defaults to: nil)

    Reason for the modification, shows up on the audit log entry.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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 = patch(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Failed to modify guild widget. Response: #{response_error_body(response)}")
  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

Parameters:

  • channel_id (String)

    The ID of the channel the message is located in

  • message_id (String)

    The ID of the message to pin

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

    The reason for pinning the message. Shows up in the audit log.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



370
371
372
373
374
375
376
377
378
379
380
# File 'lib/disrb/message.rb', line 370

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 = put(url, nil, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 204

  @logger.error("Failed to pin message with ID #{message_id} in channel with ID #{channel_id}. " \
                  "Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to unban the user from

  • user_id (String)

    ID (as a string) of the user to unban from the guild

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

    Reason for the unban, shows up on the audit log entry.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



614
615
616
617
618
619
620
621
622
623
624
# File 'lib/disrb/guild.rb', line 614

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 = delete(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 204

  @logger.error("Could not remove guild ban for user with ID #{user_id} in guild with ID #{guild_id}" \
                " Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to remove the member from

  • user_id (String)

    ID (as a string) of the user to remove from the guild

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

    Reason for the kick, shows up on the audit log entry.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



526
527
528
529
530
531
532
533
534
535
536
# File 'lib/disrb/guild.rb', line 526

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 = delete(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 204

  @logger.error("Could not remove user with ID #{user_id} from guild with ID #{guild_id}." \
                " Response: #{response_error_body(response)}")
  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

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to remove the role from the member in

  • user_id (String)

    ID (as a string) of the user to remove the role from

  • role_id (String)

    ID (as a string) of the role to remove from the user

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

    Reason for the modification, shows up on the audit log entry.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



508
509
510
511
512
513
514
515
516
517
518
# File 'lib/disrb/guild.rb', line 508

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 = delete(url, headers)
  return response if response.is_a?(Faraday::Response) && 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_error_body(response)}")
  response
end

#respond_interaction(interaction, response, with_response: false, files: nil) ⇒ 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

Parameters:

  • interaction (Hash)

    The interaction payload received from the Gateway.

  • response (Hash)

    The interaction response payload.

  • with_response (TrueClass, FalseClass) (defaults to: false)

    Whether to request the created message in the response.

  • files (Array) (defaults to: nil)

    An array of arrays, each inner-array first has its filename (index 0), raw file data as a string (index 1), and then the MIME type of the file (index 2).

Returns:

  • (Faraday::Response)

    The response from the Discord API.



375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/disrb.rb', line 375

def respond_interaction(interaction, response, with_response: false, files: nil)
  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)
  if files
    response = file_upload(url, files, payload_json: data)
  else
    headers = { 'Content-Type' => 'application/json' }
    response = post(url, data, headers)
  end
  return response if response.is_a?(Faraday::Response) &&
                     ((response.status == 204 && !with_response) || (response.status == 200 && with_response))

  @logger.error("Failed to respond to interaction. Response: #{response_error_body(response)}")
  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 https://discord.com/developers/docs/resources/guild#search-guild-members

Parameters:

  • guild_id (String)

    ID (as a string) of the guild to search the members in

  • query (String)

    Query string to match usernames and nicknames against.

  • limit (Integer, nil) (defaults to: nil)

    Maximum number of members to return (1-1000). Default: 1

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



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

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 = get(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

  @logger.error("Could not search members with Guild ID #{guild_id}. Response: #{response_error_body(response)}")
  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

Parameters:

  • channel_id (String)

    The ID of the channel the message is located in

  • message_id (String)

    The ID of the message to unpin

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

    The reason for unpinning the message. Shows up in the audit log.

Returns:

  • (Faraday::Response)

    The response from the Discord API as a Faraday::Response object.



388
389
390
391
392
393
394
395
396
397
398
# File 'lib/disrb/message.rb', line 388

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 = delete(url, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 204

  @logger.error("Failed to unpin message with ID #{message_id} in channel with ID #{channel_id}. " \
                  "Response: #{response_error_body(response)}")
  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.

Parameters:

  • application_id (String)

    The ID of the application to update the role connection for.

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

    The vanity name of the platform a bot has connected (max 50 chars)

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

    The username on the platform a bot has connected (max 100 chars)

  • metadata (Hash, nil) (defaults to: nil)

    Hash mapping application role connection metadata keys to their string-ified values (max 100 chars) for the user on the platform a bot has connected.

Returns:

  • (Faraday::Response, nil)

    The response from the Discord API as a Faraday::Response object or nil if no modifications were provided.



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

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 = put(url, data, headers)
  return response if response.is_a?(Faraday::Response) && response.status == 200

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