From b874d74c0286c9a811e59ba71afa3dc07e7f444f Mon Sep 17 00:00:00 2001 From: alufers Date: Thu, 5 Oct 2023 17:59:43 +0200 Subject: [PATCH] Add @har suffix to messages to generate a har file --- tghelpers/command.go | 1 + tghelpers/command_dispatcher.go | 32 +++++++++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/tghelpers/command.go b/tghelpers/command.go index cadaa47..7b4bc7a 100644 --- a/tghelpers/command.go +++ b/tghelpers/command.go @@ -63,6 +63,7 @@ func CommandMatches(cmd Command, userInput string) bool { usersCmd := strings.Split(userInput, " ")[0] // strip bot suffix on groups usersCmd = strings.TrimSuffix(usersCmd, "@"+viper.GetString("telegram.username")) + usersCmd = strings.TrimSuffix(usersCmd, "@har") for _, alias := range cmd.Aliases() { if alias == usersCmd { return true diff --git a/tghelpers/command_dispatcher.go b/tghelpers/command_dispatcher.go index dec9789..c13212b 100644 --- a/tghelpers/command_dispatcher.go +++ b/tghelpers/command_dispatcher.go @@ -7,6 +7,7 @@ import ( "log" "strings" + "github.com/alufers/paczkobot/httphelpers" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" ) @@ -66,9 +67,14 @@ func (d *CommandDispatcher) RunUpdateLoop() error { ctx := context.WithValue(ctx, UpdateContextKey, u) ctx = context.WithValue(ctx, ArgsContextKey, args) - for _, hook := range d.UpdateHooks { - if hook.OnUpdate(ctx) { - return // hook has handled the message stop processing + + // TODO: move this to a nice hook + if strings.HasSuffix(args.CommandName, "@har") { + ctx = httphelpers.WithHarLoggerStorage(ctx) + for _, hook := range d.UpdateHooks { + if hook.OnUpdate(ctx) { + return // hook has handled the message stop processing + } } } @@ -93,6 +99,26 @@ func (d *CommandDispatcher) RunUpdateLoop() error { break } } + + storage := httphelpers.GetHarLoggerStorage(ctx) + + if storage != nil { + + jsonData, err := storage.GetJSONData() + if err != nil { + log.Printf("Error while getting HAR data: %v", err) + } else { + sendDoc := tgbotapi.NewDocument(args.ChatID, tgbotapi.FileReader{ + Name: "har.json", + Reader: strings.NewReader(string(jsonData)), + }) + sendDoc.Caption = "HAR data" + _, err := d.BotAPI.Send(sendDoc) + if err != nil { + log.Printf("Error while sending HAR data: %v", err) + } + } + } if err != nil { log.Printf("Error while processing command %v: %v", cmdText, err) msg := tgbotapi.NewMessage(args.ChatID, "🚫 Error: "+html.EscapeString(err.Error())+"")