-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathDiscordToIrcConverter.cs
64 lines (54 loc) · 2.54 KB
/
DiscordToIrcConverter.cs
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
using Discord.WebSocket;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace IrcDiscordRelay
{
internal static class DiscordToIrcConverter
{
private static readonly Regex BoldRegex = new(@"\*\*(.*?)\*\*");
private static readonly Regex ItalicRegex = new(@"\*(.*?)\*");
private static readonly Regex UnderlineRegex = new(@"__(.*?)__");
private static readonly Regex StrikethroughRegex = new(@"~~(.*?)~~");
private static readonly Regex SlashCommandRegex = new(@"<\/(\w+):?\d*>");
private static readonly Regex EmojiRegex = new(@"<([A-Za-z0-9-_]?:[A-Za-z0-9-_]+:)[0-9]+>");
public static string Convert(SocketMessage message)
{
string messageContent = message.Content;
// Replace Discord markdown with IRC formatting codes
messageContent = BoldRegex.Replace(messageContent, "\x02$1\x02");
messageContent = ItalicRegex.Replace(messageContent, "\x1D$1\x1D");
messageContent = UnderlineRegex.Replace(messageContent, "\x1F$1\x1F");
messageContent = StrikethroughRegex.Replace(messageContent, "\x1E$1\x1E");
// Parse <:emoji:0123456789> to :emoji:
messageContent = EmojiRegex.Replace(messageContent, "$1");
// Parse mentions
foreach (SocketUser userMention in message.MentionedUsers)
{
messageContent = messageContent.Replace($"<@{userMention.Id}>", $"@{userMention.Username}");
}
foreach (SocketRole roleMention in message.MentionedRoles)
{
messageContent = messageContent.Replace($"<@&{roleMention.Id}>", $"@{roleMention.Name}");
}
foreach (SocketGuildChannel channelMention in message.MentionedChannels)
{
messageContent = messageContent.Replace($"<#{channelMention.Id}>", $"#{channelMention.Name}");
}
// Support attachments
if (message.Attachments.Any())
{
IEnumerable<string> attachments = message.Attachments.Select(x => x.Url);
messageContent += "\n" + string.Join("\n", attachments);
}
// Parse slash commands
messageContent = SlashCommandRegex.Replace(messageContent, m =>
{
string tag = m.Value;
string commandName = tag[2..^1].Split(':')[0];
return $"/{commandName}";
});
return messageContent;
}
}
}