From 78aaa9b80a27c59fc3cae3550558a3ba29459306 Mon Sep 17 00:00:00 2001 From: Fedorov Vladimir Date: Sat, 11 Mar 2023 18:30:12 +0700 Subject: [PATCH] up --- commands/command.go | 3 ++- config/config.go | 14 +++++----- db/db.go | 65 ++++++++++++++++++++++++++++++++++++--------- main.go | 36 +++++++++++++++++++------ 4 files changed, 91 insertions(+), 27 deletions(-) diff --git a/commands/command.go b/commands/command.go index 55678a3..2c3eafe 100644 --- a/commands/command.go +++ b/commands/command.go @@ -6,5 +6,6 @@ const ( Start = Command("/start") Help = Command("/help") Ping = Command("/ping") - Go = Command("/go") + Go = Command("/go") + Stat = Command("/stat") ) diff --git a/config/config.go b/config/config.go index baa1991..1967315 100644 --- a/config/config.go +++ b/config/config.go @@ -1,15 +1,17 @@ package config type Config struct { - MongoURL string - DBName string - ChatsCollectionName string + MongoURL string + DBName string + ChatsCollectionName string + WorkoutsCollectionName string } func NewConfig() *Config { return &Config{ - MongoURL: "mongodb://mongo:o6bbyog3DHG0GYdu@158.160.11.219:27027", - DBName: "valera", - ChatsCollectionName: "users", + MongoURL: "mongodb://mongo:o6bbyog3DHG0GYdu@158.160.11.219:27027", + DBName: "valera", + ChatsCollectionName: "users", + WorkoutsCollectionName: "workouts", } } diff --git a/db/db.go b/db/db.go index 5daaef1..075c2b0 100644 --- a/db/db.go +++ b/db/db.go @@ -5,6 +5,7 @@ import ( "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" + "log" "time" "valera/config" ) @@ -21,9 +22,8 @@ type chatDTO struct { } type ChatInfoDTO struct { - ChatID int64 `bson:"chat_id"` - Status string `bson:"status"` - Workouts []Workout `bson:"workouts"` + ChatID int64 `bson:"chat_id"` + Status string `bson:"status"` } func (c *ChatInfoDTO) GetStatus() UserState { @@ -34,17 +34,22 @@ func (c *ChatInfoDTO) GetStatus() UserState { } type Workout struct { - Name string `bson:"name"` - Count int `bson:"count"` + ChatID int64 `bson:"chat_id"` + Name string `bson:"name"` + Count int `bson:"count"` + CreatedAt time.Time `bson:"created_at"` + Username string `bson:"username"` } func NewWorkout( name string, count int, + username string, ) *Workout { return &Workout{ - Name: name, - Count: count, + Name: name, + Count: count, + Username: username, } } @@ -75,10 +80,13 @@ func AddChat(chatID int64) error { return result.Err() } -func AddWorkoutInUser(chatID int64, workout *Workout) error { +func AddWorkout(chatID int64, workout *Workout) error { if err := AddChat(chatID); err != nil { return err } + workout.ChatID = chatID + loc, _ := time.LoadLocation("Asia/Novosibirsk") + workout.CreatedAt = time.Now().In(loc) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() @@ -88,16 +96,18 @@ func AddWorkoutInUser(chatID int64, workout *Workout) error { return err } - collection := client.Database(cfg.DBName).Collection(cfg.ChatsCollectionName) - _, err = collection.UpdateOne( + collection := client.Database(cfg.DBName).Collection(cfg.WorkoutsCollectionName) + _, err = collection.InsertOne( ctx, - bson.M{"chat_id": chatID}, - bson.M{"$push": bson.M{"workouts": workout}}, + workout, ) return err } func GetUserInfo(chatID int64) (*ChatInfoDTO, error) { + if err := AddChat(chatID); err != nil { + return nil, err + } ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() @@ -131,3 +141,34 @@ func SetStatusInUser(chatID int64, status UserState) error { ) return err } + +func GetStat(chatID int64) (map[string]int, error) { + if err := AddChat(chatID); err != nil { + return nil, err + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + + client, err := mongo.Connect(ctx, options.Client().ApplyURI(cfg.MongoURL)) + if err != nil { + return nil, err + } + + collection := client.Database(cfg.DBName).Collection(cfg.WorkoutsCollectionName) + cursor, err := collection.Find(ctx, bson.M{"chat_id": chatID}) + if err != nil { + return nil, err + } + res := map[string]int{} + for cursor.Next(context.Background()) { + var result Workout + if err := cursor.Decode(&result); err != nil { + log.Fatal(err) + } + res[result.Name] += result.Count + } + if err := cursor.Err(); err != nil { + log.Fatal(err) + } + return res, err +} diff --git a/main.go b/main.go index dc44584..1d01b69 100644 --- a/main.go +++ b/main.go @@ -15,10 +15,9 @@ import ( ) const ( - version = "v1.0.0" + version = "v1.0.1" ) - type Opts struct { Token string `short:"t" long:"token" description:"Telegram api token"` Name string `short:"n" long:"name" description:"Telegram bot name" default:"@body_weight_loss_bot"` @@ -81,8 +80,7 @@ func run() { text := update.Message.Text chatID := update.Message.Chat.ID - // username := update.Message.From.UserName - + username := update.Message.From.UserName userInfoDTO, err := db.GetUserInfo(chatID) if err != nil { @@ -92,15 +90,19 @@ func run() { if userInfoDTO.GetStatus() == db.UserStateGo { count, err := strconv.Atoi(text) if err != nil { + log.Println(err) continue } - if err := db.AddWorkoutInUser(chatID, db.NewWorkout("Отжимания", count)); err != nil { + if err := db.AddWorkout(chatID, db.NewWorkout("Отжимания", count, username)); err != nil { + log.Println(err) continue } msg := tgbot.NewMessage(chatID, fmt.Sprintf("Отлично, %s, записал.", text)) msg.ReplyMarkup = tgbot.NewHideKeyboard(false) _, _ = bot.Send(msg) - db.SetStatusInUser(chatID, db.UserStateNone) + if err := db.SetStatusInUser(chatID, db.UserStateNone); err != nil { + log.Println(err) + } continue } @@ -108,8 +110,11 @@ func run() { switch command { case commands.Start: _, _ = bot.Send(tgbot.NewMessage(chatID, fmt.Sprintf("Здорова, я Валера (%s), твой тренер (%d).", version, chatID))) + if err := db.SetStatusInUser(chatID, db.UserStateNone); err != nil { + log.Println(err) + } case commands.Help: - _, _ = bot.Send(tgbot.NewMessage(chatID, "Вот что я умею:\n\n1) Предлагать размяться")) + _, _ = bot.Send(tgbot.NewMessage(chatID, "Вот что я умею:\n\n1) Предлагать размяться\n2) Показывать статистику")) case commands.Ping: _, _ = bot.Send(tgbot.NewMessage(chatID, "pong")) case commands.Go: @@ -119,11 +124,26 @@ func run() { tgbot.NewKeyboardButton("1"), tgbot.NewKeyboardButton("2"), tgbot.NewKeyboardButton("3"), + tgbot.NewKeyboardButton("5"), + tgbot.NewKeyboardButton("8"), ), ) if _, err = bot.Send(msg); err == nil { - db.SetStatusInUser(chatID, db.UserStateGo) + if err := db.SetStatusInUser(chatID, db.UserStateGo); err != nil { + log.Println(err) + } } + case commands.Stat: + stat, err := db.GetStat(chatID) + if err != nil { + log.Println(err) + continue + } + msgText := "Результаты за сегодня:\n" + for k, v := range stat { + msgText += fmt.Sprintf("- %s: %d\n", k, v) + } + _, _ = bot.Send(tgbot.NewMessage(chatID, msgText)) } } }