-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.js
1179 lines (1042 loc) · 48.9 KB
/
bot.js
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const config = require('../elite-dangerous-news-discord-bot-config.json');
const { version, author, license } = require('./package.json');
const fs = require('fs');
const Discord = require('discord.js');
const fetch = require('node-fetch');
const moment = require('moment'); require('moment-precise-range-plugin');
const { htmlToText } = require('html-to-text');
const he = require('he');
const forceSync = require('sync-rpc');
const syncGetOwnerUsername = forceSync(require.resolve('./async-as-sync.js'));
const client = new Discord.Client();
// CONSTANTS
// WEBSITES
const AUTHOR_URL = 'https://andrew-larson.dev';
const TWITTER_URL = 'https://twitter.com/Alien_Drew';
const PATREON_URL = 'https://www.patreon.com/Andrew_J_Larson';
const KOFI_URL = 'https://ko-fi.com/Andrew_J_Larson';
// STATUS TYPES
const PLAY = 'PLAYING';
const WATCH = 'WATCHING';
const LISTEN = 'LISTENING';
const STREAM = 'STREAMING';
// ADMIN PERMISSION
const ADMIN = 'MANAGE_MESSAGES';
// OTHER PERMISSIONS
const SEND = 'SEND_MESSAGES';
const EVERYONE = 'MENTION_EVERYONE';
// EMBED MAXES
const DESCRIPTION_LENGTH = 2048;
const FIELD_VALUE_LENGTH = 1024;
const FIELDS = 25;
// SAVE LOCATION
const SERVER_SAVE_DIR = './servers/';
const SAVE_POSTFIX = '.guild';
// BOT CONSTANTS
const IN_JSON_FORMAT = '?_format=json';
const GITHUB_REPO_URL = 'https://github.com/Andrew-J-Larson/elite-dangerous-news-discord-bot';
const BOT_NAME = 'Elite Dangerous News';
const DEFAULT_PREFIX = 'edn';
const PRESENCE_NAME = `@${BOT_NAME} help | for commands`;
const NO_PERMISSION = "Sorry, but you don't have permissions for that command.";
const MAIN_BOT_COLOR = 0xCCCCCC; // A SILVER LIKE COLOR
const ED_DOMAIN = 'elitedangerous.com';
const ED_FRONTEND_URL = 'https://www.' + ED_DOMAIN + '/';
const ED_BACKEND_URL = 'https://cms.' + ED_DOMAIN + '/';
const ED_FORUMS_URL = 'https://forums.frontier.co.uk/';
const ED_NODE_URL_PREFIX = ED_BACKEND_URL + 'node/';
const EDN_ARTICLE_URL_PREFIX = ED_FRONTEND_URL + 'news/article/';
const EDN_ARTICLE_IMG_URL_PREFIX = 'https://cms.' + ED_DOMAIN;
const EDN_JSON_URL = ED_BACKEND_URL + 'api/news' + IN_JSON_FORMAT; // NO RSS - because there is no official RSS endpoint
const BOT_IMAGES_URL_PREFIX = 'https://raw.githubusercontent.com/Andrew-J-Larson/elite-dangerous-news-discord-bot/main/images/'
const EDN_IMAGES_URL_PREFIX = BOT_IMAGES_URL_PREFIX + 'Elite-Dangerous-Logo/';
const EDN_LOGO_SILVER_THUMB = EDN_IMAGES_URL_PREFIX + 'Elite-Dangerous_Silver_Thumbnail.png';
const EDN_LOGO_WHITE_BOT_IMAGE = EDN_IMAGES_URL_PREFIX + 'Elite-Dangerous_White_Bot_Picture.png';
const EDN_ARTICLE_NO_IMAGE = BOT_IMAGES_URL_PREFIX + 'No-Image.png';
const BOT_THUMBNAIL_IMAGE = EDN_LOGO_SILVER_THUMB;
const BOT_FOOTER_IMAGE = EDN_LOGO_WHITE_BOT_IMAGE;
const FEED_INTERVAL_SPEED = 60000; // 1 minute in milliseconds
const ALL_POST_DELAY = 1500; // 1.5 seconds in milliseconds
const ITALIC = '<i>';
const BOLD = '<b>';
const STRIKETHROUGH = '<s>';
const UNDERLINE = '<u>';
const HEADING = '<h>';
const HEADING_START = '<hs>';
const HEADING_END = '<he>';
const HTML_TO_TEXT = {
wordwrap: null,
formatters: {
'customLineBreaks': function (elem, walk, builder, formatOptions) {
builder.openBlock(formatOptions.leadingLineBreaks || 0);
builder.closeBlock(formatOptions.trailingLineBreaks || 0);
},
'customItalic': function (elem, walk, builder, formatOptions) {
let tag = formatOptions.tag || '*';
builder.addInline(tag);
walk(elem.children, builder);
builder.addInline(tag);
},
'customBold': function (elem, walk, builder, formatOptions) {
let tag = formatOptions.tag || '**';
builder.addInline(tag);
walk(elem.children, builder);
builder.addInline(tag);
},
'customStrikethrough': function (elem, walk, builder, formatOptions) {
let tag = formatOptions.tag || '~~';
builder.addInline(tag);
walk(elem.children, builder);
builder.addInline(tag);
},
'customUnderline': function (elem, walk, builder, formatOptions) {
let tag = formatOptions.tag || '__';
builder.addInline(tag);
walk(elem.children, builder);
builder.addInline(tag);
},
'customLink': function (elem, walk, builder, formatOptions) {
function getHref() {
if (formatOptions.ignoreHref) { return ''; }
if (!elem.attribs || !elem.attribs.href) { return ''; }
let href = elem.attribs.href.replace(/^mailto:/, '');
if (formatOptions.noAnchorUrl && href[0] === '#') { return ''; }
href = (formatOptions.baseUrl && href[0] === '/')
? formatOptions.baseUrl + href
: href;
return he.decode(href, builder.options.decodeOptions);
}
const href = getHref();
if (!href) {
walk(elem.children, builder);
} else {
let text = '';
builder.pushWordTransform(
str => {
if (str) { text += str; }
return str;
}
);
builder.addInline('[', { noWordTransform: true });
walk(elem.children, builder);
builder.popWordTransform();
builder.addInline('](' + href + ')', { noWordTransform: true });
}
},
'customImage': function (elem, walk, builder, formatOptions) {
const attribs = elem.attribs || {};
const alt = (attribs.alt)
? he.decode(attribs.alt, builder.options.decodeOptions)
: '';
const src = (!attribs.src)
? ''
: (formatOptions.baseUrl && attribs.src.indexOf('/') === 0)
? formatOptions.baseUrl + attribs.src
: attribs.src;
const text = (!src)
? alt
: (!alt)
? '[[' + src + '](' + src + ')]'
: '[[' + alt + '](' + src + ')]';
builder.addInline(text);
},
'customIframe': function (elem, walk, builder, formatOptions) {
const attribs = elem.attribs || {};
const title = (attribs.title)
? he.decode(attribs.title, builder.options.decodeOptions)
: '';
const src = (!attribs.src)
? ''
: (formatOptions.baseUrl && attribs.src.indexOf('/') === 0)
? formatOptions.baseUrl + attribs.src
: attribs.src;
const text = (!src)
? title
: (!title)
? '{[' + src + '](' + src + ')}'
: '{[' + title + '](' + src + ')}';
builder.addInline(text);
},
'customHeading': function (elem, walk, builder, formatOptions) {
let tag = formatOptions.tag;
let tagStart = formatOptions.tagStart || (tag ? tag : '**__');
let tagEnd = formatOptions.tagEnd || (tag ? tag : '__**');
builder.openBlock(formatOptions.leadingLineBreaks || 1);
builder.addInline(tagStart);
if (formatOptions.uppercase !== false) {
builder.pushWordTransform(str => str.toUpperCase());
walk(elem.children, builder);
builder.popWordTransform();
} else {
walk(elem.children, builder);
}
builder.addInline(tagEnd);
builder.closeBlock(formatOptions.trailingLineBreaks || 1);
}
},
tags: {
'br': {
format: 'customLineBreaks',
options: { trailingLineBreaks: 2 }
}, // change 2 to 1, for single line breaks
'p': { options: { trailingLineBreaks: 2 } }, // change 2 to 1, for single line breaks
'a': { format: 'customLink' },
'img': { format: 'customImage' },
'iframe': { format: 'customIframe' },
'ul': { options: { itemPrefix: ' • ' } },
'em': {
format: 'customItalic',
options: { tag: ITALIC }
}, // tag gets replaced after markdown escapes
'i': {
format: 'customItalic',
options: { tag: ITALIC }
}, // tag gets replaced after markdown escapes
'strong': {
format: 'customBold',
options: { tag: BOLD }
}, // tag gets replaced after markdown escapes
'b': {
format: 'customBold',
options: { tag: BOLD }
}, // tag gets replaced after markdown escapes
'strike': {
format: 'customStrikethrough',
options: { tag: STRIKETHROUGH }
}, // tag gets replaced after markdown escapes
's': {
format: 'customStrikethrough',
options: { tag: STRIKETHROUGH }
}, // tag gets replaced after markdown escapes
'u': {
format: 'customUnderline',
options: { tag: UNDERLINE }
}, // tag gets replaced after markdown escapes
'h1': {
format: 'customHeading',
options: {
tagStart: HEADING_START, tagEnd: HEADING_END, // tags gets replaced after markdown escapes
leadingLineBreaks: 2, trailingLineBreaks: 2
}
}, // change 2 to 1, for single line breaks
'h2': {
format: 'customHeading',
options: {
tagStart: HEADING_START, tagEnd: HEADING_END, // tags gets replaced after markdown escapes
leadingLineBreaks: 2, trailingLineBreaks: 2
}
}, // change 2 to 1, for single line breaks
'h3': {
format: 'customHeading',
options: {
tagStart: HEADING_START, tagEnd: HEADING_END, // tags gets replaced after markdown escapes
leadingLineBreaks: 2, trailingLineBreaks: 2
}
}, // change 2 to 1, for single line breaks
'h4': {
format: 'customHeading',
options: {
tagStart: HEADING_START, tagEnd: HEADING_END, // tags gets replaced after markdown escapes
leadingLineBreaks: 2, trailingLineBreaks: 2
}
}, // change 2 to 1, for single line breaks
'h5': {
format: 'customHeading',
options: {
tagStart: HEADING_START, tagEnd: HEADING_END, // tags gets replaced after markdown escapes
leadingLineBreaks: 2, trailingLineBreaks: 2
}
}, // change 2 to 1, for single line breaks
'h6': {
format: 'customHeading',
options: {
tagStart: HEADING_START, tagEnd: HEADING_END, // tags gets replaced after markdown escapes
leadingLineBreaks: 2, trailingLineBreaks: 2
}
} // change 2 to 1, for single line breaks
}
};
const NEWEST_POST_FILE = './newest-post.txt';
const DEFAULT_SETTINGS = {
prefix: DEFAULT_PREFIX,
feedChannel: null,
feedRole: null
};
// BOT VARIABLES
let serversFolderAccess = true; // prevents creation of settings files when it doesn't have access to servers folder
// each server's settings will be stored as an entry in the settings like such:
// [server id]: {settings object}
// the inital settings object get's a deep copy of the DEFAULT_SETTINGS object
let settings = {};
// FUNCTIONS
function logConnectedServers() {
console.log('Connected to the following servers:');
let connectedServers = 0;
client.guilds.cache.forEach(server => {
let ownerId = server.ownerID;
let owner = ownerId ? syncGetOwnerUsername(ownerId) : null;
let ownerUsername = owner ? (owner.username + '#' + owner.discriminator) : null;
console.log(`\t"${server.name}" (${server.id})` + (ownerUsername ? (' [Owner: ' + ownerUsername + ']') : ''));
connectedServers++;
});
return connectedServers;
}
// returns the user from a mention
function getUserFromMention(mention) {
if (!mention) return false;
if (mention.startsWith('<@') && mention.endsWith('>')) {
mention = mention.slice(2, -1);
if (mention.startsWith('!')) mention = mention.slice(1);
return client.users.cache.get(mention);
}
}
// returns the channel id from channel mention
function getChannelFromMention(mention) {
if (!mention) return false;
if (mention.startsWith('<#') && mention.endsWith('>')) {
mention = mention.slice(2, -1);
return mention;
}
}
// returns the role id from role mention
function getRoleFromMention(mention) {
if (!mention) return false;
if (mention.startsWith('<@&') && mention.endsWith('>')) {
mention = mention.slice(3, -1);
return mention;
}
}
// escapes all discord markdown to return useful string
function escapeMarkdown(text) {
let unescaped = text.replace(/\\(\*|_|`|~|\\)/g, '$1'); // unescape any "backslashed" character
let escaped = unescaped.replace(/(\*|_|`|~|\\)/g, '\\$1'); // escape *, _, `, ~, \
return escaped;
}
// converts unescaped html-text-string to discord markdown
function convertToDiscord(text) {
let escaped = escapeMarkdown(text);
let converted = escaped.replace(new RegExp(ITALIC, 'g'), '*')
.replace(new RegExp(BOLD, 'g'), '**')
.replace(new RegExp(STRIKETHROUGH, 'g'), '~~')
.replace(new RegExp(UNDERLINE, 'g'), '__')
.replace(new RegExp(HEADING_START, 'g'), '**__')
.replace(new RegExp(HEADING_END, 'g'), '__**');
return converted;
}
// load all bot settings
function loadSettings() {
// check for folder/file existence before trying to load
let totalSettingsLoaded = 0;
// check if servers folder exists, and if not, to create it
console.log('Attempting to load all server settings...');
if (!fs.existsSync(SERVER_SAVE_DIR)) {
try {
fs.mkdirSync(SERVER_SAVE_DIR);
} catch (err) {
serversFolderAccess = false;
console.error("Couldn't create `servers` folder to store server settings.");
}
console.log('Bot has been activated for the first time, no settings to load for any server.');
} else { // we have a servers folder to look through
try {
// for every file, check text
fs.readdirSync(SERVER_SAVE_DIR).forEach(file => {
let settingsLoaded = 0;
// make sure the file we are reading from follows our settings save postfix
if (file.endsWith(SAVE_POSTFIX)) {
// need to remove the postfix from the file to get the server id
let serverId = file.replace(SAVE_POSTFIX, '');
// confirm serverId is a real server we are connected to (avoids invalid save files)
let serverGuild = client.guilds.cache.get(serverId);
if (serverGuild) {
let data = fs.readFileSync(SERVER_SAVE_DIR + file, 'utf8');
// check to make sure that a specific server's settings hasn't already loaded in
if (settings[serverId] && settings[serverId].prefix) {
// this shouldn't actually ever happen
console.log("Some how the server settings has already loaded in for: " + serverId);
} else {
// create new server entry with default settings
settings[serverId] = JSON.parse(JSON.stringify(DEFAULT_SETTINGS));
// loop through lines until correct setting is found or until end of file
let keys = Object.keys(settings[serverId]);
console.log((serverGuild.name ? ('"' + serverGuild.name + '" (' + serverId + ')') : serverId) + ':');
data.toString().split('\n').forEach(function (line, index, arr) {
if (index === arr.length - 1 && line === "") return;
console.log('\t' + index + ' ' + line);
// check and load in settings to specific server id entry
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
let keyStart = key + '=';
if (line.startsWith(keyStart)) {
settings[serverId][key] = line.substring(keyStart.length)
settingsLoaded++;
}
}
});
if (settingsLoaded == keys.length) console.log('\tSettings loaded successfully');
else if (settingsLoaded) console.log('\tPartial settings loaded successfully');
else console.log('\tNo settings found in file to load');
}
totalSettingsLoaded += settingsLoaded;
} else {
console.error('Tried to load a non-server save file named: ' + file);
}
}
});
} catch (err) {
console.log("Couldn't access the servers folder, or one or more server save files: " + err);
}
}
return totalSettingsLoaded;
}
// delete all bot settings
function deleteSettings(serverId) {
// if there is a server entry in settings object, delete it
if (settings[serverId]) {
try {
delete settings[serverId];
console.log(`${serverId}: Deleted server settings from object.`);
} catch (err) {
console.error(`${serverId}: Couldn't delete server settings from object. Error: ` + err);
}
}
// if there is a settings file for the server, delete it
let serverSaveFile = SERVER_SAVE_DIR + serverId + SAVE_POSTFIX;
if (fs.existsSync(serverSaveFile)) {
try {
fs.unlinkSync(serverSaveFile);
console.log(`${serverSaveFile}: Deleted server settings file.`);
} catch (err) {
console.error(`${serverSaveFile}: Couldn't delete server settings file. Error: ` + err);
}
}
}
// save all bot settings
function saveSettings(serverId) {
// if the servers folder wasn't created or can't access, prevent saving server settings
if (serversFolderAccess && serverId) {
// need to add entry to settings object if there doesn't already appear to be one
if (!settings[serverId]) {
settings[serverId] = JSON.parse(JSON.stringify(DEFAULT_SETTINGS));
}
// create/overwrite existing save file
let saveString = '';
let keys = Object.keys(settings[serverId]);
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
let keyStart = key + '=';
if (settings[serverId][key]) saveString += keyStart + settings[serverId][key] + '\n';
}
// write to file
try {
fs.writeFileSync(SERVER_SAVE_DIR + serverId + SAVE_POSTFIX, saveString);
console.log(`${serverId}: Settings saved successfully.`);
} catch (err) {
console.error(`${serverId}: Couldn't save settings. Error: ` + err);
}
} else if (!serverId) { // should never get beyond this point
console.error('No server id was passed into function.');
} else {
console.error("No access to servers folder, or it doesn't exist.");
}
}
// returns channel or author based on if it can send a message in current channel
function msgLocate(msg) {
if (msg.guild && msg.channel.permissionsFor(msg.guild.me).has(SEND)) return msg.channel;
else {
msg.author.send("I don't have permissions to send messages from the channel which you sent the command!");
return msg.author;
};
}
// set the prefix for the bot to use
function setPrefix(msg, prefix) {
let serverId = msg ? (msg.guild ? msg.guild.id : null) : null;
// only execute if we have a the server ID
if (serverId) {
// either set or show the prefix
if (prefix) {
// don't save when it's not needed
prefix = prefix.toLowerCase();
if (prefix == settings[serverId].prefix) {
msgLocate(msg).send('The bot already has the prefix `' + prefix + '`.');
return false;
} else {
settings[serverId].prefix = prefix;
saveSettings(serverId);
// need to update the status to use new prefix
client.user.setPresence({
status: 'available',
activity: {
name: PRESENCE_NAME,
type: PLAY,
url: GITHUB_REPO_URL
}
});
msgLocate(msg).send('The prefix has been set to `' + prefix + '`.');
return true;
}
} else {
msgLocate(msg).send('The current prefix is `' + settings[serverId].prefix + '`.');
return false;
}
} else {
msgLocate(msg).send('Error: Something went wrong setting the prefix.');
console.log(`Error: Set prefix failed, no server id.`);
return false;
}
}
// BOT FUNCTIONS
// sends and formats article post to discord, or to the feed channel if msg is null
function createArticlePost(msg, post) {
let serverId = msg ? (msg.guild ? msg.guild.id : null) : null;
// get the right and formatted information for title and body
let title = (post.title.replace(/\s/g, '').length > 0) ? htmlToText(post.title, { wordwrap: null }).replace(/\r/g, '').trim() : null;
let body = htmlToText(post.body.replace(/\r?\n|\r/g, ''), HTML_TO_TEXT).trim();
let sentences = body.split('\n');
// sometimes the title is in the body
if (!title) {
title = sentences.shift();
// remove the newlines before the next sentence
while (sentences[0] == '') sentences.shift();
}
// get the first sentence and separate from others
let firstSentence = sentences.shift();
let moreSentences = '\n' + sentences.join('\n');
// escape discord markdown symbols
title = escapeMarkdown(title);
firstSentence = convertToDiscord(firstSentence);
moreSentences = convertToDiscord(moreSentences);
// include the forum link (nice purpose for cases where articles have same slug article link)
let relatedForumURL = post.forumLink;
// start creating the embed
const embed = new Discord.MessageEmbed()
.setColor(MAIN_BOT_COLOR)
.setAuthor(moment(new Date(post.date)).format('DD MMM YYYY').toUpperCase())
.setTitle('__' + title + '__')
.setURL(EDN_ARTICLE_URL_PREFIX + post.slug)
.setFooter(new Date(post.date).toUTCString(), BOT_FOOTER_IMAGE);
(async () => {
// conditionally set image if there is one, else use a specific image
let imageToCheck;
let imageExists = true;
if (post.image && post.image.indexOf(',') != 0) {
let images = post.image.replace(/^,+/, '').split(',');
imageToCheck = EDN_ARTICLE_IMG_URL_PREFIX + images[0];
// only set the image if the file is online and working
await fetch(imageToCheck).then((response) => {
if (response.status >= 400 && response.status < 600) {
imageExists = false;
}
});
} else imageExists = false;
if (imageExists) embed.attachFiles([imageToCheck]);
else embed.attachFiles([EDN_ARTICLE_NO_IMAGE]);
// need to size differently for posts larger than 2048 characters
let relatedForumLink = '**[Related Forum](' + relatedForumURL + ')**';
let description = (firstSentence.length > 0) ? ('**' + firstSentence + '**') : '';
// continue with creating rest of description
description += (moreSentences.length > 0) ? moreSentences : '';
description += description ? ('\n\n' + relatedForumLink + '\n') : '\n'; // an ending newline is needed sometimes to cut the description correctly
const desc = [];
const endStringTests = ['\n\n', '\n'];
if (description.length > DESCRIPTION_LENGTH) {
let firstChunkEnd = -1;
let firstEndStringTestIndex = 0;
while (firstChunkEnd < 0 && firstEndStringTestIndex < endStringTests.length) {
let firstEndString = endStringTests[firstEndStringTestIndex];
// need to make sure that the first chunk ends at a double newline, single newline, space, or at max length
let newDescription = description.substring(0, DESCRIPTION_LENGTH + firstEndString.length);
firstChunkEnd = newDescription.lastIndexOf(firstEndString);
// can't go further if firstChunkEnd, wasn't found
if (firstChunkEnd > 0) {
// fix the newDescription to match requirements, and get the extended description
newDescription = description.substring(0, firstChunkEnd);
let extDescription = description.substring(firstChunkEnd + firstEndString.length);
desc.push(newDescription);
// need to dynamically create the new fields to overcome description/field string length restrictions
while (extDescription.length != 0) {
let iterationChunkEnd = -1;
let iterationEndStringTestIndex = 0;
while (iterationChunkEnd < 0 && iterationEndStringTestIndex < endStringTests.length) {
let iterationEndString = endStringTests[iterationEndStringTestIndex];
// similar chunking like in normal description
let newFieldValue = extDescription.substring(0, FIELD_VALUE_LENGTH + iterationEndString.length);
iterationChunkEnd = newFieldValue.lastIndexOf(iterationEndString);
// can't go further if iterationChunkEnd, wasn't found
if (iterationChunkEnd > 0) {
newFieldValue = extDescription.substring(0, iterationChunkEnd);
desc.push(newFieldValue);
extDescription = extDescription.substring(iterationChunkEnd + iterationEndString.length);
}
iterationEndStringTestIndex++;
}
}
}
firstEndStringTestIndex++;
}
} else desc.push(description);
// conditionally set description if there is one
embed.setDescription(desc[0]);
// for each part of description beyond the character limit, include as fields
if (desc.length > 1) {
for (let i = 1; i < desc.length; i++) {
embed.addField('\u200B', desc[i]);
}
}
// send to all discord servers feed channels if not part of msg
if (!msg) {
// need to loop through all servers loaded in settings
let seconds = 0;
let keys = Object.keys(settings);
for (let i = 0; i < keys.length; i++) {
// check if server has active feed channel
serverId = keys[i];
if (settings[serverId].feedChannel) {
let server = client.guilds.cache.get(serverId);
let channel = server.channels.cache.get(settings[serverId].feedChannel);
let mentionRole = settings[serverId].feedRole ? server.roles.cache.get(settings[serverId].feedRole).toString() : null;
// need to limit posting to avoid ratelimiting
setTimeout(function () {
// optionally included mention role
if (mentionRole) {
channel.send(mentionRole, embed).catch(err => {
// mention role has been deleted likely
console.error(`${serverId}: Has the role been deleted? Error: ` + err);
});
} else if (channel) {
channel.send(embed).catch(err => {
// channel has been deleted likely
console.error(`${serverId}: Do we have access to the channel? Error: ` + err);
});
} else if (!channel && server) {
console.error(`${serverId}: Has the channel been deleted?`);
} else { // !server
console.error(`${serverId}: Has the server been deleted?`);
}
}, ALL_POST_DELAY * (seconds + 1));
}
seconds++;
}
} else {
msgLocate(msg).send(embed).catch(err => {
console.error(`${serverId}: ` + err);
return false;
});
}
return true;
})();
}
// fetches all the posts in order and without being empty
async function fetchEdnArticles() {
let allNewsJSON = await fetch(EDN_JSON_URL);
// sadly need to sort all the posts first
let allNews = await allNewsJSON.json();
allNews.sort((a, b) => (new Date(b.date)) - (new Date(a.date)));
// then need to remove posts that have no description
for (let testBodyIndex = allNews.length - 1; testBodyIndex >= 0; testBodyIndex--) {
if (allNews[testBodyIndex].body.trim() == '') allNews.splice(testBodyIndex, 1);
}
return allNews;
}
// gets only the very most recent singular post from Elite Dangerous News
function getEdnTopPost(msg) {
(async () => {
let allNews = await fetchEdnArticles();
let post = allNews[0];
// post new article to channel or feed channel if it was a feed
createArticlePost(msg, post);
})();
}
// gets posts from elite dangerous news
// if nothing is entered, it'll grab the newest post(s),
// [for feed] but if a postNode is entered, it'll show old to new posts starting from and skipping postNode
function getEdnPosts(msg, postNode) {
return (async () => {
let allNews = await fetchEdnArticles();
// as long as we don't have a postNode, we need a date to check against
let checkDate = !postNode ? allNews[0].date : null;
let post = null;
// loop through all articles to find oldest with matching date
const TOTAL_ARTICLES = allNews.length;
let i = 0; // end index
let j = 0; // start index
let matched = false;
while (!matched && i < TOTAL_ARTICLES) {
post = allNews[i];
let peekPost = i < (TOTAL_ARTICLES - 1) ? allNews[i + 1] : null;
// if we have a date to check, else find postNode
if (checkDate) {
let currDate = post.date == checkDate;
let peekDate = peekPost && (peekPost.date == checkDate);
// need to include found node
if (!currDate && peekDate) j = i + 1;
if (currDate && !peekDate) matched = true;
else i++;
} else if (postNode) {
let currNode = post.nid == postNode;
let peekNode = peekPost && (peekPost.nid == postNode);
// need to exclude found node
if (!currNode && peekNode) j = i;
if (currNode && !peekNode) matched = true;
else i++;
}
}
// either start posting matching articles or a note about there being none
if (matched) {
let postIndex = 0;
// need to either get a chunch of same date posts, or get posts after matched post
let noErrors = true;
if (checkDate) {
// loop and send all articles that matched the date
for (let k = i; k >= j; k--) {
// must not take a post that has no description
let currentPost = allNews[k];
if (currentPost.body.trim() != '') {
setTimeout(function () {
if (!createArticlePost(msg, currentPost)) noErrors = false;
}, ALL_POST_DELAY * postIndex);
postIndex++;
}
}
} else if (postNode) {
// loop and send all articles after the matched date
for (let k = j; k >= 0; k--) {
// must not take a post that has no description
let currentPost = allNews[k];
if (currentPost.body.trim() != '') {
setTimeout(function () {
if (!createArticlePost(msg, currentPost)) noErrors = false;
}, ALL_POST_DELAY * postIndex);
postIndex++;
}
}
}
return noErrors;
} else {
msgLocate(msg).send('Sorry, but no articles exist for the date you entered.');
return true;
}
})();
}
// sets the role to mention for the feed, role name/mention is required
function setFeedRole(msg, roleArgs) {
let serverId = msg ? (msg.guild ? msg.guild.id : null) : null;
// only execute if we have the server ID
if (serverId) {
// return if there is no channel set
if (!settings[serverId] || !settings[serverId].feedChannel) {
msgLocate(msg).send("Sorry, but there's no channel set for the feed to send messages and mention in.");
return false;
}
// need to get actual roleArg
let roleArg;
if (roleArgs.length > 1) {
roleArg = roleArgs.join(' ');
} else roleArg = roleArgs[0];
// check if the role is valid to get a role ID
let roleId = null;
if (roleArg) {
checkRoleMention = getRoleFromMention(roleArg);
if (checkRoleMention) roleId = checkRoleMention;
else {
// if name has spaces, remove the quotes encasing the argument
if (roleArg.length > 3 &&
roleArg.startsWith('"') && roleArg.endsWith('"')) roleArg = roleArg.slice(1, -1);
// continue checking like normal
if (roleArg.length > 1) {
// check for name to get role ID
roleId = msg.guild.roles.cache.find(role => role.name === roleArg).id;
// else check to see if we were given an id
if (!roleId) roleId = msg.guild.roles.cache.find(role => role.id === roleArg).id;
}
}
} else roleId = settings[serverId].feedRole; // where the following if will disable it
if (roleId) {
let roleResult = true;
// dependant on permissions or choice, set or unset feed role
let botHasEveryonePermission = msg.guild.channels.cache.get(settings[serverId].feedChannel).permissionsFor(msg.guild.me).has(EVERYONE);
if (roleId == settings[serverId].feedRole) {
// unsets role
settings[serverId].feedRole = null;
msgLocate(msg).send('The feed role mention is now turned off.');
} else if (msg.guild.roles.cache.get(roleId).mentionable) {
// checks if the role itself is mentionable by everyone, then sets role
settings[serverId].feedRole = roleId;
msgLocate(msg).send('Automatic feed role mention changed to ' + msg.guild.roles.cache.get(roleId).toString() + '.', { 'allowedMentions': { 'users': [] } });
} else if (botHasEveryonePermission) {
// checks if the bot has permissions to mention everyone, then sets role
settings[serverId].feedRole = roleId;
msgLocate(msg).send('Automatic feed role mention changed to ' + msg.guild.roles.cache.get(roleId).toString() + '.', { 'allowedMentions': { 'users': [] } });
} else if (!botHasEveryonePermission && (roleId == msg.guild.roles.cache.everyone.id || roleId == msg.guild.roles.cache.here.id)) {
// throw error when bot can't mention @everyone or @here
msgLocate(msg).send("Sorry, but I don't have the permission to mention everyone/here in the currently set channel.");
roleResult = false;
} else {
// if all else fails, then the bot can't mention the role for some reason
msgLocate(msg).send("Sorry, but that role is currently not mentionable. Please make sure that the bot has permissions to mention anyone, or that the role itself is mentionable by everyone.");
}
saveSettings(serverId);
return roleResult;
} else {
if (roleArg) msgLocate(msg).send("Sorry, that's either not a real role or it was entered incorrectly.");
else msgLocate(msg).send("Sorry, but you need to include the role to be mentioned.");
return false;
}
} else {
msgLocate(msg).send('Error: Something went wrong setting the feed role.');
console.log(`Error: Set feed role failed, no server id.`);
return false;
}
}
// sets the channel for the feed, channel name/mention is optional
function setFeedChannel(msg, channelArg) {
let serverId = msg ? (msg.guild ? msg.guild.id : null) : null;
let channelId = null;
// only execute if we have the server ID
if (serverId) {
// check if the channel name is valid to get a channel ID
if (channelArg) {
checkChannelMention = getChannelFromMention(channelArg);
if (checkChannelMention) channelId = checkChannelMention;
else if (channelArg.length > 1) {
// check for one word name to get channel ID
channelId = msg.guild.channels.cache.find(channel => channel.name === channelArg.toLowerCase()).id;
// else check to see if we were given an id
if (!channelId) channelId = msg.guild.channels.cache.find(channel => channel.id === channelArg).id;
}
} else {
// use current channel
channelId = msg.channel.id;
}
if (channelId) {
if (channelId == settings[serverId].feedChannel) {
settings[serverId].feedChannel = null;
settings[serverId].feedRole = null;
msgLocate(msg).send('The feed is now turned off.');
} else if (msg.guild.channels.cache.get(channelId).permissionsFor(msg.guild.me).has(SEND)) {
settings[serverId].feedChannel = channelId;
msgLocate(msg).send('Automatic feed channel changed to ' + msg.guild.channels.cache.get(channelId).toString() + '.');
} else {
msgLocate(msg).send("Sorry, but I don't have the permission to send messages in that channel.");
}
saveSettings(serverId);
return true;
} else {
msgLocate(msg).send("Sorry, that's either not a real channel or it was entered incorrectly.");
return false;
}
} else {
msgLocate(msg).send('Error: Something went wrong setting the feed channel.');
console.log(`Error: Set feed channel failed, no server id.`);
return false;
}
}
// this will check for new posts, and update the newest post file information
function checkFeed() {
(async () => {
// start checking for new posts
let allNews = await fetchEdnArticles();
let post = allNews[0];
let newPostAvailable = true;
let checkPostNode = post.nid;
// check for file existence before trying to load
let data;
let filePostNode;
try {
data = fs.readFileSync(NEWEST_POST_FILE, 'utf8');
// check first line of file with string of feed
filePostNode = data.toString().replace(/\n$/, '');
// check to make sure we actually have a new post
if (checkPostNode == filePostNode) newPostAvailable = false;
} catch (err) {
console.log('Feed file will be initialized.');
}
// if there's still a new post available, save it
if (newPostAvailable) {
console.log(`Found a new post from Elite Dangerous News at: ${ED_NODE_URL_PREFIX}${checkPostNode}`);
// get post(s) after the last known post (via node compare) from json file
if (getEdnPosts(null, filePostNode)) {
// write to file
try {
fs.writeFileSync(NEWEST_POST_FILE, checkPostNode + '\n');
} catch (err) {
console.error(err)
}
}
} // else console.log(`No new post found, latest is still at: ${ED_NODE_URL_PREFIX}${checkPostNode}`);
return newPostAvailable;
})();
}
// MAIN START
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
// show connected servers
let numOfServers = logConnectedServers();
if (numOfServers) console.log(`Connected to ${numOfServers} servers in total.`);
else console.log('Not connected to any servers at the moment.');
// load settings in first
loadSettings();
// set status after settings are loaded in
client.user.setPresence({
status: 'available',
activity: {
name: PRESENCE_NAME,
type: PLAY,
url: GITHUB_REPO_URL
}
});
// start interval checking of the JSON feed to update channel