Skip to content

Commit

Permalink
Add @har suffix to messages to generate a har file
Browse files Browse the repository at this point in the history
  • Loading branch information
alufers committed Oct 5, 2023
1 parent 66f7faa commit b874d74
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
1 change: 1 addition & 0 deletions tghelpers/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
32 changes: 29 additions & 3 deletions tghelpers/command_dispatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"log"
"strings"

"github.com/alufers/paczkobot/httphelpers"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)

Expand Down Expand Up @@ -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
}
}
}

Expand All @@ -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: <b>"+html.EscapeString(err.Error())+"</b>")
Expand Down

0 comments on commit b874d74

Please sign in to comment.