valera/internal/states/stat_bot_state/stat_bot_state.go

105 lines
2.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"
"time"
"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",
"/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, username string) error {
if !slices.Contains(names, text) {
return nil
}
if text == "/stat" {
s.sendStatToChatAfter(chatInfo.ChatID, "Результаты за сегодня:\n", s.getStartDay())
}
if text == "/stat_week" {
s.sendStatToChatAfter(chatInfo.ChatID, "Результаты за неделю:\n", s.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 := s.getStartDay()
if err := s.sendStatToChatAfter(chatID, "Напоминаю:\n- Cегодня больше не жрем!\n\nРезультаты за сегодня:\n", s.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", s.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: %d\n", k, v)
}
_, _ = s.bot.Send(tgbot.NewMessage(chatID, msgText))
return nil
}
func (s *statBotState) getStartDay() time.Time {
loc, _ := time.LoadLocation("Asia/Novosibirsk")
t := time.Now().In(loc)
t = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, loc)
return t
}
func (s *statBotState) getStartWeek() time.Time {
t := s.getStartDay()
t = t.Add(-6 * 24 * time.Hour)
return t
}