@jnode/discord 1.0.8 → 1.0.9

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.
Files changed (2) hide show
  1. package/README.md +141 -77
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -6,16 +6,20 @@ Simple Discord API package for Node.js.
6
6
  npm install @jnode/discord
7
7
  ```
8
8
 
9
- ## Basic usage
9
+ ## Basic Usage
10
10
 
11
+ ### Import JustDiscord
11
12
  ```js
12
- // import JustDiscord
13
13
  const discord = require('@jnode/discord');
14
+ ```
14
15
 
15
- // create a client
16
- const client = new discord.Client('YOUR_BOT_TOKEN');
16
+ ### Create a Client
17
+ ```js
18
+ const client = new discord.Client('BOT_TOKEN');
19
+ ```
17
20
 
18
- // connect to Discord gateway
21
+ ### Connect to Discord Gateway
22
+ ```js
19
23
  client.connectGateway((gateway) => {
20
24
  // receive Discord gateway "READY" event
21
25
  gateway.on('READY', (d) => {
@@ -24,96 +28,156 @@ client.connectGateway((gateway) => {
24
28
  });
25
29
  ```
26
30
 
27
- ## DiscordClient
31
+ ## Class: `Client`
28
32
 
29
- ### Constructor
33
+ The main class for interacting with the Discord API and Gateway.
30
34
 
35
+ ### Constructor
31
36
  ```js
32
- constructor(token, options = {})
37
+ new discord.Client(token, options = {})
33
38
  ```
34
-
35
- * `token`: Your Discord bot token.
36
- * `options`: An object containing client options.
37
- * `apiVersion`: The Discord API version to use. (default: `10`)
38
- * `apiBase`: The base URL for the Discord API. (default: `'discord.com/api'`)
39
- * `apiAutoRetry`: Whether to automatically retry requests when receiving a 429 status code. (default: `true`)
40
- * `apiThrowError`: Whether to throw an error when an API request returns a status code outside of the 2xx range. (default: `true`)
41
- * `gatewayIntents`: The gateway intents to use. (default: `0b11111111111111111000110011`)
42
- * `gatewayUrl`: The URL for the Discord gateway. (default: `'wss://gateway.discord.gg'`)
43
- * `gatewayReconnectDelay`: The delay in milliseconds before attempting to reconnect to the gateway. (default: `5000`)
44
- * `gatewayConnectTimeout`: The timeout in milliseconds for the gateway connection. (default: `5000`)
45
- * `gatewayThrowError`: Whether to throw an error when the gateway encounters an issue. (default: `true`)
39
+ - `token`: Your Discord bot token.
40
+ - `options`: An optional object for setting various client options:
41
+ - `apiVersion`: The Discord API version. Default is `10`.
42
+ - `apiBase`: The base URL of the Discord API. Default is `discord.com/api`.
43
+ - `apiAutoRetry`: Whether to auto-retry requests when receiving a 429 error. Default is `true`.
44
+ - `apiThrowError`: Whether to throw errors when the API status code is not 2xx. Default is `true`.
45
+ - `gatewayIntents`: The gateway intents used for connecting to the Gateway. Default is `0b11111111111111111000110011`. You can find more about intents in the [Discord Developer Documentation](https://discord.com/developers/docs/events/gateway).
46
+ - `gatewayUrl`: The base URL for the Discord Gateway. Default is `wss://gateway.discord.gg`.
47
+ - `gatewayReconnectDelay`: The delay (in milliseconds) before attempting to reconnect to the gateway. Default is `5000`. Set to less than 0 to disable auto-reconnect.
48
+ - `gatewayConnectTimeout`: The timeout (in milliseconds) before giving up on connecting to the gateway. Default is `5000`. Set to less than 0 to disable connect timeout.
49
+ - `gatewayThrowError`: Whether to throw errors when the gateway encounters an issue. Default is `true`.
46
50
 
47
51
  ### Methods
48
52
 
49
- #### `apiUrl(path)`
50
-
51
- Returns the full API URL with the base, version, and provided path.
52
-
53
- * `path`: The API endpoint path.
54
-
55
- #### `async apiRequest(method = 'GET', path = '/', body)`
56
-
57
- Makes a request to the Discord API.
58
-
59
- * `method`: The HTTP method (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`). (default: `'GET'`)
60
- * `path`: The API endpoint path. (default: `'/'`)
61
- * `body`: The request body (will be stringified to JSON). (optional)
62
-
63
- #### `async apiRequestMultipart(method = 'GET', path = '/', body, attachments = [])`
64
-
65
- Makes a multipart request to the Discord API.
66
-
67
- * `method`: The HTTP method (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`). (default: `'GET'`)
68
- * `path`: The API endpoint path. (default: `'/'`)
69
- * `body`: The request body (will be stringified to JSON).
70
- * `attachments`: An array of attachment objects. Each attachment object should have the following properties:
71
- * `name`: The file name.
72
- * `type`: The content type of the file.
73
- * `data`: The file data (Buffer or Uint8Array).
74
- * `encoded`: Boolean, should be true if the data has already been encoded.
75
-
76
- #### `async connectGateway(cb)`
77
-
78
- Connects to the Discord gateway.
53
+ - `apiUrl(path)`: Returns the full API URL with the base, version, and given path.
54
+ - `path`: API endpoint path. Example: `/channels/123456789`.
55
+ - **Returns**: `string` - The full API URL. Example: `https://discord.com/api/v10/channels/123456789`.
56
+
57
+ - `async apiRequest(method = 'GET', path = '/', body)`: Makes an HTTP request to the Discord API, find out more at [Discord Developer Documentation](https://discord.com/developers/docs).
58
+ - `method`: HTTP method (e.g. `GET`, `POST`, `PUT`, `DELETE`). Default is `GET`.
59
+ - `path`: API endpoint path. Default is `/`. Example: `/channels/123456789/messages`.
60
+ - `body`: Request body data (will be stringified). Example: `{ content: 'Hello, Discord!' }`.
61
+ - **Returns**: `Promise<RequestResponse>` - A promise that resolves to a `RequestResponse` object.
62
+ - **Example**:
63
+ ```js
64
+ client.apiRequest('POST', '/channels/123456789/messages', { content: 'Hello, Discord!' })
65
+ .then(res => {
66
+ if (res.statusCode === 200) {
67
+ console.log('Message sent successfully!');
68
+ } else {
69
+ console.error('Failed to send message:', res.statusCode, res.text());
70
+ }
71
+ }).catch(err => {
72
+ console.error('Error sending message:', err);
73
+ });
74
+ ```
75
+
76
+ - `async apiRequestMultipart(method = 'GET', path = '/', body, attachments = [])`: Makes a multipart HTTP request to the Discord API.
77
+ - `method`: HTTP method (e.g. `GET`, `POST`, `PUT`, `DELETE`). Default is `GET`.
78
+ - `path`: API endpoint path. Default is `/`. Example: `/channels/123456789/messages`.
79
+ - `body`: Request body data (will be stringified). Example: `{ content: 'Hello, Discord!' }`.
80
+ - `attachments`: An array of attachments, each attachment is an object like: `{ name: 'file.png', type: 'image/png', data: Buffer, encoded: base64 or undefined }`.
81
+ - **Returns**: `Promise<RequestResponse>` - A promise that resolves to a `RequestResponse` object.
82
+ - **Example**:
83
+ ```js
84
+ const fs = require('fs').promises;
85
+
86
+ async function uploadFile(channelId, filePath) {
87
+ const fileData = await fs.readFile(filePath);
88
+ const fileType = 'image/png';
89
+ const fileName = 'my_image.png';
90
+
91
+ client.apiRequestMultipart('POST', `/channels/${channelId}/messages`, { content: 'Here\'s an image!' }, [{
92
+ name: fileName,
93
+ type: fileType,
94
+ data: fileData
95
+ }]).then(res => {
96
+ if (res.statusCode === 200) {
97
+ console.log('File uploaded successfully!');
98
+ } else {
99
+ console.error('Failed to upload file:', res.statusCode, res.text());
100
+ }
101
+ }).catch(err => {
102
+ console.error('Error uploading file:', err);
103
+ });
104
+ }
105
+ uploadFile('123456789', './my_image.png');
106
+ ```
107
+
108
+ - `async connectGateway(cb)`: Connects to the Discord Gateway.
109
+ - `cb`: A callback function that takes a `gateway` object as an argument.
110
+ - **Returns**: `Promise<Gateway>` - A promise that resolves to a `Gateway` object.
111
+ - **Example**:
112
+ ```js
113
+ client.connectGateway((gateway) => {
114
+ gateway.on('READY', (data) => {
115
+ console.log('Connected to Discord, user id:', data.user.id);
116
+ });
117
+ gateway.on('MESSAGE_CREATE', (message) => {
118
+ if (message.content === '!ping') {
119
+ console.log('Recieve Ping Message')
120
+ }
121
+ });
122
+ });
123
+ ```
79
124
 
80
- * `cb`: A callback function that will be called with the `DiscordGateway` instance.
125
+ ## Class: `Gateway`
81
126
 
82
- ## DiscordGateway
127
+ Manages the Discord Gateway connection for receiving real-time events. You can find more about gateway events in the [Discord Developer Documentation](https://discord.com/developers/docs/events/gateway).
83
128
 
84
129
  ### Events
85
130
 
86
- * `socketOpened`: Emitted when the WebSocket connection is opened.
87
- * `socketClosed`: Emitted when the WebSocket connection is closed.
88
- * `socketError`: Emitted when an error occurs with the WebSocket connection.
89
- * `socketMessage`: Emitted when a message is received from the WebSocket.
90
- * `message`: Emitted when a message with json data is received from the WebSocket.
91
- * `READY`: Emitted when the gateway sends a `READY` event.
92
- * Other events may be emitted depending on the received `t` value, such as `MESSAGE_CREATE`, `GUILD_CREATE`.
131
+ - `socketOpened`: Emitted when the WebSocket connection is opened.
132
+ - `event`: A WebSocket event object.
133
+ - `socketClosed`: Emitted when the WebSocket connection is closed.
134
+ - `event`: A WebSocket event object.
135
+ - `socketError`: Emitted when a WebSocket error occurs.
136
+ - `event`: A WebSocket event object.
137
+ - `socketMessage`: Emitted when a raw WebSocket message is received.
138
+ - `event`: A WebSocket event object.
139
+ - `message`: Emitted when a complete JSON payload is received.
140
+ - `data`: A JSON object.
141
+ - Discord Gateway Event (`READY`, `MESSAGE_CREATE`... etc.): The gateway will auto dispatch discord events. Check [Discord Developer Documentation](https://discord.com/developers/docs/events/gateway-events) for all avaliable events. The event callback will be a data object from discord.
93
142
 
94
143
  ### Methods
95
144
 
96
- #### `async getGatewayUrl()`
97
-
98
- Gets the gateway URL from the Discord API.
99
-
100
- #### `connect()`
101
-
102
- Connects to the Discord gateway.
103
-
104
- #### `sendMessage(op, d = null)`
145
+ - `async getGatewayUrl()`: Retrieves the gateway URL from the Discord API.
146
+ - **Returns**: `Promise<string>` - A promise that resolves to the gateway URL.
147
+
148
+ - `connect()`: Opens the WebSocket connection to the Discord Gateway.
149
+
150
+ - `sendMessage(op, d = null)`: Sends a message to the Discord Gateway.
151
+ - `op`: Opcode of the message. Check [Discord Developer Documentation](https://discord.com/developers/docs/events/gateway-events) for all avaliable opcodes.
152
+ - `d`: Payload of the message.
153
+ - **Example**:
154
+ ```js
155
+ gateway.sendMessage(1, {}); //send heartbeat
156
+ gateway.sendMessage(2, { //Identify
157
+ token: 'BOT_TOKEN',
158
+ properties: {
159
+ os: process.platform,
160
+ browser: 'Node.js',
161
+ device: 'JustDiscord'
162
+ },
163
+ intents: 0b11111111111111111000110011 //replace with your intents
164
+ });
165
+ ```
105
166
 
106
- Sends a message to the Discord gateway.
167
+ ## Class: `DiscordAPIError`
107
168
 
108
- * `op`: The opcode of the message.
109
- * `d`: The data of the message. (optional)
169
+ An error that is thrown when the Discord API returns a non-2xx status code.
110
170
 
111
- ## Errors
171
+ ### Properties
112
172
 
113
- ### DiscordAPIError
173
+ - `message`: The error message.
174
+ - `body`: The response body.
175
+ - `headers`: The response headers.
114
176
 
115
- Thrown when an API request returns a status code outside of the 2xx range.
177
+ ## Helper functions
116
178
 
117
- * `code`: The HTTP status code.
118
- * `body`: The response body.
119
- * `headers`: The response headers.
179
+ - `RequestResponse` class with properties like:
180
+ - `statusCode`: Status code.
181
+ - `headers`: Response headers.
182
+ - `text(encoding)`: Return response body in string, with optional encoding. Example: `res.text('utf-8')`.
183
+ - `json()`: Return response body in JSON format, or `undefined` when cannot parse JSON. Example: `res.json()`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jnode/discord",
3
- "version": "1.0.8",
3
+ "version": "1.0.9",
4
4
  "description": "Simple Discord API package for Node.js.",
5
5
  "main": "src/index.js",
6
6
  "scripts": {