From bcffbc88d43bd75f82801c62818980a95c41c81a Mon Sep 17 00:00:00 2001 From: rumblefrog Date: Thu, 5 Sep 2019 16:31:45 -0400 Subject: [PATCH] enhancement(bot): replace mention when using simple messages | closes #25 --- server/bot/pipeline.go | 3 ++- server/bot/util.go | 56 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/server/bot/pipeline.go b/server/bot/pipeline.go index b38e9230..3f67891f 100644 --- a/server/bot/pipeline.go +++ b/server/bot/pipeline.go @@ -24,7 +24,8 @@ func Listen() { if !config.Config.Bot.SimpleMessage { RelayBot.ChannelMessageSendEmbed(channel.ID, message.Embed()) } else { - RelayBot.ChannelMessageSend(channel.ID, message.Plain()) + content := TransformMentions(RelayBot, channel.ID, message.Plain()) + RelayBot.ChannelMessageSend(channel.ID, content) } } } diff --git a/server/bot/util.go b/server/bot/util.go index 4937e83e..34e8704c 100644 --- a/server/bot/util.go +++ b/server/bot/util.go @@ -1,14 +1,19 @@ package bot import ( + "fmt" "regexp" + "strings" "github.com/Necroforger/dgrouter/exrouter" "github.com/bwmarrin/discordgo" ) var ( + ChannelRegex = regexp.MustCompile("(?:<#)?([0-9]+)>?") ChannelRegexExplicit = regexp.MustCompile("^(?:<#)?([0-9]+)>?$") + UserRegex = regexp.MustCompile("(?:<@!?)?([0-9]+)>?") + RoleRegex = regexp.MustCompile("(?:<@&)?([0-9]+)>?") ) func GuildMemberPermissions(member *discordgo.Member, guild *discordgo.Guild) (apermissions int) { @@ -63,3 +68,54 @@ func ParseChannel(arg string) (string, bool) { return "", false } + +func TransformMentions(session *discordgo.Session, cid string, body string) string { + if ChannelRegex.Match([]byte(body)) { + matches := ChannelRegex.FindAllStringSubmatch(body, -1) + + n := len(matches) + + for i := 0; i < n; i++ { + channel, err := session.Channel(matches[i][1]) + + if err == nil { + body = strings.Replace(body, matches[i][0], fmt.Sprintf("#%s", channel.Name), -1) + } + } + } + + // Role match has to be before user, otherwise UserRegex will partial match role + if RoleRegex.Match([]byte(body)) { + channel, err := session.Channel(cid) + + if err == nil { + matches := RoleRegex.FindAllStringSubmatch(body, -1) + + n := len(matches) + + for i := 0; i < n; i++ { + role, err := session.State.Role(channel.GuildID, matches[i][1]) + + if err == nil { + body = strings.Replace(body, matches[i][0], fmt.Sprintf("@%s", role.Name), -1) + } + } + } + } + + if UserRegex.Match([]byte(body)) { + matches := UserRegex.FindAllStringSubmatch(body, -1) + + n := len(matches) + + for i := 0; i < n; i++ { + user, err := session.User(matches[i][1]) + + if err == nil { + body = strings.Replace(body, matches[i][0], fmt.Sprintf("@%s", user.Username), -1) + } + } + } + + return body +}