-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
269 lines (246 loc) · 8.82 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import * as Common from './common';
import WebSocket from 'ws';
import EventEmitter from 'node:events';
/*eslint-disable */
// ts wont shut up if I put any type other than "any" for this or the messageHandlers. maybe theres a way to fix this, but I don't know it.
function getEnumKeyByEnumValue(myEnum: any, enumValue: number): string | null { // {[key: string]: Common.OperationCodes}
const keys = Object.keys(myEnum).filter(x => myEnum[x] == enumValue);
return keys.length > 0 ? keys[0] : null;
}
const messageHandlers: { [key: number]: (client: Client, data?: any, debugOptions?: Common.ClientDebugOptions) => void } = {
/*eslint-enable */
[Common.OperationCodes.AUTHENTICATE]: (client: Client) => {
client.ws?.send(JSON.stringify({
op: Common.OperationCodes.AUTHENTICATE,
d: {
connectAs: client.authOptions.connectAs ?? 'application',
applicationId: client.authOptions.id,
applicationSecret: client.authOptions.secret,
version: client.authOptions.wssVersionOverride ?? Common.BP_VERSION
}
}));
},
[Common.OperationCodes.AUTH_SUCCESS]: (client: Client, data: Common.ServerResponseAuthSuccess, debugOptions?: Common.ClientDebugOptions) => {
client.connected = true;
client.emit('debug', `Successfully authenticated with application "${data.name}" (${client.authOptions.id})`);
if (debugOptions?.logHeartbeat) client.emit('debug', 'Heartbeat interval set to ' + data.heartbeatInterval);
client.heartbeatInterval = setInterval(() => {
client.ws?.send(JSON.stringify({
op: Common.OperationCodes.HEARTBEAT
}));
if (debugOptions?.logHeartbeat) client.emit('debug', 'Heartbeat sent');
}, data.heartbeatInterval);
return data;
},
[Common.OperationCodes.ERROR]: (client: Client, data: Common.ServerResponseError) => {
if (!client.connected) client.emit('debug', 'Failed to authenticate');
let error = data.error;
if (error.toLowerCase().includes('invalid websocket version')) error = 'Outdated WebSocket server version. Please update BotPanel.js.';
throw Error(error);
},
[Common.OperationCodes.GUILD_INTERACTION]: (client: Client, data: Common.GuildRequestInfo) => {
return new DashboardRequestInteraction(client, { interactionId: data.interactionId, guildId: data.guildId, include: data.include });
},
[Common.OperationCodes.MODIFY_GUILD_DATA]: (client: Client, data: Common.GuildDataChangeInfo) => {
return new DashboardChangeInteraction(client, data);
}
};
/**
* Represents a client for Bot Panel
* @constructor
*/
export class Client extends EventEmitter {
/** Authentication information for the client */
authOptions: Common.AuthenticationData;
/** Client WebSocket */
ws: undefined | WebSocket;
/** Whether the client is currently connected to the WebSocket */
connected: boolean = false;
/** Options for debugging BotPanel.js */
debugOptions: undefined | Common.ClientDebugOptions;
heartbeatInterval: undefined | NodeJS.Timeout;
/**
* @param options Authentication options
*/
constructor(options: Common.AuthenticationData, debugOptions?: Common.ClientDebugOptions) {
super();
this.authOptions = options;
this.debugOptions = debugOptions;
}
/** Connects to the Bot Panel WebSocket and login */
async login() {
return new Promise<WebSocket | null>((resolve) => {
try {
const ws = new WebSocket(this.authOptions.wss ?? 'wss://wss.botpanel.xyz');
if (this.ws) this.ws.close;
this.ws = ws;
this.connected = false;
ws.onopen = () => {
this.emit('debug', 'Connection initialized.');
resolve(ws);
};
ws.onclose = (event) => {
clearInterval(this.heartbeatInterval);
this.connected = false;
this.emit('debug', 'Connection closed.');
this.emit('close');
if (event.code != 1005 && !this.debugOptions?.disableAutoReconnect) {
this.emit('debug', 'Reconnecting to WebSocket in 5 seconds.');
setTimeout(()=>{this.login();},5000);
}
};
ws.on('error', (err) => {
console.error('WebSocket', err);
ws.close();
});
ws.onmessage = (event) => {
const message: string = event.data.toString();
const data: Common.ServerMessage = JSON.parse(message);
this.emit('message', message);
let dataToSend;
const eventHandler = messageHandlers[data.op];
if (!eventHandler) return;
try {
dataToSend = eventHandler(this, data.d, this.debugOptions);
} catch (err) {
this.emit('debug', `[${Common.OperationCodes[data.op]}]: ${err}`);
throw err;
}
this.emit(getEnumKeyByEnumValue(Common.OperationCodes, data.op) ?? data.op.toString(), dataToSend);
};
} catch (err) {
this.emit('debug', 'Failed to connect: ' + err);
throw err;
}
});
}
/** Closes the WebSocket connection */
disconnect() {
if (this.connected) this.ws?.close();
}
/** Sends a message to the WebSocket server (as JSON) */
send(message: object) {this.ws?.send(JSON.stringify(message));}
}
export class DashboardInteraction {
client: Client;
/**
* Assigned ID for the interaction
*/
id: Common.GuildDataChangeInfo['interactionId'] | null;
/**
* ID of the guild involved with the interaction
*/
guildId: Common.GuildDataChangeInfo['guildId'];
constructor(client: Client, options: Common.InteractionInfo) {
this.client = client;
this.id = options.interactionId;
this.guildId = options.guildId;
}
}
/**
* Guild information request interaction
*/
export class DashboardRequestInteraction extends DashboardInteraction {
requestedElements: Common.GuildRequestInfo['include'];
constructor(client: Client, options: Common.GuildRequestInfo) {
super(client, options);
this.requestedElements = options.include;
}
/**
* Sends an interaction response containing guild information
* @param data Guild info
*/
async send(info: Common.GuildRequestResponse) {
info.data ??= {};
// convert array values into strings
for (const [key, value] of Object.entries(info.data)) {
if (Array.isArray(value)) info.data[key] = value.toString();
}
// check for missing elements
const missing: Array<string> = [];
for (let i = 0; i < this.requestedElements.length; i++) {
const element = this.requestedElements[i];
if (!info[element]) {
missing.push(element);
}
}
if (missing.length > 0) this.client.emit('debug', 'Warning: Guild interaction response is missing the following elements: ' + missing.join(', '));
// default position values
for (const element of this.requestedElements) {
const elements = info[element];
if (!elements) continue;
for (let i = 0; i < elements.length; i++) {
const item = elements[i];
item.position = item.position ?? 0;
if (element == Common.ElementType.Role) item.managed = item.managed ?? false;
}
}
await new Promise((resolve) => {
this.client.ws?.send(JSON.stringify({
op: Common.OperationCodes.REQUEST_GUILD_DATA,
d: {
interactionId: this.id,
data: info.data,
inGuild: info.inGuild,
textChannels: info.textChannels ?? [],
voiceChannels: info.voiceChannels ?? [],
categories: info.categories ?? [],
roles: info.roles ?? [],
}
}), resolve);
});
}
}
/**
* Dashboard changed interaction
*/
export class DashboardChangeInteraction extends DashboardInteraction {
/**
* ID of the user that initiated the interaction
*/
userId: string;
/**
* Dashboard input that was changed
*/
input: {
type: Common.GuildDataChangeInfo['inputType'],
name: Common.GuildDataChangeInfo['varname'],
value: Common.GuildDataChangeInfo['data']
};
rawData: Common.GuildDataChangeInfo;
constructor(client: Client, options: Common.GuildDataChangeInfo) {
super(client, options);
let newValue: Common.GuildData = options.data;
// convert string to array for Select and Checkbox types
if (typeof options.data == 'string') newValue = options.inputType == Common.ComponentType.Checkbox || options.inputType == Common.ComponentType.Select ? options.data.split(',') : options.data;
this.userId = options.userId;
this.input = {
type: options.inputType,
name: options.varname,
value: newValue
};
this.rawData = options;
}
/**
* Sends an interaction response indicating if the change was successful
* @param success Was the change successful? (this will be shown to the user)
* @param newValue Optional new value to display on the dashboard input (if 'success' is not false).
*/
async acknowledge(data?: Common.AcknowledgementData) {
if (!this.id) throw Error('Interaction already acknowledged');
await new Promise((resolve) => {
this.client.ws?.send(JSON.stringify({
op: Common.OperationCodes.ACKNOWLEDGE_INTERACTION,
d: {
interactionId: this.id,
success: data?.success ?? true,
message: data?.message,
key: this.rawData.varname,
value: data?.newValue ? (typeof data?.newValue == 'object' ? data?.newValue.join(',') : data?.newValue) : this.rawData.data
}
}), resolve);
});
this.id = null;
}
}
export * from './common';