@open-discord-bots/framework 0.3.14 → 0.3.15

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 (41) hide show
  1. package/dist/api/main.js +1 -1
  2. package/dist/api/modules/responder.js +50 -26
  3. package/package.json +1 -1
  4. package/src/api/index.ts +0 -31
  5. package/src/api/main.ts +0 -203
  6. package/src/api/modules/action.ts +0 -89
  7. package/src/api/modules/base.ts +0 -845
  8. package/src/api/modules/builder.ts +0 -1755
  9. package/src/api/modules/checker.ts +0 -1826
  10. package/src/api/modules/client.ts +0 -2345
  11. package/src/api/modules/code.ts +0 -84
  12. package/src/api/modules/component.ts +0 -2000
  13. package/src/api/modules/config.ts +0 -264
  14. package/src/api/modules/console.ts +0 -697
  15. package/src/api/modules/cooldown.ts +0 -369
  16. package/src/api/modules/database.ts +0 -321
  17. package/src/api/modules/event.ts +0 -123
  18. package/src/api/modules/flag.ts +0 -99
  19. package/src/api/modules/fuse.ts +0 -365
  20. package/src/api/modules/helpmenu.ts +0 -273
  21. package/src/api/modules/language.ts +0 -230
  22. package/src/api/modules/permission.ts +0 -363
  23. package/src/api/modules/plugin.ts +0 -294
  24. package/src/api/modules/post.ts +0 -137
  25. package/src/api/modules/progressbar.ts +0 -370
  26. package/src/api/modules/responder.ts +0 -1625
  27. package/src/api/modules/session.ts +0 -181
  28. package/src/api/modules/startscreen.ts +0 -345
  29. package/src/api/modules/state.ts +0 -298
  30. package/src/api/modules/statistic.ts +0 -380
  31. package/src/api/modules/verifybar.ts +0 -68
  32. package/src/api/modules/worker.ts +0 -119
  33. package/src/cli/editConfig.ts +0 -930
  34. package/src/cli/index.ts +0 -152
  35. package/src/index.ts +0 -8
  36. package/src/startup/compilation.ts +0 -204
  37. package/src/startup/dump.ts +0 -46
  38. package/src/startup/errorHandling.ts +0 -42
  39. package/src/startup/pluginLauncher.ts +0 -265
  40. package/src/utilities/index.ts +0 -229
  41. package/tools/cleanup.js +0 -2
