Skip to content

Commit

Permalink
Little bit of optimization. Now we firsrt check if the message is not…
Browse files Browse the repository at this point in the history
… from the bot, in a valid channel, and now also contains a valid prefix. This should prevent hitting the guild endpoints unnecessarily to do user role checks (#21)
  • Loading branch information
ezelkow1 authored Mar 23, 2018
1 parent 7655bef commit eef721c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 8 deletions.
23 changes: 15 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,9 +142,12 @@ func ready(s *discordgo.Session, event *discordgo.Ready) {
// Set the playing status.
s.UpdateStatus(0, "")
//SendEmbed(s, config.BroadcastChannel, "", "I iz here", "Keybot has arrived. You may now use me like the dumpster I am")
guildID = event.Guilds[0].ID
if config.KeyRole != "" {
guildID = event.Guilds[0].ID
refreshRoles(s)
}

initialized = true
refreshRoles(s)
}
}

Expand All @@ -153,22 +156,26 @@ func ready(s *discordgo.Session, event *discordgo.Ready) {
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {

// Ignore all messages created by the bot itself
// This isn't required in this specific example but it's a good practice.
if m.Author.ID == s.State.User.ID {
return
}

// Check if a user has the proper role, if a non-empty role is set
if !isUserRoleAllowed(s, m) {
return
}

// Only allow messages in either DM or broadcast channel
dmchan, _ := s.UserChannelCreate(m.Author.ID)
if (m.ChannelID != config.BroadcastChannel) && (m.ChannelID != dmchan.ID) {
return
}

// Skip any messages we dont care about
if checkPrefix(m.Content) == false {
return
}

// Check if a user has the proper role, if a non-empty role is set
if !isUserRoleAllowed(s, m) {
return
}

// Add a new key to the db
if strings.HasPrefix(m.Content, "!add ") == true {
AddGame(s, m)
Expand Down
16 changes: 16 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,19 @@ func isUserRoleAllowed(s *discordgo.Session, m *discordgo.MessageCreate) bool {

return false
}

// Check if a msg has a prefix we care about. This is for
// optimization so we can skip any messages we dont care about.
// If adding new message triggers they must be added here
func checkPrefix(msg string) bool {

if (msg == "!listkeys") ||
(strings.HasPrefix(msg, "!add ") == true) ||
(strings.HasPrefix(msg, "!take ") == true) ||
(strings.HasPrefix(msg, "!search ") == true) ||
(strings.HasPrefix(msg, "!help") == true) {
return true
}

return false
}

0 comments on commit eef721c

Please sign in to comment.