Skip to content

Commit

Permalink
🐛 Ignore Old AppMention Events (#18)
Browse files Browse the repository at this point in the history
This commit adds a check to the AppMention event handler, to check how
recent the message was created. If the message is greater than 2 seconds
old, it will be ignored. This will prevent the bot responding to edited,
older messages.

Previously, the bot would respond to any incoming AppMention event,
regardless of how old the message was.

Fixes #16.
  • Loading branch information
toddtee authored Sep 25, 2023
1 parent 495f566 commit 441975b
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions internal/events/events_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package events

import (
"fmt"
"strconv"
"strings"
"time"

"github.com/slack-go/slack"
"github.com/slack-go/slack/slackevents"
Expand Down Expand Up @@ -55,6 +57,11 @@ func teamJoin(ev *slackevents.TeamJoinEvent, api *slack.Client) {
}

func appMention(ev *slackevents.AppMentionEvent, api *slack.Client) {
// If the message was created in the past, then ignore it.
if pastAppMention(ev) {
return
}

// If the message contains "ping", then respond with a randomly selected greeting message.
if strings.Contains(ev.Text, "ping") {
err := ping.Handler(api, ev)
Expand All @@ -68,5 +75,23 @@ func appMention(ev *slackevents.AppMentionEvent, api *slack.Client) {
if strings.Contains(ev.Text, "coffee") {
coffee.Handler(api, ev)
}
}

// pastAppMention checks how recently the message was created.
// The message is considered in the past if it was created 2 seconds ago or more.
func pastAppMention(ev *slackevents.AppMentionEvent) bool {

// Split the timestamp into seconds and nanoseconds.
// Only the seconds are needed.
tp := strings.Split(ev.TimeStamp, ".")

ct := time.Now().Unix()
et, err := strconv.ParseInt(tp[0], 10, 64)
if err != nil {
fmt.Printf("Error parsing event timestamp: %s", err)
}

td := ct - et

return td >= 2
}

0 comments on commit 441975b

Please sign in to comment.