From 9a5e486430ab432008d3777731cc4c782cbfe7c8 Mon Sep 17 00:00:00 2001 From: Shigbeard <4262327+Shigbeard@users.noreply.github.com> Date: Thu, 18 May 2023 22:40:06 +1000 Subject: [PATCH] Add Features - Mention and Channel Link conversion for Discord Relay (#4) * Added functionality to convert mentions --- src/relayDiscord.go | 3 +++ src/utils.go | 56 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/src/relayDiscord.go b/src/relayDiscord.go index 0d43733..825a268 100644 --- a/src/relayDiscord.go +++ b/src/relayDiscord.go @@ -44,6 +44,9 @@ func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { message = m.Content } + // Convert all <@ >, <# >, and similarly formatted items in Discord messages to something we can actually read. + message = convertDiscordFormattedItems(message, m.GuildID) + // Convert <:example:868167672758693909> to :example: message = filterDiscordEmotes(message) diff --git a/src/utils.go b/src/utils.go index 274194c..32ea2bd 100755 --- a/src/utils.go +++ b/src/utils.go @@ -81,6 +81,62 @@ func bToMb(b uint64) uint64 { return b / 1024 / 1024 } +// convertDiscordFormattedItems : Formats Discord Formatted Items to Text Only +func convertDiscordFormattedItems(str string, gid string) string { + // match all discord formatted items + reChannel := regexp.MustCompile(`<#(\d+)>`) + reMentionUser := regexp.MustCompile(`<@(?:\!)?(\d+)>`) + reMentionRole := regexp.MustCompile(`<@&(\d+)>`) + + str = reChannel.ReplaceAllStringFunc(str, func(s string) string { + // get the channels for this guild + id := reChannel.FindStringSubmatch(s)[1] + channels, err := DiscordSession.GuildChannels(gid) + if err != nil { + log.Errorln("[utils:convertDiscordFormattedItems]", "Error getting guild channels: ", err) + return s + } + for _, c := range channels { + if c.ID == id { + return "<%" + c.Name + ">" + } + } + + return s + }) + reMentionUser.FindAllStringSubmatchIndex(str, -1) + str = reMentionUser.ReplaceAllStringFunc(str, func(s string) string { + // get the user for this guild + id := reMentionUser.FindStringSubmatch(s)[1] + member, err := DiscordSession.GuildMember(gid, id) + if err != nil { + log.Errorln("[utils:convertDiscordFormattedItems]", "Error getting guild member: ", err) + return s + } + if member.Nick != "" { + return "<@" + member.Nick + ">" + } else { + return "<@" + member.User.Username + ">" + } + }) + str = reMentionRole.ReplaceAllStringFunc(str, func(s string) string { + // get the role for this guild + id := reMentionRole.FindStringSubmatch(s)[1] + roles, err := DiscordSession.GuildRoles(gid) + if err != nil { + log.Errorln("[utils:convertDiscordFormattedItems]", "Error getting guild roles: ", err) + return s + } + for _, r := range roles { + if r.ID == id { + return "<%@" + r.Name + ">" + } + } + return s + }) + return str +} + // filterDiscordEmotes : Formats Discord Emotes Correctly func filterDiscordEmotes(str string) string { re := regexp.MustCompile(`<:(\S+):\d+>`)