@@ -1,697 +0,0 @@
1
- ///////////////////////////////////////
2
- //CONSOLE MODULE
3
- ///////////////////////////////////////
4
- import { ODHTTPGetRequest, ODVersion, ODSystemError, ODPluginError, ODManager, ODManagerData, ODValidId, ODNoGeneric } from "./base.js"
5
- import { ODMain } from "../main.js"
6
- import nodepath from "path"
7
- import fs from "fs"
8
- import ansis from "ansis"
9
-
10
- /**## ODValidConsoleColor `type`
11
- * This is a collection of all the supported console colors within Open Discord.
12
- */
13
- export type ODValidConsoleColor = "white"|"red"|"yellow"|"green"|"blue"|"gray"|"cyan"|"magenta"
14
-
15
- /**## ODConsoleMessageParam `type`
16
- * This interface contains all data required for a console log parameter within Open Discord.
17
- */
18
- export interface ODConsoleMessageParam {
19
- /**The key of this parameter. */
20
- key:string,
21
- /**The value of this parameter. */
22
- value:string,
23
- /**When enabled, this parameter will only be shown in the debug file. */
24
- hidden?:boolean
25
- }
26
-
27
- /**## ODConsoleMessage `class`
28
- * This is an Open Discord console message.
29
- *
30
- * It is used to create beautiful & styled logs in the console with a prefix, message & parameters.
31
- * It also has full color support using `ansis` and parameters are parsed for you!
32
- */
33
- export class ODConsoleMessage {
34
- /**The main message sent in the console */
35
- message: string
36
- /**An array of all the parameters in this message */
37
- params: ODConsoleMessageParam[]
38
- /**The prefix of this message (!uppercase recommended!) */
39
- prefix: string
40
- /**The color of the prefix of this message */
41
- color: ODValidConsoleColor
42
-
43
- constructor(message:string, prefix:string, color:ODValidConsoleColor, params?:ODConsoleMessageParam[]){
44
- this.message = message
45
- this.params = params ? params : []
46
- this.prefix = prefix
47
-
48
- if (["white","red","yellow","green","blue","gray","cyan","magenta"].includes(color)){
49
- this.color = color
50
- }else{
51
- this.color = "white"
52
- }
53
- }
54
- /**Render this message to the console using `console.log`! Returns `false` when something went wrong. */
55
- render(){
56
- try {
57
- const prefixcolor = ansis[this.color]
58
-
59
- const paramsstring = " "+this.createParamsString("gray")
60
- const message = prefixcolor("["+this.prefix+"] ")+this.message
61
-
62
- console.log(message+paramsstring)
63
- return true
64
- }catch{
65
- return false
66
- }
67
- }
68
- /**Create a more-detailed, non-colored version of this message to store it in the `debug.txt` file! */
69
- toDebugString(){
70
- const pstrings: string[] = []
71
- this.params.forEach((p) => {
72
- pstrings.push(p.key+": "+p.value)
73
- })
74
- const pstring = (pstrings.length > 0) ? " ("+pstrings.join(", ")+")" : ""
75
- const date = new Date()
76
- const dstring = `${date.getDate()}/${date.getMonth()+1}/${date.getFullYear()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
77
- return `[${dstring} ${this.prefix}] ${this.message}${pstring}`
78
- }
79
- /**Render the parameters of this message in a specific color. */
80
- createParamsString(color:ODValidConsoleColor){
81
- let validcolor: ODValidConsoleColor = "white"
82
- if (["white","red","yellow","green","blue","gray","cyan","magenta"].includes(color)){
83
- validcolor = color
84
- }
85
-
86
- const pstrings: string[] = []
87
- this.params.forEach((p) => {
88
- if (!p.hidden) pstrings.push(p.key+": "+p.value)
89
- })
90
-
91
- return (pstrings.length > 0) ? ansis[validcolor](" ("+pstrings.join(", ")+")") : ""
92
- }
93
- /**Set the message */
94
- setMessage(message:string){
95
- this.message = message
96
- return this
97
- }
98
- /**Set the params */
99
- setParams(params:ODConsoleMessageParam[]){
100
- this.params = params
101
- return this
102
- }
103
- /**Set the prefix */
104
- setPrefix(prefix:string){
105
- this.prefix = prefix
106
- return this
107
- }
108
- /**Set the prefix color */
109
- setColor(color:ODValidConsoleColor){
110
- if (["white","red","yellow","green","blue","gray","cyan","magenta"].includes(color)){
111
- this.color = color
112
- }else{
113
- this.color = "white"
114
- }
115
- return this
116
- }
117
- }
118
-
119
- /**## ODInfoConsoleMessage `class`
120
- * This is an Open Discord console info message.
121
- *
122
- * It is the same as a normal `ODConsoleMessage`, but it has a predefined prefix & color scheme for the "INFO" messages!
123
- */
124
- export class ODInfoConsoleMessage extends ODConsoleMessage {
125
- constructor(message:string,params?:ODConsoleMessageParam[]){
126
- super(message,"INFO","blue",params)
127
- }
128
- }
129
-
130
- /**## ODSystemConsoleMessage `class`
131
- * This is an Open Discord console system message.
132
- *
133
- * It is the same as a normal `ODConsoleMessage`, but it has a predefined prefix & color scheme for the "SYSTEM" messages!
134
- */
135
- export class ODSystemConsoleMessage extends ODConsoleMessage {
136
- constructor(message:string,params?:ODConsoleMessageParam[]){
137
- super(message,"SYSTEM","green",params)
138
- }
139
- }
140
-
141
- /**## ODPluginConsoleMessage `class`
142
- * This is an Open Discord console plugin message.
143
- *
144
- * It is the same as a normal `ODConsoleMessage`, but it has a predefined prefix & color scheme for the "PLUGIN" messages!
145
- */
146
- export class ODPluginConsoleMessage extends ODConsoleMessage {
147
- constructor(message:string,params?:ODConsoleMessageParam[]){
148
- super(message,"PLUGIN","magenta",params)
149
- }
150
- }
151
-
152
- /**## ODDebugConsoleMessage `class`
153
- * This is an Open Discord console debug message.
154
- *
155
- * It is the same as a normal `ODConsoleMessage`, but it has a predefined prefix & color scheme for the "DEBUG" messages!
156
- */
157
- export class ODDebugConsoleMessage extends ODConsoleMessage {
158
- constructor(message:string,params?:ODConsoleMessageParam[]){
159
- super(message,"DEBUG","cyan",params)
160
- }
161
- }
162
-
163
- /**## ODWarningConsoleMessage `class`
164
- * This is an Open Discord console warning message.
165
- *
166
- * It is the same as a normal `ODConsoleMessage`, but it has a predefined prefix & color scheme for the "WARNING" messages!
167
- */
168
- export class ODWarningConsoleMessage extends ODConsoleMessage {
169
- constructor(message:string,params?:ODConsoleMessageParam[]){
170
- super(message,"WARNING","yellow",params)
171
- }
172
- }
173
-
174
- /**## ODErrorConsoleMessage `class`
175
- * This is an Open Discord console error message.
176
- *
177
- * It is the same as a normal `ODConsoleMessage`, but it has a predefined prefix & color scheme for the "ERROR" messages!
178
- */
179
- export class ODErrorConsoleMessage extends ODConsoleMessage {
180
- constructor(message:string,params?:ODConsoleMessageParam[]){
181
- super(message,"ERROR","red",params)
182
- }
183
- }
184
-
185
- /**## ODError `class`
186
- * This is an Open Discord error.
187
- *
188
- * It is used to render and log Node.js errors & crashes in a styled way to the console & `debug.txt` file!
189
- */
190
- export class ODError {
191
- /**The original error that this class wraps around */
192
- error: any
193
- /**The origin of the original error */
194
- origin: NodeJS.UncaughtExceptionOrigin
195
-
196
- constructor(error:any, origin:NodeJS.UncaughtExceptionOrigin){
197
- this.error = error
198
- this.origin = origin
199
- }
200
-
201
- /**Render this error to the console using `console.log`! Returns `false` when something went wrong. */
202
- render(){
203
- try {
204
- let prefix = (this.error["_ODErrorType"] && this.error["_ODErrorType"] == "plugin") ? "PLUGIN ERROR" : ((this.error["_ODErrorType"] == "system") ? "OPENTICKET ERROR" : "UNKNOWN ERROR")
205
- //title
206
- console.log(ansis.red("["+prefix+"]: ")+this.error.message+" | origin: "+this.origin)
207
- //stack trace
208
- if (this.error.stack) console.log(ansis.gray(this.error.stack))
209
- //additional message
210
- if (this.error["_ODErrorType"] == "plugin") console.log(ansis.red.bold("\nPlease report this error to the plugin developer and help us create a more stable plugin!"))
211
- else console.log(ansis.red.bold("\nPlease report this error to our discord server and help us create a more stable bot!"))
212
- console.log(ansis.red("Also send the "+ansis.cyan.bold("debug.txt")+" file! It would help a lot!\n"))
213
- return true
214
- }catch{
215
- return false
216
- }
217
- }
218
- /**Create a more-detailed, non-colored version of this error to store it in the `debug.txt` file! */
219
- toDebugString(){
220
- const date = new Date()
221
- const dstring = `${date.getDate()}/${date.getMonth()+1}/${date.getFullYear()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
222
- return "["+dstring+" UNKNOWN OPENDISCORD ERROR]: "+this.error.message+" | Error Origin: "+this.origin+" | Stacktrace:\n"+this.error.stack
223
- }
224
- }
225
-
226
- /**## ODConsoleMessageTypes `type`
227
- * This is a collection of all the default console message types within Open Discord.
228
- */
229
- export type ODConsoleMessageTypes = "info"|"system"|"plugin"|"debug"|"warning"|"error"
230
-
231
- /**## ODConsoleManager `class`
232
- * This is the Open Discord console manager.
233
- *
234
- * It handles the entire console system of Open Discord. It's also the place where you need to log `ODConsoleMessage`'s.
235
- * This manager keeps a short history of messages sent to the console which is configurable by plugins.
236
- *
237
- * The debug file (`debug.txt`) is handled in a sub-manager!
238
- */
239
- export class ODConsoleManager {
240
- /**The history of `ODConsoleMessage`'s and `ODError`'s since startup */
241
- history: (ODConsoleMessage|ODError)[] = []
242
- /**The max length of the history. The oldest messages will be removed when over the limit */
243
- historylength = 100
244
- /**An alias to the debugfile manager. (`debug.txt`) */
245
- debugfile: ODDebugFileManager
246
- /**Is silent mode enabled? */
247
- silent: boolean = false
248
-
249
- constructor(historylength:number, debugfile:ODDebugFileManager){
250
- this.historylength = historylength
251
- this.debugfile = debugfile
252
- }
253
-
254
- /**Log a message to the console ... But in the Open Discord way :) */
255
- log(message:ODConsoleMessage): void
256
- log(message:ODError): void
257
- log(message:string, type?:ODConsoleMessageTypes, params?:ODConsoleMessageParam[]): void
258
- log(message:ODConsoleMessage|ODError|string, type?:ODConsoleMessageTypes, params?:ODConsoleMessageParam[]){
259
- if (message instanceof ODConsoleMessage){
260
- if (!this.silent) message.render()
261
- if (this.debugfile) this.debugfile.writeConsoleMessage(message)
262
- this.history.push(message)
263
-
264
- }else if (message instanceof ODError){
265
- if (!this.silent) message.render()
266
- if (this.debugfile) this.debugfile.writeErrorMessage(message)
267
- this.history.push(message)
268
-
269
- }else if (["string","number","boolean","object"].includes(typeof message)){
270
- let newMessage: ODConsoleMessage
271
- if (type == "info") newMessage = new ODInfoConsoleMessage(message,params)
272
- else if (type == "system") newMessage = new ODSystemConsoleMessage(message,params)
273
- else if (type == "plugin") newMessage = new ODPluginConsoleMessage(message,params)
274
- else if (type == "debug") newMessage = new ODDebugConsoleMessage(message,params)
275
- else if (type == "warning") newMessage = new ODWarningConsoleMessage(message,params)
276
- else if (type == "error") newMessage = new ODErrorConsoleMessage(message,params)
277
- else newMessage = new ODSystemConsoleMessage(message,params)
278
-
279
- if (!this.silent) newMessage.render()
280
- if (this.debugfile) this.debugfile.writeConsoleMessage(newMessage)
281
- this.history.push(newMessage)
282
- }
283
- this.purgeHistory()
284
- }
285
- /**Shorten the history when it exceeds the max history length! */
286
- protected purgeHistory(){
287
- if (this.history.length > this.historylength) this.history.shift()
288
- }
289
- }
290
-
291
- /**## ODDebugFileManager `class`
292
- * This is the Open Discord debug file manager.
293
- *
294
- * It manages the Open Discord debug file (`debug.txt`) which keeps a history of all system logs.
295
- * There are even internal logs that aren't logged to the console which are available in this file!
296
- *
297
- * Using this class, you can change the max length of this file and some other cool things!
298
- */
299
- export class ODDebugFileManager {
300
- /**The path to the debugfile (`./debug.txt` by default) */
301
- path: string
302
- /**The filename of the debugfile (`debug.txt` by default) */
303
- filename: string
304
- /**The current version of the bot used in the debug file. */
305
- version: ODVersion
306
- /**The max length of the debug file. */
307
- maxlines: number
308
-
309
- constructor(path:string, filename:string, maxlines:number, version:ODVersion){
310
- this.path = nodepath.join(path,filename)
311
- this.filename = filename
312
- this.version = version
313
- this.maxlines = maxlines
314
-
315
- this.writeStartupStats()
316
- }
317
-
318
- /**Check if the debug file exists */
319
- protected existsDebugFile(){
320
- return fs.existsSync(this.path)
321
- }
322
- /**Read from the debug file */
323
- protected readDebugFile(){
324
- if (this.existsDebugFile()){
325
- try {
326
- return fs.readFileSync(this.path).toString()
327
- }catch{
328
- return false
329
- }
330
- }else{
331
- return false
332
- }
333
- }
334
- /**Write to the debug file and shorten it when needed. */
335
- protected writeDebugFile(text:string){
336
- const currenttext = this.readDebugFile()
337
- if (currenttext){
338
- const splitted = currenttext.split("\n")
339
-
340
- if (splitted.length+text.split("\n").length > this.maxlines){
341
- splitted.splice(7,(text.split("\n").length))
342
- }
343
-
344
- splitted.push(text)
345
- fs.writeFileSync(this.path,splitted.join("\n"))
346
- }else{
347
- //write new file:
348
- const newtext = this.createStatsText()+text
349
- fs.writeFileSync(this.path,newtext)
350
- }
351
- }
352
- /**Generate the statistics/header of the debug file (containing the version) */
353
- protected createStatsText(){
354
- const date = new Date()
355
- const dstring = `${date.getDate()}/${date.getMonth()+1}/${date.getFullYear()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
356
- return [
357
- "=========================",
358
- "OPEN DISCORD DEBUG FILE:",
359
- "version: "+this.version.toString(),
360
- "last startup: "+dstring,
361
- "=========================\n\n"
362
- ].join("\n")
363
- }
364
- /**Write the statistics/header to the debug file on startup */
365
- protected writeStartupStats(){
366
- const currenttext = this.readDebugFile()
367
- if (currenttext){
368
- //edit previous file:
369
- const splitted = currenttext.split("\n")
370
- splitted.splice(0,7)
371
-
372
- if (splitted.length+11 > this.maxlines){
373
- splitted.splice(0,((splitted.length+11) - this.maxlines))
374
- }
375
-
376
- splitted.unshift(this.createStatsText())
377
- splitted.push("\n---------------------------------------------------------------------\n---------------------------------------------------------------------\n")
378
-
379
- fs.writeFileSync(this.path,splitted.join("\n"))
380
- }else{
381
- //write new file:
382
- const newtext = this.createStatsText()
383
- fs.writeFileSync(this.path,newtext)
384
- }
385
- }
386
- /**Write an `ODConsoleMessage` to the debug file */
387
- writeConsoleMessage(message:ODConsoleMessage){
388
- this.writeDebugFile(message.toDebugString())
389
- }
390
- /**Write an `ODError` to the debug file */
391
- writeErrorMessage(error:ODError){
392
- this.writeDebugFile(error.toDebugString())
393
- }
394
- /**Write custom text to the debug file */
395
- writeText(text:string){
396
- this.writeDebugFile(text)
397
- }
398
- /**Write a custom note to the debug file (starting with `[NOTE]:`) */
399
- writeNote(text:string){
400
- this.writeDebugFile("[NOTE]: "+text)
401
- }
402
- }
403
-
404
- /**## ODDebugger `class`
405
- * This is the Open Discord debugger.
406
- *
407
- * It is a simple wrapper around the `ODConsoleManager` to handle debugging (primarily for `ODManagers`).
408
- * Messages created using this debugger are only logged to the debug file unless specified otherwise.
409
- *
410
- * You will probably notice this class being used in the `ODManager` constructor.
411
- *
412
- * Using this system, all additions & removals inside a manager are logged to the debug file. This makes searching for errors a lot easier!
413
- */
414
- export class ODDebugger {
415
- /**An alias to the Open Discord console manager. */
416
- console: ODConsoleManager
417
- /**When enabled, debug logs are also shown in the console. */
418
- visible: boolean = false
419
-
420
- constructor(console:ODConsoleManager){
421
- this.console = console
422
- }
423
-
424
- /**Create a debug message. This will always be logged to `debug.txt` & sometimes to the console (when enabled). Returns `true` when visible */
425
- debug(message:string, params?:{key:string,value:string}[]): boolean {
426
- if (this.visible){
427
- this.console.log(new ODDebugConsoleMessage(message,params))
428
- return true
429
- }else{
430
- this.console.debugfile.writeConsoleMessage(new ODDebugConsoleMessage(message,params))
431
- return false
432
- }
433
- }
434
- }
435
-
436
- /**## ODLivestatusColor `type`
437
- * This is a collection of all the colors available within the LiveStatus system.
438
- */
439
- export type ODLiveStatusColor = "normal"|"red"|"green"|"blue"|"yellow"|"white"|"gray"|"magenta"|"cyan"
440
-
441
- /**## ODLiveStatusSourceData `interface`
442
- * This is an interface containing all raw data received from the LiveStatus system.
443
- */
444
- export interface ODLiveStatusSourceData {
445
- /**The message to display */
446
- message:{
447
- /**The title of the message to display */
448
- title:string,
449
- /**The title color of the message to display */
450
- titleColor:ODLiveStatusColor,
451
- /**The description of the message to display */
452
- description:string,
453
- /**The description color of the message to display */
454
- descriptionColor:ODLiveStatusColor
455
- },
456
- /**The message will only be shown when the bot matches all statements */
457
- active:{
458
- /**A list of versions to match */
459
- versions:string[],
460
- /**A list of languages to match */
461
- languages:string[],
462
- /**All languages should match */
463
- allLanguages:boolean,
464
- /**Match when the bot is using plugins */
465
- usingPlugins:boolean,
466
- /**Match when the bot is not using plugins */
467
- notUsingPlugins:boolean,
468
- /**Match when the bot is using slash commands */
469
- usingSlashCommands:boolean,
470
- /**Match when the bot is not using slash commands */
471
- notUsingSlashCommands:boolean,
472
- /**Match when the bot is not using transcripts */
473
- notUsingTranscripts:boolean,
474
- /**Match when the bot is using text transcripts */
475
- usingTextTranscripts:boolean,
476
- /**Match when the bot is using html transcripts */
477
- usingHtmlTranscripts:boolean
478
- }
479
- }
480
-
481
- /**## ODLiveStatusSource `class`
482
- * This is the Open Discord livestatus source.
483
- *
484
- * It is an empty template for a livestatus source.
485
- * By default, you should use `ODLiveStatusUrlSource` or `ODLiveStatusFileSource`,
486
- * unless you want to create one on your own!
487
- *
488
- * This class doesn't do anything on it's own! It's just a template!
489
- */
490
- export class ODLiveStatusSource extends ODManagerData {
491
- /**The raw data of this source */
492
- data: ODLiveStatusSourceData[]
493
-
494
- constructor(id:ODValidId, data:ODLiveStatusSourceData[]){
495
- super(id)
496
- this.data = data
497
- }
498
-
499
- /**Change the current data using this method! */
500
- setData(data:ODLiveStatusSourceData[]){
501
- this.data = data
502
- }
503
- /**Get all messages relevant to the bot based on some parameters. */
504
- async getMessages(main:ODMain): Promise<ODLiveStatusSourceData[]> {
505
- const validMessages: ODLiveStatusSourceData[] = []
506
-
507
- //parse data from ODMain
508
- const currentVersion: string = main.versions.get("opendiscord:version")?.toString(true) ?? "<OD:UNKNOWN_VERSION>"
509
- const usingSlashCommands: boolean = main.configs.get("opendiscord:general")?.data.slashCommands ?? false
510
- const usingTranscripts: false|"text"|"html" = false as false|"text"|"html" //TODO
511
- const currentLanguage: string = main.languages.getCurrentLanguageId()
512
- const usingPlugins: boolean = (main.plugins.getLength() > 0)
513
-
514
- //check data for each message
515
- this.data.forEach((msg) => {
516
- const {active} = msg
517
-
518
- const correctVersion = active.versions.includes(currentVersion)
519
- const correctSlashMode = (usingSlashCommands && active.usingSlashCommands) || (!usingSlashCommands && active.notUsingSlashCommands)
520
- const correctTranscriptMode = (usingTranscripts == "text" && active.usingTextTranscripts) || (usingTranscripts == "html" && active.usingHtmlTranscripts) || (!usingTranscripts && active.notUsingTranscripts)
521
- const correctLanguage = active.languages.includes(currentLanguage) || active.allLanguages
522
- const correctPlugins = (usingPlugins && active.usingPlugins) || (!usingPlugins && active.notUsingPlugins)
523
-
524
- if (correctVersion && correctLanguage && correctPlugins && correctSlashMode && correctTranscriptMode) validMessages.push(msg)
525
- })
526
-
527
- //return the valid messages
528
- return validMessages
529
- }
530
- }
531
-
532
- /**## ODLiveStatusFileSource `class`
533
- * This is the Open Discord livestatus file source.
534
- *
535
- * It is a LiveStatus source that will read the data from a local file.
536
- *
537
- * This can be used for testing/extending the LiveStatus system!
538
- */
539
- export class ODLiveStatusFileSource extends ODLiveStatusSource {
540
- /**The path to the source file */
541
- path: string
542
-
543
- constructor(id:ODValidId, path:string){
544
- if (fs.existsSync(path)){
545
- super(id,JSON.parse(fs.readFileSync(path).toString()))
546
- }else throw new ODSystemError("LiveStatus source file doesn't exist!")
547
- this.path = path
548
- }
549
- }
550
-
551
- /**## ODLiveStatusUrlSource `class`
552
- * This is the Open Discord livestatus url source.
553
- *
554
- * It is a LiveStatus source that will read the data from a http URL (json file).
555
- *
556
- * This is the default way of receiving LiveStatus messages!
557
- */
558
- export class ODLiveStatusUrlSource extends ODLiveStatusSource {
559
- /**The url used in the request */
560
- url: string
561
- /**The `ODHTTPGetRequest` helper to fetch the url! */
562
- request: ODHTTPGetRequest
563
-
564
- constructor(main:ODMain,id:ODValidId, url:string){
565
- super(id,[])
566
- this.url = url
567
- this.request = new ODHTTPGetRequest(main,url,false)
568
- }
569
- async getMessages(main:ODMain): Promise<ODLiveStatusSourceData[]> {
570
- //additional setup
571
- this.request.url = this.url
572
- const rawRes = await this.request.run()
573
- if (rawRes.status != 200) throw new ODSystemError("ODLiveStatusUrlSource => Request Failed!")
574
- try{
575
- this.setData(JSON.parse(rawRes.body))
576
- }catch{
577
- throw new ODSystemError("ODLiveStatusUrlSource => Request Failed!")
578
- }
579
-
580
- //default
581
- return super.getMessages(main)
582
- }
583
- }
584
-
585
- /**## ODLiveStatusManagerIdConstraint `type`
586
- * The constraint/layout for id mappings/interfaces of the `ODLiveStatusManager` class.
587
- */
588
- export type ODLiveStatusManagerIdConstraint = Record<string,ODLiveStatusSource>
589
-
590
- /**## ODLiveStatusManager `class`
591
- * This is the Open Discord livestatus manager.
592
- *
593
- * It manages all LiveStatus sources and has the renderer for all LiveStatus messages.
594
- *
595
- * You can use this to customise or add stuff to the LiveStatus system.
596
- * Access it in the global `opendiscord.startscreen.livestatus` variable!
597
- */
598
- export class ODLiveStatusManager<IdList extends ODLiveStatusManagerIdConstraint = ODLiveStatusManagerIdConstraint> extends ODManager<ODLiveStatusSource> {
599
- /**The class responsible for rendering the livestatus messages. */
600
- renderer: ODLiveStatusRenderer
601
- /**A reference to the ODMain or "opendiscord" global variable */
602
- protected main: ODMain|null = null
603
-
604
- constructor(debug:ODDebugger,console:ODConsoleManager){
605
- super(debug,"livestatus source")
606
- this.renderer = new ODLiveStatusRenderer(console)
607
- }
608
-
609
- /**Get the messages from all sources combined! */
610
- async getAllMessages(): Promise<ODLiveStatusSourceData[]> {
611
- if (!this.main) throw new ODSystemError("ODLiveStatusManager:getAllMessages() --> Unable to get messages, 'opendiscord/ODMain' has not been connected!")
612
- const messages: ODLiveStatusSourceData[] = []
613
- for (const source of this.getAll()){
614
- try {
615
- messages.push(...(await source.getMessages(this.main)))
616
- }catch{}
617
- }
618
- return messages
619
- }
620
- /**Set the opendiscord `ODMain` class to use for fetching message filters. */
621
- useMain(main:ODMain){
622
- this.main = main
623
- }
624
-
625
- get<LiveStatusId extends keyof ODNoGeneric<IdList>>(id:LiveStatusId): IdList[LiveStatusId]
626
- get(id:ODValidId): ODLiveStatusSource|null
627
-
628
- get(id:ODValidId): ODLiveStatusSource|null {
629
- return super.get(id)
630
- }
631
-
632
- remove<LiveStatusId extends keyof ODNoGeneric<IdList>>(id:LiveStatusId): IdList[LiveStatusId]
633
- remove(id:ODValidId): ODLiveStatusSource|null
634
-
635
- remove(id:ODValidId): ODLiveStatusSource|null {
636
- return super.remove(id)
637
- }
638
-
639
- exists(id:keyof ODNoGeneric<IdList>): boolean
640
- exists(id:ODValidId): boolean
641
-
642
- exists(id:ODValidId): boolean {
643
- return super.exists(id)
644
- }
645
- }
646
-
647
- /**## ODLiveStatusRenderer `class`
648
- * This is the Open Discord livestatus renderer.
649
- *
650
- * It's responsible for rendering all LiveStatus messages to the console.
651
- */
652
- export class ODLiveStatusRenderer {
653
- /**A reference to the ODConsoleManager or "opendiscord.console" global variable */
654
- protected console: ODConsoleManager
655
-
656
- constructor(console:ODConsoleManager){
657
- this.console = console
658
- }
659
-
660
- /**Render all messages */
661
- render(messages:ODLiveStatusSourceData[]): string {
662
- try {
663
- //process data
664
- const final: string[] = []
665
- messages.forEach((msg) => {
666
- const titleColor = msg.message.titleColor
667
- const title = "["+msg.message.title+"] "
668
-
669
- const descriptionColor = msg.message.descriptionColor
670
- const description = msg.message.description.split("\n").map((text,row) => {
671
- //first row row doesn't need prefix
672
- if (row < 1) return text
673
- //other rows do need a prefix
674
- let text2 = text
675
- for (const i of title){
676
- text2 = " "+text2
677
- }
678
- return text2
679
- }).join("\n")
680
-
681
-
682
- if (!["red","yellow","green","blue","gray","magenta","cyan"].includes(titleColor)) var finalTitle = ansis.white(title)
683
- else var finalTitle = ansis[(titleColor == "normal" ? "white" : titleColor)](title)
684
- if (!["red","yellow","green","blue","gray","magenta","cyan"].includes(descriptionColor)) var finalDescription = ansis.white(description)
685
- else var finalDescription = ansis[(descriptionColor == "normal" ? "white" : descriptionColor)](description)
686
-
687
- final.push(finalTitle+finalDescription)
688
- })
689
-
690
- //return all messages
691
- return final.join("\n")
692
- }catch{
693
- this.console.log("Failed to render LiveStatus messages!","error")
694
- return ""
695
- }
696
- }
697
- }