forked from creesch/discordIRCd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
1496 lines (1174 loc) · 59.4 KB
/
server.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
// When false nothing will be logged.
// Configuration goes here.
require('./config.js');
if (!configuration.DEBUG) {
console.log = function() {};
}
const Discord = require("discord.js");
const fs = require('fs');
let net;
let netOptions = {};
if (configuration.tlsEnabled) {
net = require('tls');
netOptions = {
key: fs.readFileSync(configuration.tlsOptions.keyPath),
cert: fs.readFileSync(configuration.tlsOptions.certPath)
}
} else {
net = require('net');
}
let request;
if (configuration.handleCode) {
request = require('request');
}
//
// Let's ready some variables and stuff we will use later on.
//
// Object which will contain channel information.
let ircDetails = {
DMserver: {
lastPRIVMSG: []
}
};
// Since we want a seperate connection for each discord server we will need to store our sockets.
let ircClients = [];
// Simply used to give each new socket a unique number.
let ircClientCount = 0;
// This is used to make sure that if discord reconnects not everything is wiped.
let discordFirstConnection = true;
// Max line lenght for irc messages.
const maxLineLength = 510;
//
// Generic functions
//
// Function that parses irc messages.
// Shamelessly stolen from node-irc https://github.com/aredridel/node-ircd
function parseMessage(line) {
let message = {};
let m = /(:[^ ]+ )?([A-Z0-9]+)(?: (.*))?/i.exec(line);
if (!m) {
message['error'] = 'Unable to parse message';
} else {
let i;
if (m[3] && (i = m[3].indexOf(':')) !== -1) {
let rest = m[3].slice(i + 1);
message.params = m[3].slice(0, i - 1).split(' ');
message.params.push(rest);
} else {
if (m[3]) {
message.params = m[3].split(' ');
} else {
message.params = [];
}
}
if (m[2]) {
message.command = m[2].toUpperCase();
}
if (m[1]) {
message.sender = m[1];
}
}
return message;
}
// Returns a number based on the discord server that increases per call.
// Used to make fairly sure nicknames on irc end up being unique after being scrubbed.
// Make nicknames work for irc.
function ircNickname(discordDisplayName, botuser, discriminator) {
const replaceRegex = /[^a-zA-Z0-9_\\[\]\{\}\^`\|]/g;
const shortenRegex = /_+/g;
if (replaceRegex.test(discordDisplayName)) {
let newDisplayname = `${discordDisplayName.replace(replaceRegex, '_')}${discriminator}`;
newDisplayname = newDisplayname.replace(shortenRegex, '_');
return botuser ? `${newDisplayname}[BOT]` : newDisplayname;
} else {
return botuser ? `${discordDisplayName}[BOT]` : discordDisplayName;
}
}
// Parses discord lines to make them work better on irc.
function parseDiscordLine(line, discordID) {
// Discord markdown parsing the lazy way. Probably fails in a bunch of different ways but at least it is easy.
line = line.replace(/\*\*(.*?)\*\*/g, '\x02$1\x0F');
line = line.replace(/\*(.*?)\*/g, '\x1D$1\x0F');
line = line.replace(/^_(.*?)\_$/g, '\x01ACTION $1\x01');
line = line.replace(/__(.*?)__/g, '\x1F$1\x0F');
// With the above regex we might end up with to many end characters. This replaces the,
line = line.replace(/\x0F{2,}/g, '\x0F');
// Now let's replace mentions with names we can recognize.
const mentionUserRegex = /(<@!?\d+?>)/g;
const mentionUserFound = line.match(mentionUserRegex);
if (mentionUserFound) {
mentionUserFound.forEach(function(mention) {
const userID = mention.replace(/<@!?(\d+?)>/, '$1');
const memberObject = discordClient.guilds.get(discordID).members.get(userID);
const displayName = memberObject.displayName;
const isBot = memberObject.user.bot;
const discriminator = memberObject.user.discriminator;
const userName = ircNickname(displayName, isBot, discriminator);
const replaceRegex = new RegExp(mention, 'g');
if (userName) {
line = line.replace(replaceRegex, `@${userName}`);
}
});
}
// Now let's do this again and replace mentions with roles we can recognize.
const mentionRoleRegex = /(<@&\d+?>)/g;
const mentionRoleFound = line.match(mentionRoleRegex);
if (mentionRoleFound) {
mentionRoleFound.forEach(function(mention) {
const roleID = mention.replace(/<@&(\d+?)>/, '$1');
const roleObject = discordClient.guilds.get(discordID).roles.get(roleID);
const replaceRegex = new RegExp(mention, 'g');
if (roleObject) {
const name = roleObject.name;
line = line.replace(replaceRegex, `@${name}`);
}
});
}
// Channels are also a thing!.
const mentionChannelRegex = /(<#\d+?>)/g;
const mentionChannelFound = line.match(mentionChannelRegex);
if (mentionChannelFound) {
mentionChannelFound.forEach(function(mention) {
const channelID = mention.replace(/<#(\d+?)>/, '$1');
const channelObject = discordClient.guilds.get(discordID).channels.get(channelID);
const replaceRegex = new RegExp(mention, 'g');
if (channelObject) {
const name = channelObject.name;
line = line.replace(replaceRegex, `#${name}`);
}
});
}
return line;
}
// Parse irc lines to make them work better on discord.
function parseIRCLine(line, discordID, channel) {
line = line.replace(/\001ACTION(.*?)\001/g, '_$1_');
// Discord-style username mentions (@User)
const mentionDiscordRegex = /(@.+?\s)/g;
const mentionDiscordFound = line.match(mentionDiscordRegex);
if (mentionDiscordFound) {
mentionDiscordFound.forEach(function(mention) {
const userNickname = mention.replace(/@(.+?)\s/, '$1');
if (ircDetails[discordID].channels[channel].members.hasOwnProperty(userNickname)) {
const userID = ircDetails[discordID].channels[channel].members[userNickname].id;
const replaceRegex = new RegExp(mention, 'g');
line = line.replace(replaceRegex, `<@!${userID}> `);
}
});
}
// IRC-style username mentions (User: at the start of the line)
const mentionIrcRegex = /(^.+?:)/g;
const mentionIrcFound = line.match(mentionIrcRegex);
if (mentionIrcFound) {
mentionIrcFound.forEach(function(mention) {
const userNickname = mention.replace(/^(.+?):/, '$1');
if (ircDetails[discordID].channels[channel].members.hasOwnProperty(userNickname)) {
const userID = ircDetails[discordID].channels[channel].members[userNickname].id;
const replaceRegex = new RegExp(mention, 'g');
line = line.replace(replaceRegex, `<@!${userID}>`);
}
});
}
// Channel names
const mentionChannelRegex = /(#.+?\s)/g;
const mentionChannelFound = line.match(mentionChannelRegex);
if (mentionChannelFound) {
mentionChannelFound.forEach(function(mention) {
const channelName = mention.replace(/#(.+?)\s/, '$1');
if (ircDetails[discordID].channels.hasOwnProperty(channelName)) {
const userID = ircDetails[discordID].channels[channelName].id;
const replaceRegex = new RegExp(mention, 'g');
line = line.replace(replaceRegex, `<#${userID}> `);
}
});
}
return line;
}
//
// Discord related functionality.
//
// Create our discord client.
let discordClient = new Discord.Client({
fetchAllMembers: true,
sync: true
});
// Log into discord using the token defined in config.js
discordClient.login(configuration.discordToken);
//
// Various events used for debugging.
//
// Will log discord debug information.
discordClient.on('debug', function(info) {
console.log('debug', info);
});
// When debugging we probably want to know about errors as well.
discordClient.on('error', function(info) {
console.log('error', info);
sendGeneralNotice('Discord error.');
});
// Emitted when the Client tries to reconnect after being disconnected.
discordClient.on('reconnecting', function() {
console.log('reconnecting');
sendGeneralNotice('Reconnecting to Discord.');
});
// Emitted whenever the client websocket is disconnected.
discordClient.on('disconnect', function(event) {
console.log('disconnected', event);
sendGeneralNotice('Discord has been disconnected.');
});
// Emitted for general warnings.
discordClient.on('warn', function(info) {
console.log('warn', info);
});
// Discord is ready.
discordClient.on('ready', function() {
// This is probably not needed, but since sometimes things are weird with discord.
discordClient.guilds.array().forEach(function(guild) {
guild.fetchMembers();
guild.sync();
});
console.log(`Logged in as ${discordClient.user.username}!`);
// Lets grab some basic information we will need eventually.
// But only do so if this is the first time connecting.
if (discordFirstConnection) {
discordFirstConnection = false;
discordClient.guilds.array().forEach(function(guild) {
const guildID = guild.id;
if (!ircDetails.hasOwnProperty(guildID)) {
ircDetails[guildID] = {
lastPRIVMSG: [],
channels: {},
members: {}
};
}
guild.members.array().forEach(function(member) {
const ircDisplayName = ircNickname(member.displayName, member.user.bot, member.user.discriminator);
ircDetails[guildID].members[ircDisplayName] = member.id;
});
});
discordClient.channels.array().forEach(function(channel) {
// Of course only for channels.
if (channel.type === 'text') {
const guildID = channel.guild.id,
channelName = channel.name,
channelID = channel.id,
channelTopic = channel.topic || 'No topic';
ircDetails[guildID].channels[channelName] = {
id: channelID,
joined: [],
topic: channelTopic
};
}
});
// Now that is done we can start the irc server side of things.
ircServer.listen(configuration.ircServer.listenPort);
} else {
sendGeneralNotice('Discord connection has been restored.');
}
});
//
// Acting on events
//
// There are multiple events that indicate a users is no longer on the server.
// We abuse the irc QUIT: message for this even if people are banned.
function guildMemberNoMore(guildID, ircDisplayName, noMoreReason) {
let found = false;
// First we go over the channels.
for (let channel in ircDetails[guildID].channels) {
if (ircDetails[guildID].channels.hasOwnProperty(channel) && ircDetails[guildID].channels[channel].joined.length > 0) {
let channelMembers = ircDetails[guildID].channels[channel].members;
// Within the channels we go over the members.
if (channelMembers.hasOwnProperty(ircDisplayName)) {
if (!found) {
let memberDetails = ircDetails[guildID].channels[channel].members[ircDisplayName];
console.log(`User ${ircDisplayName} quit ${noMoreReason}`);
ircDetails[guildID].channels[channel].joined.forEach(function(socketID) {
sendToIRC(guildID, `:${ircDisplayName}!${memberDetails.id}@whatever QUIT :${noMoreReason}\r\n`, socketID);
});
found = true;
}
delete ircDetails[guildID].channels[channel].members[ircDisplayName];
}
}
}
if (noMoreReason !== 'User gone offline') {
delete ircDetails[guildID].members[ircDisplayName];
}
}
function guildMemberCheckChannels(guildID, ircDisplayName, guildMember) {
// First we go over the channels.
for (let channel in ircDetails[guildID].channels) {
if (ircDetails[guildID].channels.hasOwnProperty(channel) && ircDetails[guildID].channels[channel].joined.length > 0) {
let isInDiscordChannel = false;
let isCurrentlyInIRC = false;
let channelDetails = ircDetails[guildID].channels[channel];
let channelMembers = channelDetails.members;
let channelID = channelDetails.id;
//Let's check the discord channel.
let discordMemberArray = discordClient.guilds.get(guildID).channels.get(channelID).members.array();
discordMemberArray.forEach(function(discordMember) {
if (guildMember.displayName === discordMember.displayName && (guildMember.presence.status !== 'offline' || configuration.showOfflineUsers)) {
isInDiscordChannel = true;
}
});
// Within the channels we go over the members.
if (channelMembers.hasOwnProperty(ircDisplayName)) {
// User found for channel.
isCurrentlyInIRC = true;
}
// If the user is in the discord channel but not irc we will add the user.
if (!isCurrentlyInIRC && isInDiscordChannel) {
ircDetails[guildID].channels[channel].members[ircDisplayName] = {
discordName: guildMember.displayName,
discordState: guildMember.presence.status,
ircNick: ircDisplayName,
id: guildMember.id
};
console.log(`User ${ircDisplayName} joined ${channel}`);
ircDetails[guildID].channels[channel].joined.forEach(function(socketID) {
sendToIRC(guildID, `:${ircDisplayName}!${guildMember.id}@whatever JOIN #${channel}\r\n`, socketID);
const socketDetails = getSocketDetails(socketID);
if (guildMember.presence === 'idle' && socketDetails.awayNotify) {
console.log(`User ${ircDisplayName} is away: Idle`);
sendToIRC(guildID, `:${ircDisplayName}!${guildMember.id}@whatever AWAY :Idle\r\n`, socketID);
}
if (guildMember.presence === 'dnd' && socketDetails.awayNotify) {
console.log(`User ${ircDisplayName} is away: Do not disturb`);
sendToIRC(guildID, `:${ircDisplayName}!${guildMember.id}@whatever AWAY :Do not disturb\r\n`, socketID);
}
// Unlikely to happen, but just to be sure.
if (guildMember.presence === 'offline' && configuration.showOfflineUsers && socketDetails.awayNotify) {
console.log(`User ${ircDisplayName} is offline`);
sendToIRC(guildID, `:${ircDisplayName}!${guildMember.id}@whatever AWAY :Offline\r\n`, socketID);
}
});
}
// If the user is currently in irc but not in the discord channel they have left the channel.
if (isCurrentlyInIRC && !isInDiscordChannel) {
ircDetails[guildID].channels[channel].joined.forEach(function(socketID) {
console.log(`User ${ircDisplayName} left ${channel}`);
sendToIRC(guildID, `:${ircDisplayName}!${guildMember.id}@whatever PART #${channel}\r\n`, socketID);
delete ircDetails[guildID].channels[channel].members[ircDisplayName];
});
}
}
}
}
function guildMemberNickChange(guildID, oldIrcDisplayName, newIrcDisplayName, newDiscordDisplayName) {
// First we go over the channels.
let foundInChannels = false;
let memberId;
ircDetails[guildID].members[newIrcDisplayName] = ircDetails[guildID].members[oldIrcDisplayName];
delete ircDetails[guildID].members[oldIrcDisplayName];
for (let channel in ircDetails[guildID].channels) {
if (ircDetails[guildID].channels.hasOwnProperty(channel) && ircDetails[guildID].channels[channel].joined.length > 0) {
let channelDetails = ircDetails[guildID].channels[channel];
let channelMembers = channelDetails.members;
// Within the channels we go over the members.
if (channelMembers.hasOwnProperty(oldIrcDisplayName)) {
let tempMember = channelMembers[oldIrcDisplayName];
tempMember.displayName = newDiscordDisplayName;
tempMember.ircNick = newIrcDisplayName;
memberId = tempMember.id;
delete ircDetails[guildID].channels[channel].members[oldIrcDisplayName];
ircDetails[guildID].channels[channel].members[oldIrcDisplayName] = tempMember;
foundInChannels = true;
}
}
}
if (foundInChannels) {
console.log(`Changing nickname ${oldIrcDisplayName} into ${newIrcDisplayName}`);
sendToIRC(guildID, `:${oldIrcDisplayName}!${memberId}@whatever NICK ${newIrcDisplayName}\r\n`);
}
}
discordClient.on('guildMemberRemove', function(GuildMember) {
if (ircClients.length > 0) {
console.log('guildMemberRemove');
const guildID = GuildMember.guild.id;
const isBot = GuildMember.user.bot;
const discriminator = GuildMember.user.discriminator;
const ircDisplayName = ircNickname(GuildMember.displayName, isBot, discriminator);
guildMemberNoMore(guildID, ircDisplayName, 'User removed');
}
});
discordClient.on('presenceUpdate', function(oldMember, newMember) {
if (ircClients.length > 0) {
const guildID = newMember.guild.id;
const isBot = newMember.user.bot;
const discriminator = newMember.user.discriminator;
const ircDisplayName = ircNickname(newMember.displayName, isBot, discriminator);
const oldPresenceState = oldMember.presence.status;
const newPresenceState = newMember.presence.status;
if (oldPresenceState === 'offline' && !configuration.showOfflineUsers) {
guildMemberCheckChannels(guildID, ircDisplayName, newMember);
} else if (newPresenceState === 'offline' && !configuration.showOfflineUsers) {
guildMemberNoMore(guildID, ircDisplayName, 'User gone offline');
} else if (configuration.showOfflineUsers) {
ircClients.forEach(function(socket) {
if (socket.awayNotify) {
// Technically we could just do socket.writeline for these. But for consistency we go through the sendToIRC function.
if (newPresenceState === 'offline' && configuration.showOfflineUsers) {
sendToIRC(guildID, `:${ircDisplayName}!${newMember.id}@whatever AWAY :Offline\r\n`, socket.ircid);
} else if (newPresenceState === 'dnd') {
sendToIRC(guildID, `:${ircDisplayName}!${newMember.id}@whatever AWAY :Do not disturb\r\n`, socket.ircid);
} else if (newPresenceState === 'idle') {
sendToIRC(guildID, `:${ircDisplayName}!${newMember.id}@whatever AWAY :Idle\r\n`, socket.ircid);
} else if (oldPresenceState !== 'offline' && newPresenceState === 'online') {
sendToIRC(guildID, `:${ircDisplayName}!${newMember.id}@whatever AWAY\r\n`, socket.ircid);
}
}
});
}
}
});
discordClient.on('guildMemberUpdate', function(oldMember, newMember) {
if (ircClients.length > 0) {
console.log('guildMemberUpdate');
const guildID = newMember.guild.id;
const oldIsBot = oldMember.user.bot;
const newIsBot = newMember.user.bot;
const discriminator = newMember.user.discriminator;
const oldIrcDisplayName = ircNickname(oldMember.displayName, oldIsBot, discriminator);
const newIrcDisplayName = ircNickname(newMember.displayName, newIsBot, discriminator);
const newDiscordDisplayName = newMember.displayName;
if (oldIrcDisplayName !== newIrcDisplayName) {
if (newMember.id === discordClient.user.id) {
sendToIRC(newMember.guild.id, `:${oldIrcDisplayName}!${discordClient.user.id}@whatever NICK ${newIrcDisplayName}\r\n`);
} else {
guildMemberNickChange(guildID, oldIrcDisplayName, newIrcDisplayName, newDiscordDisplayName);
}
} else {
guildMemberCheckChannels(guildID, newIrcDisplayName, newMember);
}
}
});
discordClient.on('guildMemberAdd', function(GuildMember) {
if (ircClients.length > 0) {
console.log('guildMemberAdd');
const guildID = GuildMember.guild.id;
const isBot = GuildMember.user.bot;
const discriminator = GuildMember.user.discriminator;
const ircDisplayName = ircNickname(GuildMember.displayName, isBot, discriminator);
guildMemberCheckChannels(guildID, ircDisplayName, GuildMember);
}
});
discordClient.on('channelCreate', function(newChannel) {
if (newChannel.type === 'text') {
const discordServerId = newChannel.guild.id;
ircDetails[discordServerId].channels[newChannel.name] = {
id: newChannel.id,
members: {},
topic: newChannel.topic || 'No topic',
joined: []
};
}
});
discordClient.on('channelDelete', function(deletedChannel) {
if (deletedChannel.type === 'text') {
const discordServerId = deletedChannel.guild.id;
if (ircDetails[discordServerId].channels[deletedChannel.name].joined.length > 0) {
const PartAlertMessage = `:discordIRCd!notReallyA@User PRIVMSG #${deletedChannel.name} :#${deletedChannel.name} has been deleted \r\n`;
sendToIRC(discordServerId, PartAlertMessage);
const joinedSockets = ircDetails[discordServerId].channels[deletedChannel.name].joined;
joinedSockets.forEach(function(socketID) {
// First we inform the user in the old channelContent
partCommand(deletedChannel.name, discordServerId, socketID);
});
}
// Finally remove the channel from the list.
delete ircDetails[discordServerId].channels[deletedChannel.name];
}
});
discordClient.on('channelUpdate', function(oldChannel, newChannel) {
const discordServerId = oldChannel.guild.id;
console.log('channel updated');
if (oldChannel.type === 'text') {
if (oldChannel.name !== newChannel.name) {
console.log(`channel name changed from #${oldChannel.name} to #${newChannel.name}`);
ircDetails[discordServerId].channels[newChannel.name] = {
id: newChannel.id,
members: {},
topic: newChannel.topic || 'No topic',
joined: []
};
if (ircDetails[discordServerId].channels[oldChannel.name].joined.length > 0) {
const PartAlertMessage = `:discordIRCd!notReallyA@User PRIVMSG #${oldChannel.name} :#${oldChannel.name} has been renamed to #${newChannel.name} \r\n`;
sendToIRC(discordServerId, PartAlertMessage);
const joinedSockets = ircDetails[discordServerId].channels[oldChannel.name].joined;
joinedSockets.forEach(function(socketID) {
// First we inform the user in the old channelContent
partCommand(oldChannel.name, discordServerId, socketID);
joinCommand(newChannel.name, discordServerId, socketID);
});
}
// Delete the old one.
delete ircDetails[discordServerId].channels[oldChannel.name];
}
}
// Simple topic change.
if (oldChannel.topic !== newChannel.topic) {
const topic = newChannel.topic || 'No topic';
ircClients.forEach(function(socket) {
if (socket.discordid === discordServerId && ircDetails[discordServerId].channels[newChannel.name].joined.indexOf(socket.ircid) > -1) {
const topicMSG = `:noboyknows!orCares@whatever TOPIC #${newChannel.name} :${topic}\r\n`;
sendToIRC(discordServerId, topicMSG, socket.ircid);
}
});
}
});
// Processing received messages
discordClient.on('message', function(msg) {
if (ircClients.length > 0 && msg.channel.type === 'text') {
const discordServerId = msg.guild.id;
// Webhooks don't have a member.
let authorDisplayName;
if (msg.member) {
authorDisplayName = msg.member.displayName;
} else {
authorDisplayName = msg.author.username;
}
const isBot = msg.author.bot;
const discriminator = msg.author.discriminator;
const authorIrcName = ircNickname(authorDisplayName, isBot, discriminator);
const channelName = msg.channel.name;
// Doesn't really matter socket we pick this from as long as it is connected to the discord server.
let ownNickname = getSocketDetails(ircDetails[discordServerId].channels[channelName].joined[0]).nickname;
let messageContent = msg.content;
if (configuration.handleCode) {
const codeRegex = /```(.*?)\r?\n([\s\S]*?)```/;
const replaceRegex = /```.*?\r?\n[\s\S]*?```/;
if (codeRegex.test(messageContent)) {
const codeDetails = messageContent.match(codeRegex);
// In the future I want to include the url in the message. But since the call to gist is async that doesn't fit the current structure.
messageContent = messageContent.replace(replaceRegex, '');
let extension;
let language;
if (codeDetails[1]) {
language = codeDetails[1].toLowerCase();
switch (language) {
case 'javascript':
extension = 'js';
break;
case 'html':
extension = 'html';
break;
case 'css':
extension = 'css';
break;
case 'xml':
extension = 'xml';
break;
case 'python':
extension = 'py';
break;
case 'c#':
extension = 'cs';
break;
case 'c++':
extension = 'cc';
break;
case 'php':
extension = 'php';
break;
default:
extension = 'txt';
break;
}
} else {
extension = 'txt';
language = 'unknown';
}
const gistFileName = `${authorIrcName}_code.${extension}`;
let postBody = {
description: `Code block on ${msg.guild.name} in channel ${channelName} from ${authorIrcName}`,
public: false,
files: {
}
};
postBody.files[gistFileName] = {
'content': codeDetails[2]
};
let gistOptions = {
url: 'https://api.github.com/gists',
headers: {
'Authorization': `token ${configuration.githubToken}`,
'User-Agent': 'discordIRCd'
},
method: 'POST',
json: postBody
};
request(gistOptions, function(error, response, body) {
if (error) {
console.log('Gist error:', error);
}
if (!error && response.statusCode === 201) {
console.log(body.html_url);
const gistMessage = `:${authorIrcName}!${msg.author.id}@whatever PRIVMSG #${channelName} :${body.html_url}\r\n`;
ircDetails[discordServerId].channels[channelName].joined.forEach(function(socketID) {
sendToIRC(discordServerId, gistMessage, socketID);
});
}
if (!error && response.statusCode !== 201) {
console.log('Something went wrong on the gist side of things:', response.statusCode);
}
});
}
}
let memberMentioned = false;
let memberDirectlyMentioned = false;
const ownGuildMember = discordClient.guilds.get(discordServerId).members.get(discordClient.user.id);
if (msg.mentions.roles.array().length > 0) {
ownGuildMember.roles.array().forEach(function(role) {
if (msg.isMentioned(role)) {
memberMentioned = true;
}
});
}
if (msg.mentions.everyone) {
memberMentioned = true;
}
// Only add it if the nickname is known. If it is undefined the client is not in the channel and will be notified through PM anyway.
if (memberMentioned && ownNickname) {
messageContent = `${ownNickname}: ${messageContent}`;
}
if (msg.mentions.users.array().length > 0) {
if (msg.isMentioned(ownGuildMember)) {
memberDirectlyMentioned = true;
}
}
// Only act on text channels and if the user has joined them in irc or if the user is mentioned in some capacity.
if (ircDetails[discordServerId].channels[channelName].joined.length > 0 || memberMentioned || memberDirectlyMentioned) {
// IRC does not handle newlines. So we split the message up per line and send them seperatly.
const messageArray = messageContent.split(/\r?\n/);
const attachmentArray = msg.attachments.array();
if (attachmentArray.length > 0) {
attachmentArray.forEach(function(attachment) {
const filename = attachment.filename;
const url = attachment.url;
const attachmentLine = `${filename}: ${url}`;
messageArray.push(attachmentLine);
});
}
messageArray.forEach(function(line) {
const messageTemplate = `:${authorIrcName}!${msg.author.id}@whatever PRIVMSG #${channelName} :`;
const messageTemplateLength = messageTemplate.length;
const remainingLength = maxLineLength - messageTemplateLength;
const matchRegex = new RegExp(`[\\s\\S]{1,${remainingLength}}`, 'g');
const linesArray = line.match(matchRegex) || [];
linesArray.forEach(function(sendLine) {
// Trying to prevent messages from irc echoing back and showing twice.
if (ircDetails[discordServerId].lastPRIVMSG.indexOf(sendLine) < 0) {
const lineToSend = parseDiscordLine(sendLine, discordServerId);
const message = `${messageTemplate}${lineToSend}\r\n`;
ircDetails[discordServerId].channels[channelName].joined.forEach(function(socketID) {
sendToIRC(discordServerId, message, socketID);
});
// Let's make people aware they are mentioned in channels they are not in.
if (memberMentioned || memberDirectlyMentioned) {
ircClients.forEach(function(socket) {
if (socket.discordid === discordServerId && ircDetails[discordServerId].channels[channelName].joined.indexOf(socket.ircid) === -1) {
const message = `:discordIRCd!notReallyA@User PRIVMSG discordIRCd :#${channelName}: <${authorDisplayName}> ${lineToSend}\r\n`;
sendToIRC(discordServerId, message, socket.ircid);
}
});
}
}
});
});
}
}
if (ircClients.length > 0 && msg.channel.type === 'dm') {
const discordServerId = 'DMserver';
const authorDisplayName = msg.author.username;
const authorIsBot = msg.author.bot;
const authorDiscriminator = msg.author.discriminator;
const authorIrcName = ircNickname(authorDisplayName, authorIsBot, authorDiscriminator);
const recipientIsBot = msg.channel.recipient.bot;
const recipientDiscriminator = msg.channel.recipient.discriminator;
const recipient = ircNickname(msg.channel.recipient.username, recipientIsBot, recipientDiscriminator);
let ownNickname;
ircClients.forEach(function(socket) {
if (socket.discordid === discordServerId) {
ownNickname = socket.nickname;
}
});
let messageTemplate;
if (authorIrcName === ownNickname) {
messageTemplate = `:${authorIrcName}!${msg.author.id}@whatever PRIVMSG ${recipient} :`;
} else {
messageTemplate = `:${authorIrcName}!${msg.author.id}@whatever PRIVMSG ${ownNickname} :`;
}
// IRC does not handle newlines. So we split the message up per line and send them seperatly.
const messageArray = msg.content.split(/\r?\n/);
messageArray.forEach(function(line) {
const messageTemplateLength = messageTemplate.length;
const remainingLength = maxLineLength - messageTemplateLength;
const matchRegex = new RegExp(`[\\s\\S]{1,${remainingLength}}`, 'g');
const linesArray = line.match(matchRegex) || [];
linesArray.forEach(function(sendLine) {
// Trying to prevent messages from irc echoing back and showing twice.
if (ircDetails[discordServerId].lastPRIVMSG.indexOf(sendLine) < 0) {
const lineToSend = parseDiscordLine(sendLine, discordServerId);
const message = `${messageTemplate}${lineToSend}\r\n`;
sendToIRC(discordServerId, message);
}
});
});
const attachmentArray = msg.attachments.array();
if (attachmentArray.length > 0) {
attachmentArray.forEach(function(attachment) {
const filename = attachment.filename;
const url = attachment.url;
const attachmentLine = `${filename}: ${url}`;
const message = `${messageTemplate}${attachmentLine}\r\n`;
sendToIRC(discordServerId, message);
});
}
}
});
// Join command given, let's join the channel.
function joinCommand(channel, discordID, socketID) {
let members = '';
let memberListLines = [];
const nickname = ircDetails[discordID].ircDisplayName;
const memberlistTemplate = `:${configuration.ircServer.hostname} 353 ${nickname} @ #${channel} :`;
const memberlistTemplateLength = memberlistTemplate.length;
if (ircDetails[discordID].channels.hasOwnProperty(channel)) {
const channelProperties = ircDetails[discordID].channels[channel];
const channelContent = discordClient.channels.get(channelProperties.id);
ircDetails[discordID].channels[channel].joined.push(socketID);
ircDetails[discordID].channels[channel]['members'] = {};
const channelTopic = channelProperties.topic;
channelContent.members.array().forEach(function(member) {
const isBot = member.user.bot;
const discriminator = member.user.discriminator;
const displayMember = ircNickname(member.displayName, isBot, discriminator);
if (member.presence.status === 'online' ||
member.presence.status === 'idle' ||
member.presence.status === 'dnd' ||
(member.presence.status === 'offline' && configuration.showOfflineUsers)) {
ircDetails[discordID].channels[channel].members[displayMember] = {
discordName: member.displayName,
discordState: member.presence.status,
ircNick: displayMember,
id: member.id
};
const membersPlusDisplayMember = members ? `${members} ${displayMember}` : displayMember
const newLineLength = membersPlusDisplayMember.length;
const combinedLineLength = newLineLength + memberlistTemplateLength;
if (combinedLineLength < maxLineLength) {
members = membersPlusDisplayMember;
} else {
memberListLines.push(members);
members = displayMember;
}
}
});
memberListLines.push(members);
const joinMSG = `:${nickname} JOIN #${channel}\r\n`;
console.log(joinMSG);