G
G
gelerum2021-10-17 10:34:47
go
gelerum, 2021-10-17 10:34:47

Where and how to add asynchrony to the telegram bot?

Hello, I use the telebot library along with MongoDB

Through GetClient() and GetBot() I communicate with structures of the same name

type client struct {
  client *mongo.Client  // установливаю соединение и не закрываю через другую функцию
}


The connection to the database is created at the very beginning and is not closed.
func main() {
    telegram.InitBot() // создаю соединение с апи бота 
    storage.InitClient() // создаю соединение с mongodb и добавляю клиент в структуру
    telegram.GetBot().Bot.Handle("/start", telegram.GetBot().HandleStart)
}


The function below is executed as reported by user /start
func (b *bot) HandleStart(message *tb.Message) {
  b.Bot.Send(message.Sender, "Hello")
  storage.GetClient().CreateUserDocument(message.Sender.ID) // создает документ в бд, если еще не существует с таким id пользователя
}


This is how I create a document with an initial structure and a user id, if no such id has already been created:
func (c client) CreateUserDocument(chatID int) {
  coll := c.client.Database("db").Collection("users")
  count, _ := coll.CountDocuments(context.TODO(), bson.D{{"chatID", chatID}})
  if count != 1 {
    document := bson.D{{"chatID", chatID}, {"expenses", bson.A{}}, {"income", bson.A{}}}
    coll.InsertOne(context.TODO(), document)
  }
}


How can I optimize this code and where can I add async? This is not the entire code of the project, other requests to the database are made for other bot commands.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2021-10-17
@gelerum

You can make the bot work through webhooks, then each request will be initially processed in a separate gorutin.
Plus, with this approach, you can horizontally scale the load, i.e. run the bot on several servers and send requests to them through some kind of balancer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question