disrb 0.1.4 → 0.1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 755465c33626010b7a97992a3afbcee4459e9feae3249870900531ce315ae4f5
4
- data.tar.gz: dec666a3607d7d21b3a526f6435a291122239ab66ad908d6d3a2626c1fd7ea45
3
+ metadata.gz: 720c2445e006449cf781790fe5e00fd9e08f16131c6f53e5b87463b165925d63
4
+ data.tar.gz: 38ea74986b2de4adf369de1fee414f8a7cdcc3e71614655b14519e49d72f95af
5
5
  SHA512:
6
- metadata.gz: 1120cf0957b7e7ab2c7fdbf011b27816cb9085cb957f8c3eee37813a1a3627a4649adcb2ca001052740fca0fa7db50e6a0731b87d0ad73b46d0771f1b6fad764
7
- data.tar.gz: d554f6fe8e41c6846d5ed186cc27988e050dc57af37a041203fa5c887414185238dce3c282c88b3c3a14c4e7f3f528eb7c6257b5fdd92e16b167fdd06b86b4df
6
+ metadata.gz: 922b62106b7fc15fbeb04c1ce4736f4c5c50fbd83f1012777ae11eab3f92b466d6c10ce6e5575151e3cd31a7f38fce79ebbff97a4fcbd521a10878efd3d00e9b
7
+ data.tar.gz: 17811d9847cc46ff504553d7484b1c33b944d1c3dc3c2a5f06c933ddfd589c562d5760ad63e22cd648e83294ee0b31abbfaad1256e89c05a4530c91ca599097a
data/CHANGELOG.md CHANGED
@@ -1,3 +1,23 @@
1
+ # v0.1.4.2 (2026-11-23)
2
+
3
+ - Rename project to disrb
4
+ - Migrated project to sourcehut
5
+ - Change licensing to Unlicense OR MIT OR ISC
6
+
7
+ # v0.1.4.1 (2026-04-14)
8
+
9
+ - File uploading was just not implemented in `edit_message`
10
+ - Fix file uploading function being used incorrectly in `create_message`
11
+ - Add new testing function in `test.rb`
12
+ - Fix HTTP handlers getting called incorrectly sometimes
13
+ - Add file uploading support to `respond_interaction` (you will need to specify `attachments` in the response yourself for now)
14
+ - Add uploading files to Discord also via PATCH requests
15
+ - Fix Faraday request types being set incorrectly
16
+ - Fix payload_json being added to multipart form data incorrectly
17
+ - Add info on how to create a new release in `CONTRIBUTING.md`
18
+ - Fix some typos and minor mistakes
19
+ - Add `Gemfile.lock` and remove it from `.gitignore`
20
+
1
21
  # v0.1.4 (2026-04-05)
2
22
 
3
23
  - Add support for file uploading
data/LICENSE CHANGED
@@ -1,7 +1,11 @@
1
- Copyright (c) 2025-2026 hoovad
1
+ Unlicense OR MIT OR ISC
2
2
 
3
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
3
+ This software is available under any of the following licenses, at your choice:
4
+ - The Unlicense, available at LICENSES/Unlicense.txt in this source code repository, or at
5
+ https://unlicense.org
6
+ - The MIT license, available at LICENSES/MIT.txt in this source code repository, or at
7
+ https://spdx.org/licenses/MIT.txt
8
+ - The ISC license, available at LICENSES/ISC.txt in this source code repository, or at
9
+ https://spdx.org/licenses/ISC.txt
4
10
 
5
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
-
7
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11
+ The copyright year is 2026, and the current copyright holder is hoovad.
data/LICENSES/ISC.txt ADDED
@@ -0,0 +1,5 @@
1
+ Copyright (c) 2026 hoovad
2
+
3
+ Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
4
+
5
+ THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
data/LICENSES/MIT.txt ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 hoovad
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,10 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.
4
+
5
+ In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and
6
+ successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
9
+
10
+ For more information, please refer to <http://unlicense.org/>
data/README.md CHANGED
@@ -1,28 +1,18 @@
1
- # discord.rb indev
1
+ # disrb indev
2
2
 
