From 6a3a2f5446d71d24f05a48613848ec0f3e718987 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thorben=20G=C3=BCnther?= Date: Wed, 28 Sep 2022 15:19:39 +0200 Subject: [PATCH] faceit: Refactor for additional future commands Use handleFaceitCommands to check if a API key is set. Handle response in this function as well, so that unified error handling will become easier. --- faceit.go | 29 +++++++++++++++++++++++++++++ main.go | 14 +++----------- 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/faceit.go b/faceit.go index 74b72fc..34d72b0 100644 --- a/faceit.go +++ b/faceit.go @@ -1,13 +1,17 @@ package main import ( + "database/sql" "encoding/json" "errors" "fmt" "io" "net/http" + "strconv" "strings" "time" + + "github.com/gempir/go-twitch-irc/v3" ) // TODO: check if faceitAPIKey is set @@ -28,6 +32,31 @@ type playerInfo struct { } `json:"games"` } +func (b *bot) handleFaceitCommands(parsed []string, msg *twitch.PrivateMessage) error { + if b.cfg.FaceitAPIKey == "" { + return errors.New("no Faceit API key set") + } + + switch parsed[0] { + case "!elo": + elo, err := b.getElo(msg.Channel, parsed) + if errors.Is(err, sql.ErrNoRows) { + // Only notify channel owner + if msg.User.Name == msg.Channel { + b.say(msg, "No Faceit account linked yet. Use '!set faceit ACCOUNTNAME") + } + return err + } else if err != nil { + return err + } + + b.say(msg, strconv.Itoa(elo)) + return nil + } + + return nil +} + func (b *bot) getElo(channel string, parsed []string) (int, error) { var url string diff --git a/main.go b/main.go index d89b6e2..790f8c5 100644 --- a/main.go +++ b/main.go @@ -7,7 +7,6 @@ import ( "log" "os" "os/signal" - "strconv" "strings" "syscall" @@ -71,16 +70,9 @@ func main() { } case "!elo": - elo, err := bot.getElo(message.Channel, parsed) - if errors.Is(err, sql.ErrNoRows) { - // Only notify channel owner - if message.User.Name == message.Channel { - bot.say(&message, "No Faceit account linked yet. Use '!set faceit ACCOUNTNAME") - } - } else if err != nil { - log.Printf("getElo (channel %s) failed: %v\n", message.Channel, err) - } else { - bot.say(&message, strconv.Itoa(elo)) + err := bot.handleFaceitCommands(parsed, &message) + if err != nil { + log.Printf("faceit command %v (channel %s) failed: %v\n", parsed, message.Channel, err) } default: -- 2.44.0