Answer the question
In order to leave comments, you need to log in
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 // установливаю соединение и не закрываю через другую функцию
}
func main() {
telegram.InitBot() // создаю соединение с апи бота
storage.InitClient() // создаю соединение с mongodb и добавляю клиент в структуру
telegram.GetBot().Bot.Handle("/start", telegram.GetBot().HandleStart)
}
func (b *bot) HandleStart(message *tb.Message) {
b.Bot.Send(message.Sender, "Hello")
storage.GetClient().CreateUserDocument(message.Sender.ID) // создает документ в бд, если еще не существует с таким id пользователя
}
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)
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question