Advertisement
x95u1

Notify Action if the context is not canceled within grace period.

May 24th, 2025 (edited)
1,038
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.07 KB | Source Code | 0 0
  1. func yourHandler() {
  2.     // the "recording audio" notification will be sent if we're not able to get the voice generated within 2 seconds.
  3.     cancelNotify := b.sendNotifyAction(ctx, chat, notifyGraceTime)
  4.     voice, cl, genErr := gen.ForUser(ctx, user, text)
  5.     cancelNotify()
  6.  
  7. // ...
  8. }
  9.  
  10. // sendNotifyAction sends the "recording" notification if the gracePeriod expires
  11. // before cancelFn function is called.
  12. func (b *Bot) sendNotifyAction(ctx context.Context, r tb.Recipient, gracePeriod time.Duration) (cancelFn func()) {
  13.     timeoutCtx, cancel := context.WithTimeout(ctx, 5*time.Minute) // this should never happen, just in case
  14.     go func() {
  15.         region := trace.StartRegion(timeoutCtx, "sendNotifyAction")
  16.         defer region.End()
  17.  
  18.         select {
  19.         case <-time.After(gracePeriod):
  20.             trace.Logf(ctx, "notify", "sending notify action")
  21.             if err := b.bot.Notify(r, tb.RecordingAudio); err != nil {
  22.                 dlog.Printf("%s: notification error: %s", caller(0), err)
  23.             }
  24.         case <-timeoutCtx.Done():
  25.             trace.Logf(timeoutCtx, "notify", timeoutCtx.Err().Error())
  26.             return
  27.         }
  28.     }()
  29.     return cancel
  30. }
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement