valera/internal/states/stat_bot_state/stat_bot_state.go

75 lines
1.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package stat_bot_state
import (
"fmt"
"net/http"
"valera/internal/db"
"valera/internal/states"
tgbot "github.com/go-telegram-bot-api/telegram-bot-api"
"golang.org/x/exp/slices"
)
var names = []string{
"/stat",
}
type statBotState struct {
bot *tgbot.BotAPI
dataBase *db.DB
}
func NewStatBotState(bot *tgbot.BotAPI, dataBase *db.DB) states.BotState {
return &statBotState{
bot: bot,
dataBase: dataBase,
}
}
func (s *statBotState) Do(text string, chatInfo *db.ChatInfo, username string) error {
if !slices.Contains(names, text) {
return nil
}
s.sendStatToChat(chatInfo.ChatID, "")
return nil
}
func (s *statBotState) GetHandler() (string, func(http.ResponseWriter, *http.Request)) {
return names[0], func(w http.ResponseWriter, r *http.Request) {
chats, err := s.dataBase.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 := s.sendStatToChat(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"}`)
}
}
func (s *statBotState) sendStatToChat(chatID int64, prefix string) error {
stat, err := s.dataBase.GetStat(chatID)
if err != nil {
return err
}
msgText := prefix + "Результаты за сегодня:\n"
for k, v := range stat {
msgText += fmt.Sprintf("- %s: %d\n", k, v)
}
_, _ = s.bot.Send(tgbot.NewMessage(chatID, msgText))
return nil
}