add stat
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Владимир Фёдоров 2023-03-12 00:40:37 +07:00
parent ccd55a6702
commit daa52ecbde
1 changed files with 39 additions and 9 deletions

48
main.go
View File

@ -16,7 +16,7 @@ import (
) )
const ( const (
version = "v1.1.0" version = "v1.2.0"
) )
type Opts struct { type Opts struct {
@ -88,6 +88,29 @@ func run() {
_, _ = fmt.Fprintf(w, `{"result":"ok"}`) _, _ = fmt.Fprintf(w, `{"result":"ok"}`)
}) })
http.HandleFunc("/stat", func(w http.ResponseWriter, r *http.Request) {
chats, err := db.GetAllChats()
if err != nil {
fmt.Println(err)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
_, _ = fmt.Fprintf(w, `{"result":"error"}`)
return
}
for _, chatID := range chats {
if err := sendStatToChat(bot, chatID, "Напоминаю:\n- Cегодня больше не жрем!\n\n"); err != nil {
fmt.Println(err)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
_, _ = fmt.Fprintf(w, `{"result":"error"}`)
return
}
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprintf(w, `{"result":"ok"}`)
})
port := ":10002" port := ":10002"
log.Println("Server is start up! port", port) log.Println("Server is start up! port", port)
log.Fatal(http.ListenAndServe(port, nil)) log.Fatal(http.ListenAndServe(port, nil))
@ -147,16 +170,10 @@ func run() {
case commands.Go: case commands.Go:
sendGoToChat(bot, chatID) sendGoToChat(bot, chatID)
case commands.Stat: case commands.Stat:
stat, err := db.GetStat(chatID) if err := sendStatToChat(bot, chatID, ""); err != nil {
if err != nil { fmt.Println(err)
log.Println(err)
continue continue
} }
msgText := "Результаты за сегодня:\n"
for k, v := range stat {
msgText += fmt.Sprintf("- %s: %d\n", k, v)
}
_, _ = bot.Send(tgbot.NewMessage(chatID, msgText))
} }
} }
} }
@ -178,3 +195,16 @@ func sendGoToChat(bot *tgbot.BotAPI, chatID int64) {
} }
} }
} }
func sendStatToChat(bot *tgbot.BotAPI, chatID int64, prefix string) error {
stat, err := db.GetStat(chatID)
if err != nil {
return err
}
msgText := prefix + "Результаты за сегодня:\n"
for k, v := range stat {
msgText += fmt.Sprintf("- %s: %d\n", k, v)
}
_, _ = bot.Send(tgbot.NewMessage(chatID, msgText))
return nil
}