Skip to content

Commit

Permalink
Add Features - Mention and Channel Link conversion for Discord Relay (#4
Browse files Browse the repository at this point in the history
)

* Added functionality to convert mentions
  • Loading branch information
Shigbeard committed May 18, 2023
1 parent 2cf12a8 commit 9a5e486
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/relayDiscord.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
56 changes: 56 additions & 0 deletions src/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -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+>`)
Expand Down

0 comments on commit 9a5e486

Please sign in to comment.