Skip to content

Commit

Permalink
Handle flood errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Brawl345 committed Mar 8, 2022
1 parent 3260280 commit c917208
Showing 1 changed file with 29 additions and 13 deletions.
42 changes: 29 additions & 13 deletions handler/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,28 +108,18 @@ func (h Handler) check() error {

for _, subscriber := range subscribers {
if subscriber < 0 { // Group
_, err = h.Bot.Send(telebot.ChatID(subscriber), groupText, &telebot.SendOptions{
err = h.sendText(subscriber, groupText, &telebot.SendOptions{
DisableWebPagePreview: true,
ParseMode: telebot.ModeHTML,
ReplyMarkup: replyMarkup,
})
} else {
_, err = h.Bot.Send(telebot.ChatID(subscriber), privateText, defaultSendOptions)
err = h.sendText(subscriber, privateText, defaultSendOptions)
}

if err != nil {
if errors.Is(err, telebot.ErrChatNotFound) {
log.Printf("Chat %d not found, will be deleted", subscriber)
h.DB.Subscribers.Delete(subscriber)
} else if errors.Is(err, telebot.ErrGroupMigrated) {
log.Printf("Chat %d migrated to new group", subscriber)
h.DB.Subscribers.Delete(subscriber)
h.DB.Subscribers.Create(err.(*telebot.GroupError).MigratedTo)
} else {
log.Println(err)
}
log.Printf("Error for subscriber %d: %s", subscriber, err)
}

}

err = h.DB.System.SetLastEntry(result.BreakingNews.Id)
Expand All @@ -139,3 +129,29 @@ func (h Handler) check() error {

return nil
}

func (h Handler) sendText(subscriber int64, text string, sendOptions *telebot.SendOptions) error {
_, err := h.Bot.Send(telebot.ChatID(subscriber), text, sendOptions)

if err != nil {
if errors.Is(err, telebot.ErrChatNotFound) {
log.Printf("Chat %d not found, will be deleted", subscriber)
h.DB.Subscribers.Delete(subscriber)
} else if errors.Is(err, telebot.ErrGroupMigrated) {
migratedTo := err.(*telebot.GroupError).MigratedTo
log.Printf("Chat %d migrated to new group %d", subscriber, migratedTo)
h.DB.Subscribers.Delete(subscriber)
h.DB.Subscribers.Create(migratedTo)
return h.sendText(migratedTo, text, sendOptions)
} else if errors.As(err, &telebot.FloodError{}) {
retryAfter := err.(telebot.FloodError).RetryAfter
log.Printf("%d: Flood error, retrying after: %d seconds", subscriber, retryAfter)
time.Sleep(time.Duration(retryAfter) * time.Second)
h.sendText(subscriber, text, sendOptions)
} else {
return err
}
}

return nil
}

0 comments on commit c917208

Please sign in to comment.