package weight_bot_state import ( "fmt" "log" "net/http" "strconv" "strings" "valera/internal/db" "valera/internal/states" tgbot "github.com/go-telegram-bot-api/telegram-bot-api" "golang.org/x/exp/slices" ) var names = []string{ "/weight", } type weightBotState struct { bot *tgbot.BotAPI dataBase *db.DB } func NewWeightBotState(bot *tgbot.BotAPI, dataBase *db.DB) states.BotState { return &weightBotState{ bot: bot, dataBase: dataBase, } } func (s *weightBotState) Do(text string, chatInfo *db.ChatInfo) error { if chatInfo.Status == string(db.UserStateWeight) { weight, err := getWeight(text) if err != nil { log.Println(err) return nil } if weight <= 0 { _, _ = s.bot.Send(tgbot.NewMessage(chatInfo.ChatID, "Все фигня, давай по новой")) return nil } if err := s.dataBase.AddWeight(chatInfo.ChatID, db.NewWeight(weight, chatInfo.Username)); err != nil { log.Println(err) return nil } _, _ = s.bot.Send(tgbot.NewMessage(chatInfo.ChatID, fmt.Sprintf("%vкг, записал.", weight))) return s.dataBase.SetStatusToChat(chatInfo.ChatID, db.UserStateNone) } if !slices.Contains(names, text) { return nil } s.sendWeightToChat(chatInfo.ChatID) return nil } func (s *weightBotState) 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 { w.Header().Add("Content-Type", "application/json") w.WriteHeader(http.StatusInternalServerError) _, _ = fmt.Fprintf(w, `{"result":"error"}`) return } for _, chatID := range chats { s.sendWeightToChat(chatID) } w.Header().Add("Content-Type", "application/json") w.WriteHeader(http.StatusOK) _, _ = fmt.Fprintf(w, `{"result":"ok"}`) } } func (s *weightBotState) sendWeightToChat(chatID int64) { msg := tgbot.NewMessage(chatID, "Давай взвешивайся, отпишись сколько кг ты весишь") if _, err := s.bot.Send(msg); err == nil { if err := s.dataBase.SetStatusToChat(chatID, db.UserStateWeight); err != nil { log.Println(err) } } } func getWeight(text string) (float64, error) { number := strings.ReplaceAll(text, ",", ".") return strconv.ParseFloat(number, 64) }