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.
This commit is contained in:
OleksandrParshyn 2025-10-31 15:35:13 +01:00 committed by GitHub
parent bb78b9495a
commit 4c929a8bcc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -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(), &params)
// --- GRACEFUL SHUTDOWN FIX: Context creation ---
tgBotMutex.Lock()
@ -400,6 +399,9 @@ func (t *Tgbot) OnReceive() {
// Get updates channel using the context.
updates, _ := bot.UpdatesViaLongPolling(ctx, &params)
botWG.Add(1)
go func() {
defer botWG.Done()
botHandler, _ = th.NewBotHandler(bot, updates)
botHandler.HandleMessage(func(ctx *th.Context, message telego.Message) error {