3
- [![Licensed under the MIT license](https://img.shields.io/github/license/hoovad/discord.rb)](LICENSE)
4
- [![Gem Version](https://img.shields.io/gem/v/disrb?logo=ruby&color=green)](https://rubygems.org/gems/disrb)
5
- ![project status: active](https://img.shields.io/badge/project_status-active-green)
6
- [![main](https://github.com/hoovad/discord.rb/actions/workflows/main.yml/badge.svg)](https://github.com/hoovad/discord.rb/actions/workflows/main.yml)
3
+ [Changelog](CHANGELOG.md) | [Documentation](https://www.rubydoc.info/gems/disrb/)
7
4
 
8
- [Changelog](CHANGELOG.md) | [Documentation](https://www.rubydoc.info/gems/disrb/) | [Contributing](CONTRIBUTING.md)
9
-
10
- > [!IMPORTANT]
11
5
  > This is project is still in early development. Expect changes that might break your code at any time. If your code suddenly doesn't work but it did on a previous version, check the [Changelog](CHANGELOG.md) for any breaking changes.
12
6
 
13
7
  W.I.P. Discord API wrapper written in Ruby for fun.
14
8
 
15
- > [!NOTE]
16
9
  > This is not a full-featured Discord API handler. This gem lets you interact with the Discord API directly without all the baggage. If you want to make a bot extremely easily, this is not what you are looking for.
17
10
 
18
- If you wanted to use this project, but found that something is missing, doesn't work, don't be afraid to open an issue! Read the [Contributing](CONTRIBUTING.md) page.
19
-
20
- ## Demonstration
11
+ Please send patches to [~hoovad/public-inbox@lists.sr.ht](mailto:~hoovad/public-inbox@lists.sr.ht). For more info, see <https://git-send-email.io>.
21
12
 
22
- The test.rb file creates two commands "test" and "test2", that return "Hi" and "Hello World!" respectively, sets the bot's current activity to 'Watching if i work', and sets the presence to online since the program was started.
13
+ You may also submit questions or discussions to the same above email. Configure your email client to send emails in plain text format: <https://useplaintext.email/>
23
14
 
24
- > [!NOTE]
25
- > You will need to fill out the required data in `env.rb.template` and rename it to `env.rb` before running `test.rb`.
15
+ Submit issues, feature requests and enhancements to <https://todo.sr.ht/~hoovad/disrb>.
26
16
 
27
17
  ## How to use this project
28
18
 
@@ -32,7 +22,6 @@ Most functions in this library return a `Faraday::Response` object. Check the [F
32
22
 
33
23
  If you want to get the contents of the response, use the `body` instance method (example: `[Faraday::Response object here].body`). The contents will most likely be JSON. To convert it to a Ruby object, use `JSON.parse([Faraday::Response object here].body)` (with `require 'json'` of course).
34
24
 
35
- > [!TIP]
36
25
  > When reading the documentation, there most likely will be a link to the relevant Discord Developer Documentation page. Please read that page as well, it will contain information that may help you.
37
26
 
38
27
  ## Roadmap
@@ -47,7 +36,7 @@ If you want to get the contents of the response, use the `body` instance method
47
36
  - [ ] Alpha release (v0.2.0)
48
37
  - [ ] Add support for all Discord API endpoints (v0.2.0)
49
38
  - [ ] Add support for all Discord Gateway events and properly handle the connection (v0.1.5)
50
- - [ ] Add support for uploading files (v0.1.4)
39
+ - [x] Add support for uploading files (v0.1.4)
51
40
  - [x] Documentation (v0.1.3)
52
41
  - [x] Full message resource support (v0.1.2)
53
42
  - [x] Transition to Faraday for HTTP requests (v0.1.1)
@@ -59,4 +48,18 @@ If you want to get the contents of the response, use the `body` instance method
59
48
  - [ ] Add parameter validation
60
49
  - [ ] Stable release (v1.0.0)
61
50
  - [ ] Return classes instead of `Faraday::Response` objects
62
- - [ ] Bugfixes, consistency and improvements
51
+ - [ ] Bugfixes, consistency and improvements
52
+
53
+ ## Examples
54
+
55
+ > You will need to create a Discord bot and fill out the required data in `env.rb.template` and rename it to `env.rb` before running any examples.
56
+
57
+ Currently the only example program can be found at [examples/test.rb](examples/test.rb), and it does the following:
58
+
59
+ - Creates three commands:
60
+ - "test", bot responds with "Hi!"
61
+ - "test2", bot responds with "Hello World!"
62
+ - "file", bot responds with a file containing "Hello World in a file!"
63
+ - Sets the bot's current activity to "Watching if i work"
64
+ - Bot's presence to online since program start
65
+ - Reply to a message mentioning the bot with "pong"
data/lib/disrb/message.rb CHANGED
@@ -115,7 +115,7 @@ class DiscordApi
115
115
  data = JSON.generate(output)
116
116
  headers = { 'Authorization': @authorization_header }
117
117
  if files
118
- response = file_upload(url, files, data, headers)
118
+ response = file_upload(url, files, payload_json: data, headers: headers)
119
119
  else
120
120
  headers['Content-Type'] = 'application/json'
121
121
  response = post(url, data, headers)
@@ -272,7 +272,7 @@ class DiscordApi
272
272
  components: nil, files: nil, attachments: nil)
273
273
  if args[2..].all?(&:nil?)
274
274
  @logger.warn("No modifications provided for message with ID #{message_id} in channel with ID #{channel_id}. " \
275
- 'Only modifying Skipping function.')
275
+ 'Skipping function.')
276
276
  return
277
277
  end
278
278
  output = {}
@@ -289,7 +289,12 @@ class DiscordApi
289
289
  url = "#{@base_url}/channels/#{channel_id}/messages/#{message_id}"
290
290
  data = JSON.generate(output)
291
291
  headers = { 'Authorization': @authorization_header, 'Content-Type': 'application/json' }
292
- response = patch(url, data, headers)
292
+ if files
293
+ response = file_upload(url, files, headers: headers, payload_json: data, request_type: :patch)
294
+ else
295
+ headers['Content-Type'] = 'application/json'
296
+ response = patch(url, data, headers)
297
+ end
293
298
  return response if response.is_a?(Faraday::Response) && response.status == 200
294
299
 
295
300
  @logger.error("Failed to edit message with ID #{message_id} in channel with ID #{channel_id}. " \
data/lib/disrb.rb CHANGED
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'json'
4
+ require 'uri'
4
5
  require 'async'
5
6
  require 'async/http/endpoint'
6
7
  require 'async/websocket/client'
@@ -50,7 +51,6 @@ class Snowflake
50
51
  end
51
52
 
52
53
  # Class that contains functions that allow interacting with the Discord API.
53
- # @version 0.1.4
54
54
  class DiscordApi
55
55
  # @!attribute [r] base_url
56
56
  # @return [String] the base URL that is used to access the Discord API. ex: "https://discord.com/api/v10"
@@ -67,7 +67,7 @@ class DiscordApi
67
67
  # @param verbosity_level [String, Integer, nil] The verbosity level of the logger.
68
68
  # @param user_agent [String, nil] When sending a request to Discord's HTTP API, a valid User-Agent header must be set.
69
69
  # By setting this parameter, the value of the User-Agent header sent will be equal to the value of this parameter.
70
- # Defaults to 'discord.rb (https://github.com/hoovad/discord.rb, [discord.rb version])'
70
+ # Defaults to 'disrb (https://sr.ht/~hoovad/disrb/, [disrb version])'
71
71
  # Set verbosity_level to:
72
72
  # - 'all' or 5 to log all of the below plus debug messages
73
73
  # - 'info', 4 or nil to log all of the below plus info messages [DEFAULT]
@@ -114,7 +114,7 @@ class DiscordApi
114
114
  @verbosity_level = 4
115
115
  end
116
116
  @logger = Logger2.new(@verbosity_level)
117
- default_user_agent = "discord.rb (https://github.com/hoovad/discord.rb, #{DiscordApi::VERSION})"
117
+ default_user_agent = "disrb (https://sr.ht/~hoovad/disrb/, #{DiscordApi::VERSION})"
118
118
  if user_agent.is_a?(String) && !user_agent.empty?
119
119
  @user_agent = user_agent
120
120
  elsif user_agent.nil?
@@ -126,7 +126,7 @@ class DiscordApi
126
126
  end
127
127
  url = "#{@base_url}/applications/@me"
128
128
  headers = { 'Authorization': @authorization_header }
129
- response = DiscordApi.get(url, headers)
129
+ response = get(url, headers)
130
130
  if response.is_a?(Faraday::Response) && response.status == 200
131
131
  @application_id = JSON.parse(response.body)['id']
132
132
  else
@@ -164,8 +164,8 @@ class DiscordApi
164
164
  # https://discord.com/developers/docs/topics/gateway#resume
165
165
  # @param activities [Hash, Array, nil] Activity or list of activities to set in presence.
166
166
  # @param os [String, nil] OS name reported to the Gateway. Host OS if nil.
167
- # @param browser [String, nil] Browser/client name reported to the Gateway. "discord.rb" if nil.
168
- # @param device [String, nil] Device name reported to the Gateway. "discord.rb" if nil
167
+ # @param browser [String, nil] Browser/client name reported to the Gateway. "disrb" if nil.
168
+ # @param device [String, nil] Device name reported to the Gateway. "disrb" if nil
169
169
  # @param intents [Integer, nil] Bitwise Gateway intents integer.
170
170
  # @param presence_since [Integer, TrueClass, nil] Unix ms timestamp or true for since value in presence.
171
171
  # @param presence_status [String, nil] Presence status (e.g., "online", "idle", "dnd").
@@ -224,11 +224,11 @@ class DiscordApi
224
224
  os = nil
225
225
  end
226
226
  unless browser.is_a?(String) || browser.nil?
227
- @logger.error("Invalid browser: #{browser}. Expected a String. Defaulting to 'discord.rb'.")
227
+ @logger.error("Invalid browser: #{browser}. Expected a String. Defaulting to 'disrb'.")
228
228
  browser = nil
229
229
  end
230
230
  unless device.is_a?(String) || device.nil?
231
- @logger.error("Invalid device: #{device}. Expected a String. Defaulting to 'discord.rb'.")
231
+ @logger.error("Invalid device: #{device}. Expected a String. Defaulting to 'disrb'.")
232
232
  device = nil
233
233
  end
234
234
  unless (intents.is_a?(Integer) && intents >= 0 && intents <= 131_071) || intents.nil?
@@ -253,7 +253,7 @@ class DiscordApi
253
253
  loop do
254
254
  recieved_ready = false
255
255
  url = if rescue_connection.nil?
256
- response = DiscordApi.get("#{@base_url}/gateway")
256
+ response = get("#{@base_url}/gateway")
257
257
  if response.is_a?(Faraday::Response) && response.status == 200
258
258
  "#{JSON.parse(response.body)['url']}/?v=#{@api_version}&encoding=json"
259
259
  else
@@ -273,8 +273,8 @@ class DiscordApi
273
273
  identify[:d][:intents] = intents || 513
274
274
  identify[:d][:properties] = {}
275
275
  identify[:d][:properties][:os] = os || RbConfig::CONFIG['host_os']
276
- identify[:d][:properties][:browser] = browser || 'discord.rb'
277
- identify[:d][:properties][:device] = device || 'discord.rb'
276
+ identify[:d][:properties][:browser] = browser || 'disrb'
277
+ identify[:d][:properties][:device] = device || 'disrb'
278
278
  if !activities.nil? || !presence_since.nil? || !presence_status.nil? || !presence_afk.nil?
279
279
  identify[:d][:presence] = {}
280
280
  identify[:d][:presence][:activities] = activities unless activities.nil?
@@ -369,15 +369,21 @@ class DiscordApi
369
369
  # @param interaction [Hash] The interaction payload received from the Gateway.
370
370
  # @param response [Hash] The interaction response payload.
371
371
  # @param with_response [TrueClass, FalseClass] Whether to request the created message in the response.
372
+ # @param files [Array] An array of arrays, each inner-array first has its filename (index 0),
373
+ # raw file data as a string (index 1), and then the MIME type of the file (index 2).
372
374
  # @return [Faraday::Response] The response from the Discord API.
373
- def respond_interaction(interaction, response, with_response: false)
375
+ def respond_interaction(interaction, response, with_response: false, files: nil)
374
376
  query_string_hash = {}
375
377
  query_string_hash[:with_response] = with_response
376
378
  query_string = DiscordApi.handle_query_strings(query_string_hash)
377
379
  url = "#{@base_url}/interactions/#{interaction[:d][:id]}/#{interaction[:d][:token]}/callback#{query_string}"
378
380
  data = JSON.generate(response)
379
- headers = { 'content-type': 'application/json' }
380
- response = DiscordApi.post(url, data, headers)
381
+ if files
382
+ response = file_upload(url, files, payload_json: data)
383
+ else
384
+ headers = { 'Content-Type' => 'application/json' }
385
+ response = post(url, data, headers)
386
+ end
381
387
  return response if response.is_a?(Faraday::Response) &&
382
388
  ((response.status == 204 && !with_response) || (response.status == 200 && with_response))
383
389
 
@@ -508,18 +514,37 @@ class DiscordApi
508
514
  'Empty'
509
515
  end
510
516
 
517
+ # Parses a full URL and returns connection host and request path.
518
+ # @param url [String] Full URL.
519
+ # @param method_name [String] HTTP method name used for logging context.
520
+ # @return [Hash, nil] { host:, path: } or nil if URL is invalid.
521
+ def parse_request_url(url, method_name)
522
+ begin
523
+ uri = URI.parse(url.to_s)
524
+ rescue URI::InvalidURIError
525
+ @logger.error("Empty/invalid URL provided: #{url}. Cannot perform #{method_name} request.")
526
+ return nil
527
+ end
528
+ if uri.scheme.nil? || uri.host.nil?
529
+ @logger.error("Empty/invalid URL provided: #{url}. Cannot perform #{method_name} request.")
530
+ return nil
531
+ end
532
+
533
+ host = "#{uri.scheme}://#{uri.host}"
534
+ host = "#{host}:#{uri.port}" if uri.port && uri.port != uri.default_port
535
+ { host: host, path: uri.request_uri }
536
+ end
537
+
511
538
  # Performs an HTTP GET request using Faraday.
512
539
  # @param url [String] Full URL including scheme and host; path may be included.
513
540
  # @param headers [Hash, nil] Optional request headers.
514
541
  # @return [Faraday::Response, nil] The Faraday response object, or nil if an error was encountered.
515
542
  def get(url, headers = nil)
516
- split_url = url.split(%r{(http[^/]+)(/.*)}).reject(&:empty?)
517
- if split_url.empty?
518
- @logger.error("Empty/invalid URL provided: #{url}. Cannot perform GET request.")
519
- return
520
- end
521
- host = split_url[0]
522
- path = split_url[1] if split_url[1]
543
+ parsed_url = parse_request_url(url, 'GET')
544
+ return if parsed_url.nil?
545
+
546
+ host = parsed_url[:host]
547
+ path = parsed_url[:path]
523
548
  if headers.is_a?(Hash)
524
549
  headers['User-Agent'] = @user_agent
525
550
  elsif headers.nil?
@@ -529,11 +554,7 @@ class DiscordApi
529
554
  headers = { 'User-Agent' => @user_agent }
530
555
  end
531
556
  conn = Faraday.new(url: host, headers: headers)
532
- if path
533
- conn.get(path)
534
- else
535
- conn.get
536
- end
557
+ conn.get(path)
537
558
  end
538
559
 
539
560
  # Performs an HTTP DELETE request using Faraday.
@@ -541,13 +562,11 @@ class DiscordApi
541
562
  # @param headers [Hash, nil] Optional request headers.
542
563
  # @return [Faraday::Response, nil] The Faraday response object, or nil if an error was encountered.
543
564
  def delete(url, headers = nil)
544
- split_url = url.split(%r{(http[^/]+)(/.*)}).reject(&:empty?)
545
- if split_url.empty?
546
- @logger.error("Empty/invalid URL provided: #{url}. Cannot perform DELETE request.")
547
- return
548
- end
549
- host = split_url[0]
550
- path = split_url[1] if split_url[1]
565
+ parsed_url = parse_request_url(url, 'DELETE')
566
+ return if parsed_url.nil?
567
+
568
+ host = parsed_url[:host]
569
+ path = parsed_url[:path]
551
570
  if headers.is_a?(Hash)
552
571
  headers['User-Agent'] = @user_agent
553
572
  elsif headers.nil?
@@ -557,11 +576,7 @@ class DiscordApi
557
576
  headers = { 'User-Agent' => @user_agent }
558
577
  end
559
578
  conn = Faraday.new(url: host, headers: headers)
560
- if path
561
- conn.delete(path)
562
- else
563
- conn.delete
564
- end
579
+ conn.delete(path)
565
580
  end
566
581
 
567
582
  # Performs an HTTP POST request using Faraday.
@@ -570,13 +585,11 @@ class DiscordApi
570
585
  # @param headers [Hash, nil] Optional request headers.
571
586
  # @return [Faraday::Response, nil] The Faraday response object, or nil if an error was encountered.
572
587
  def post(url, data, headers = nil)
573
- split_url = url.split(%r{(http[^/]+)(/.*)}).reject(&:empty?)
574
- if split_url.empty?
575
- @logger.error("Empty/invalid URL provided: #{url}. Cannot perform POST request.")
576
- return
577
- end
578
- host = split_url[0]
579
- path = split_url[1] if split_url[1]
588
+ parsed_url = parse_request_url(url, 'POST')
589
+ return if parsed_url.nil?
590
+
591
+ host = parsed_url[:host]
592
+ path = parsed_url[:path]
580
593
  if headers.is_a?(Hash)
581
594
  headers['User-Agent'] = @user_agent
582
595
  elsif headers.nil?
@@ -586,11 +599,7 @@ class DiscordApi
586
599
  headers = { 'User-Agent' => @user_agent }
587
600
  end
588
601
  conn = Faraday.new(url: host, headers: headers)
589
- if path
590
- conn.post(path, data)
591
- else
592
- conn.post('', data)
593
- end
602
+ conn.post(path, data)
594
603
  end
595
604
 
596
605
  # Performs an HTTP PATCH request using Faraday.
@@ -599,13 +608,11 @@ class DiscordApi
599
608
  # @param headers [Hash, nil] Optional request headers.
600
609
  # @return [Faraday::Response, nil] The Faraday response object, or nil if an error was encountered.
601
610
  def patch(url, data, headers = nil)
602
- split_url = url.split(%r{(http[^/]+)(/.*)}).reject(&:empty?)
603
- if split_url.empty?
604
- @logger.error("Empty/invalid URL provided: #{url}. Cannot perform PATCH request.")
605
- return
606
- end
607
- host = split_url[0]
608
- path = split_url[1] if split_url[1]
611
+ parsed_url = parse_request_url(url, 'PATCH')
612
+ return if parsed_url.nil?
613
+
614
+ host = parsed_url[:host]
615
+ path = parsed_url[:path]
609
616
  if headers.is_a?(Hash)
610
617
  headers['User-Agent'] = @user_agent
611
618
  elsif headers.nil?
@@ -615,11 +622,7 @@ class DiscordApi
615
622
  headers = { 'User-Agent' => @user_agent }
616
623
  end
617
624
  conn = Faraday.new(url: host, headers: headers)
618
- if path
619
- conn.patch(path, data)
620
- else
621
- conn.patch('', data)
622
- end
625
+ conn.patch(path, data)
623
626
  end
624
627
 
625
628
  # Performs an HTTP PUT request using Faraday.
@@ -628,13 +631,11 @@ class DiscordApi
628
631
  # @param headers [Hash, nil] Optional request headers.
629
632
  # @return [Faraday::Response, nil] The Faraday response object, or nil if an error was encountered.
630
633
  def put(url, data, headers = nil)
631
- split_url = url.split(%r{(http[^/]+)(/.*)}).reject(&:empty?)
632
- if split_url.empty?
633
- @logger.error("Empty/invalid URL provided: #{url}. Cannot perform PUT request.")
634
- return
635
- end
636
- host = split_url[0]
637
- path = split_url[1] if split_url[1]
634
+ parsed_url = parse_request_url(url, 'PUT')
635
+ return if parsed_url.nil?
636
+
637
+ host = parsed_url[:host]
638
+ path = parsed_url[:path]
638
639
  if headers.is_a?(Hash)
639
640
  headers['User-Agent'] = @user_agent
640
641
  elsif headers.nil?
@@ -644,14 +645,10 @@ class DiscordApi
644
645
  headers = { 'User-Agent' => @user_agent }
645
646
  end
646
647
  conn = Faraday.new(url: host, headers: headers)
647
- if path
648
- conn.put(path, data)
649
- else
650
- conn.put('', data)
651
- end
648
+ conn.put(path, data)
652
649
  end
653
650
 
654
- # Sends a HTTP POST request to the specified URL, containing multipart/form-data data structured
651
+ # Sends a HTTP POST/PATCH request to the specified URL, containing multipart/form-data data structured
655
652
  # according to Discord documentation.
656
653
  # See https://docs.discord.com/developers/reference#uploading-files
657
654
  # @param url [String] Full URL including scheme and host; path may be included.
@@ -660,15 +657,14 @@ class DiscordApi
660
657
  # @param files [Array] An array of arrays, each inner-array first has its filename (index 0),
661
658
  # raw file data as a string (index 1), and then the MIME type of the file (index 2).
662
659
  # @param headers [Hash, nil] Optional request headers.
660
+ # @param request_type [Symbol, nil] Specify whether to make a POST (:post) or PATCH (:patch) request. POST by default.
663
661
  # @return [Faraday::Response, nil] The Faraday response object, or nil if an error was encountered.
664
- def file_upload(url, files, payload_json: nil, headers: nil)
665
- split_url = url.split(%r{(http[^/]+)(/.*)}).reject(&:empty?)
666
- if split_url.empty?
667
- @logger.error("Empty/invalid URL provided: #{url}. Cannot perform Discord multipart/form-data POST request.")
668
- return
669
- end
670
- host = split_url[0]
671
- path = split_url[1] if split_url[1]
662
+ def file_upload(url, files, payload_json: nil, headers: nil, request_type: :post)
663
+ parsed_url = parse_request_url(url, 'multipart/form-data')
664
+ return if parsed_url.nil?
665
+
666
+ host = parsed_url[:host]
667
+ path = parsed_url[:path]
672
668
  if headers.is_a?(Hash)
673
669
  headers['User-Agent'] = @user_agent
674
670
  elsif headers.nil?
@@ -677,35 +673,28 @@ class DiscordApi
677
673
  @logger.warn('Invalid headers parameter. It will be discarded.')
678
674
  headers = { 'User-Agent' => @user_agent }
679
675
  end
680
- conn = Faraday.new(url: host, headers: headers, request: :multipart, content_type: 'multipart/form-data')
681
- payload = {}
682
- # FilePart expects File/IO objects as the first argument.
683
- # However, since the function is being given raw data instead of File/IO objects, we should be using ParamPart
684
- # But, ParamPart doesn't let us use a customized Content-Disposition, which is what we need
685
- # So we will just have to wrap the raw data in an IO class with StringIO
686
- if payload_json
687
- payload[:payload_json] = Faraday::Multipart::FilePart.new(
688
- StringIO.new(payload_json),
689
- 'application/json',
690
- nil,
691
- 'Content-Disposition' => 'form-data; name="payload_json"'
692
- )
676
+ conn = Faraday.new(url: host, headers: headers) do |faraday|
677
+ faraday.request :multipart
693
678
  end
679
+ payload = {}
680
+ payload['payload_json'] = Faraday::Multipart::ParamPart.new(payload_json, 'application/json') if payload_json
694
681
  files.each_with_index do |(filename, raw_bytes, mime_type), i|
695
- payload[:"file_#{i}"] = Faraday::Multipart::FilePart.new(
682
+ payload["files[#{i}]"] = Faraday::Multipart::FilePart.new(
696
683
  StringIO.new(raw_bytes),
697
684
  mime_type,
698
- filename,
699
- 'Content-Disposition' => "form-data; name=\"files[#{i}]\"; filename=\"#{filename}\""
685
+ filename
700
686
  )
701
687
  end
702
688
  if payload.empty?
703
689
  @logger.warn("Payload empty, not sending Discord multipart/form-data POST request to #{url}.")
704
690
  nil
705
- elsif path
706
- conn.post(path, payload)
707
691
  else
708
- conn.post('', payload)
692
+ case request_type
693
+ when :post
694
+ conn.post(path, payload)
695
+ when :patch
696
+ conn.patch(path, payload)
697
+ end
709
698
  end
710
699
  end
711
700
 
data/lib/version.rb CHANGED
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ # @version 0.1.4.2
3
4
  class DiscordApi
4
- VERSION = '0.1.3'
5
+ VERSION = '0.1.4.2'
5
6
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: disrb
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.4
4
+ version: 0.1.4.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - hoovad
@@ -121,16 +121,18 @@ dependencies:
121
121
  - - ">="
122
122
  - !ruby/object:Gem::Version
123
123
  version: 0.26.0
124
- description: Discord.rb (not to be confused with discordrb) is a Ruby library that
125
- allows you to interact only with the Discord API. The library is still in development,
126
- but really simple tasks can be done.
127
- email: hoovad@proton.me
124
+ description: disrb is a Ruby library that allows you to interact with the Discord
125
+ API.
126
+ email: hoovad@purelymail.com
128
127
  executables: []
129
128
  extensions: []
130
129
  extra_rdoc_files: []
131
130
  files:
132
131
  - CHANGELOG.md
133
132
  - LICENSE
133
+ - LICENSES/ISC.txt
134
+ - LICENSES/MIT.txt
135
+ - LICENSES/Unlicense.txt
134
136
  - README.md
135
137
  - lib/disrb.rb
136
138
  - lib/disrb/application_commands.rb
@@ -139,9 +141,11 @@ files:
139
141
  - lib/disrb/message.rb
140
142
  - lib/disrb/user.rb
141
143
  - lib/version.rb
142
- homepage: https://github.com/hoovad/discord.rb
144
+ homepage: https://sr.ht/~hoovad/disrb/
143
145
  licenses:
146
+ - Unlicense
144
147
  - MIT
148
+ - ISC
145
149
  metadata: {}
146
150
  rdoc_options: []
147
151
  require_paths: