64 lines
1.4 KiB
Go
64 lines
1.4 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"git.user-penguin.space/vladimir/all-tg-bot/config"
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
"time"
|
|
)
|
|
|
|
type chatDTO struct {
|
|
ChatID int64 `bson:"chat_id"`
|
|
}
|
|
|
|
var cfg *config.Config
|
|
|
|
func init() {
|
|
cfg = config.NewConfig()
|
|
}
|
|
|
|
func AddChat(chatID int64) error {
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
|
defer cancel()
|
|
|
|
client, err := mongo.Connect(ctx, options.Client().ApplyURI(cfg.MongoURL))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
collection := client.Database(cfg.DBName).Collection(cfg.ChatsCollectionName)
|
|
|
|
result := collection.FindOne(ctx, bson.M{"chat_id": chatID})
|
|
if result.Err() == mongo.ErrNoDocuments {
|
|
if _, err := collection.InsertOne(ctx, &chatDTO{ChatID: chatID}); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
return result.Err()
|
|
}
|
|
|
|
func AddUserInChat(chatID int64, username string) error {
|
|
if err := AddChat(chatID); err != nil {
|
|
return 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 err
|
|
}
|
|
|
|
collection := client.Database(cfg.DBName).Collection(cfg.ChatsCollectionName)
|
|
_, err = collection.UpdateOne(
|
|
ctx,
|
|
bson.M{"chat_id": chatID},
|
|
bson.M{"addToSet": bson.M{"users": username}},
|
|
)
|
|
return err
|
|
}
|