From c103e9e4fc182671dcc59818214eae18c011c2dc Mon Sep 17 00:00:00 2001 From: Victor Truong Date: Mon, 27 Jul 2020 03:29:44 -0700 Subject: [PATCH] Add basic validation --- pkg/jia/handlers.go | 56 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/pkg/jia/handlers.go b/pkg/jia/handlers.go index e786adb..3e61a87 100644 --- a/pkg/jia/handlers.go +++ b/pkg/jia/handlers.go @@ -1,6 +1,11 @@ package jia import ( + "fmt" + "log" + "regexp" + "strconv" + "github.com/slack-go/slack" "github.com/slack-go/slack/slackevents" ) @@ -13,5 +18,56 @@ func HandleInnerEvent(slackClient *slack.Client, innerEvent *slackevents.EventsA } } +// TODO: Persist to Redis +var ( + lastValidNumber = 0 + lastSender = "" +) + func onMessage(slackClient *slack.Client, event *slackevents.MessageEvent) { + // Ignore messages that aren't in the target channel, or are non-user messages + if event.Channel != jiaConfig.ChannelID || event.User == "USLACKBOT" || event.User == "" { + return + } + + // Attempt to extract a positive number from the beginning of a string + countPattern := regexp.MustCompile(`^\d+`) + matchedNumber, err := strconv.Atoi(countPattern.FindString(event.Text)) + log.Println(matchedNumber) + + // Ignore messages that don't have numbers. + if err != nil { + log.Println("Failed to retrieve number, skipping…") + return + } + + // Reject if sender also sent the previous number. + if event.User == lastSender { + slackClient.AddReaction("bangbang", slack.ItemRef{ + Channel: event.Channel, + Timestamp: event.TimeStamp, + }) + slackClient.PostEphemeral(event.Channel, event.User, slack.MsgOptionText( + "You counted consecutively! That’s not allowed.", false)) + return + } + + // Ignore numbers that aren't in order. + if matchedNumber != lastValidNumber+1 { + slackClient.AddReaction("bangbang", slack.ItemRef{ + Channel: event.Channel, + Timestamp: event.TimeStamp, + }) + slackClient.PostEphemeral(event.Channel, event.User, slack.MsgOptionText( + fmt.Sprintf("You counted incorrectly! The next valid number is supposed to be *%d*.", lastValidNumber+1), false)) + return + } + + // Finally! + lastValidNumber = matchedNumber + lastSender = event.User + slackClient.AddReaction("+1", slack.ItemRef{ + Channel: event.Channel, + Timestamp: event.TimeStamp, + }) }