From 4c929a8bcce219e3cc9b58fc99fbae8d8df70832 Mon Sep 17 00:00:00 2001 From: OleksandrParshyn <43094723+OleksandrParshyn@users.noreply.github.com> Date: Fri, 31 Oct 2025 15:35:13 +0100 Subject: [PATCH] Refactor: Replace time.Sleep with sync.WaitGroup for reliable TgBot shutdown Replaced the unreliable `time.Sleep(1 * time.Second)` in `service.StopBot()` with `sync.WaitGroup`. This ensures the Long Polling goroutine is explicitly waited for and reliably exits before the panel continues, preventing potential resource leaks and incomplete shutdowns during restarts. Changes: - Added `botWG sync.WaitGroup` variable. - Updated `service.StopBot()` to call `botWG.Wait()` instead of `time.Sleep()`. - Modified `Tgbot.OnReceive()` to correctly use `botWG.Add(1)` and `defer botWG.Done()` within the Long Polling goroutine. - Corrected the goroutine structure in `OnReceive()` to properly encapsulate all message handling logic. --- web/service/tgbot.go | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/web/service/tgbot.go b/web/service/tgbot.go index b45aeb1b..8a06a1f6 100644 --- a/web/service/tgbot.go +++ b/web/service/tgbot.go @@ -44,6 +44,8 @@ var ( botCancel context.CancelFunc // tgBotMutex protects concurrent access to botCancel variable tgBotMutex sync.Mutex + // botWG waits for the OnReceive Long Polling goroutine to finish. + botWG sync.WaitGroup botHandler *th.BotHandler adminIds []int64 @@ -343,7 +345,7 @@ func StopBot() { botCancel = nil // Giving the goroutine a small delay to exit cleanly. - time.Sleep(1 * time.Second) + botWG.Wait() logger.Info("Telegram bot successfully stopped.") } } @@ -377,9 +379,6 @@ func (t *Tgbot) OnReceive() { params := telego.GetUpdatesParams{ Timeout: 30, // Increased timeout to reduce API calls } - -// updates, _ := bot.UpdatesViaLongPolling(context.Background(), ¶ms) - // --- GRACEFUL SHUTDOWN FIX: Context creation --- tgBotMutex.Lock() @@ -400,7 +399,10 @@ func (t *Tgbot) OnReceive() { // Get updates channel using the context. updates, _ := bot.UpdatesViaLongPolling(ctx, ¶ms) - + botWG.Add(1) + go func() { + defer botWG.Done() + botHandler, _ = th.NewBotHandler(bot, updates) botHandler.HandleMessage(func(ctx *th.Context, message telego.Message) error { delete(userStates, message.Chat.ID)