@jnode/discord 1.0.7 → 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 +181 -0
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,2 +1,183 @@
1
1
  # JustDiscord
2
+
2
3
  Simple Discord API package for Node.js.
4
+
5
+ ```shell
6
+ npm install @jnode/discord
7
+ ```
8
+
9
+ ## Basic Usage
10
+
11
+ ### Import JustDiscord
12
+ ```js
13
+ const discord = require('@jnode/discord');
14
+ ```
15
+
16
+ ### Create a Client
17
+ ```js
18
+ const client = new discord.Client('BOT_TOKEN');
19
+ ```
20
+
21
+ ### Connect to Discord Gateway
22
+ ```js
23
+ client.connectGateway((gateway) => {
24
+ // receive Discord gateway "READY" event
25
+ gateway.on('READY', (d) => {
26
+ console.log('Connected to Discord.');
27
+ });
28
+ });
29
+ ```
30
+
31
+ ## Class: `Client`
32
+
33
+ The main class for interacting with the Discord API and Gateway.
34
+
35
+ ### Constructor
36
+ ```js
37
+ new discord.Client(token, options = {})
38
+ ```
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`.
50
+
51
+ ### Methods
52
+
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
+ ```
124
+
125
+ ## Class: `Gateway`
126
+
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).
128
+
129
+ ### Events
130
+
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.
142
+
143
+ ### Methods
144
+
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
+ ```
166
+
167
+ ## Class: `DiscordAPIError`
168
+
169
+ An error that is thrown when the Discord API returns a non-2xx status code.
170
+
171
+ ### Properties
172
+
173
+ - `message`: The error message.
174
+ - `body`: The response body.
175
+ - `headers`: The response headers.
176
+
177
+ ## Helper functions
178
+
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.7",
3
+ "version": "1.0.9",
4
4
  "description": "Simple Discord API package for Node.js.",
5
5
  "main": "src/index.js",
6
6
  "scripts": {