Skip to content

Commit

Permalink
enhancement(bot): replace mention when using simple messages | closes #…
Browse files Browse the repository at this point in the history
  • Loading branch information
rumblefrog committed Sep 5, 2019
1 parent 61687e7 commit bcffbc8
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
3 changes: 2 additions & 1 deletion server/bot/pipeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
Expand Down
56 changes: 56 additions & 0 deletions server/bot/util.go
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down Expand Up @@ -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
}

0 comments on commit bcffbc8

Please sign in to comment.