package stat_bot_state import ( "fmt" "net/http" "time" "valera/internal/db" "valera/internal/states" "valera/internal/modules/times" tgbot "github.com/go-telegram-bot-api/telegram-bot-api" "golang.org/x/exp/slices" ) var names = []string{ "/stat", "/stat_week", } 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) error { if !slices.Contains(names, text) { return nil } if text == "/stat" { s.sendStatToChatAfter(chatInfo.ChatID, "Результаты за сегодня:\n", times.GetStartDay()) } if text == "/stat_week" { s.sendStatToChatAfter(chatInfo.ChatID, "Результаты за неделю:\n", times.GetStartWeek()) } 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 { t := times.GetStartDay() if err := s.sendStatToChatAfter(chatID, "Напоминаю:\n- Cегодня больше не жрем!\n\nРезультаты за сегодня:\n", times.GetStartDay()); err != nil { w.Header().Add("Content-Type", "application/json") w.WriteHeader(http.StatusInternalServerError) _, _ = fmt.Fprintf(w, `{"result":"error"}`) return } if t.Weekday() == time.Sunday { if err := s.sendStatToChatAfter(chatID, "Результаты за неделю:\n", times.GetStartWeek()); err != nil { 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) sendStatToChatAfter(chatID int64, prefix string, t time.Time) error { msgText := prefix stat, err := s.dataBase.GetStatAfter(chatID, t) if err != nil { return err } for k, v := range stat { msgText += fmt.Sprintf("- %s: %v\n", k, v) } _, _ = s.bot.Send(tgbot.NewMessage(chatID, msgText)) return nil }