// Package bot is the Telegram front end: it turns updates into requests // and jobs, keeps the status message of every delivery current and sends // finished files. package bot import ( "context" "fmt" "log/slog" "runtime/debug" "sync" "time" "github.com/mymmrac/telego" "github.com/noderunners/dlbot/internal/billing" "github.com/noderunners/dlbot/internal/cache" "github.com/noderunners/dlbot/internal/config" "github.com/noderunners/dlbot/internal/db" "github.com/noderunners/dlbot/internal/groups" "github.com/noderunners/dlbot/internal/i18n" "github.com/noderunners/dlbot/internal/metrics" "github.com/noderunners/dlbot/internal/sched" "github.com/noderunners/dlbot/internal/service" "github.com/noderunners/dlbot/internal/storage" "github.com/noderunners/dlbot/internal/tg" "github.com/noderunners/dlbot/internal/widget" ) // Deps are the collaborators of the bot. type Deps struct { API tg.API Config config.Config Store *db.Store Sched *sched.Scheduler Service *service.Service Billing *billing.Billing // Cashu redeems ecash tokens. Nil turns that part of /redeem off. Cashu billing.Cashu Cache *cache.Cache Storage storage.Storage I18n *i18n.Bundle Log *slog.Logger // WorkerSlots is the number of download slots serving the queue. It // only feeds the wait estimate. WorkerSlots func() int // Admins verifies group admins. A nil value gets a default checker. Admins *groups.Admins // ReloadI18n reloads the catalogs from disk. Nil when they are built in. ReloadI18n func() error // Metrics records what happens. Nil records nothing. Metrics *metrics.Metrics } // Bot handles Telegram updates and job events. type Bot struct { api tg.API cfg config.Config store *db.Store sched *sched.Scheduler svc *service.Service bill *billing.Billing cashu billing.Cashu cache *cache.Cache admins *groups.Admins storage storage.Storage tr *i18n.Bundle log *slog.Logger slots func() int id int64 username string events chan sched.Event payEvents chan billing.Event uploads chan struct{} // limits concurrent uploads to Telegram pump chan struct{} // wakes the playlist pump rate *rateLimiter bg sync.WaitGroup baseCtx context.Context metrics *metrics.Metrics // widgets decides whether HTML widgets are tried; nil turns them off. widgets *widget.Breaker liveMu sync.Mutex live map[string]*liveJob // status widgets by delivery ID liveTried map[string]int // deliveries a status widget was tried for statusMu sync.Mutex statuses map[string]*statusState // by delivery ID sending map[string]bool // jobs being delivered right now pumping map[int64]bool // users whose next playlist item is being started // cancelledAt is when each user last sent /cancel. A playlist item // that was already being looked up at that moment must not start. cancelledAt map[int64]time.Time // broadcasts holds texts waiting for the owner's confirmation. broadcasts map[string]string reloadI18n func() error // broadcastGap is the pause between two broadcast messages. broadcastGap time.Duration // Tunables, shortened in tests. reconcileEvery time.Duration statusMinGap time.Duration // invoiceGrace is how long a paid purchase may lack an invoice message // before the payer is told in a new message. invoiceGrace time.Duration } // New creates the bot and learns its own username, which is needed to // recognize commands addressed as /cmd@botname. func New(ctx context.Context, d Deps) (*Bot, error) { me, err := d.API.GetMe(ctx) if err != nil { return nil, fmt.Errorf("bot: getMe: %w", err) } if d.Log == nil { d.Log = slog.Default() } if d.WorkerSlots == nil { d.WorkerSlots = func() int { return 1 } } b := &Bot{ api: d.API, cfg: d.Config, store: d.Store, sched: d.Sched, svc: d.Service, bill: d.Billing, cashu: d.Cashu, cache: d.Cache, storage: d.Storage, tr: d.I18n, log: d.Log, slots: d.WorkerSlots, id: me.ID, username: me.Username, events: make(chan sched.Event, 1024), payEvents: make(chan billing.Event, 256), uploads: make(chan struct{}, 4), pump: make(chan struct{}, 1), rate: newRateLimiter(), baseCtx: ctx, statuses: map[string]*statusState{}, metrics: d.Metrics, live: map[string]*liveJob{}, liveTried: map[string]int{}, sending: map[string]bool{}, pumping: map[int64]bool{}, cancelledAt: map[int64]time.Time{}, broadcasts: map[string]string{}, reloadI18n: d.ReloadI18n, broadcastGap: 50 * time.Millisecond, admins: d.Admins, reconcileEvery: 5 * time.Second, statusMinGap: 3 * time.Second, invoiceGrace: 5 * time.Second, } if b.admins == nil { b.admins = groups.NewAdmins(d.API, 0) } if d.Config.Telegram.Widgets { b.widgets = widget.NewBreaker() } d.Service.SetAdmins(b.admins) d.Sched.Subscribe(func(ev sched.Event) { select { case b.events <- ev: default: // The reconcile loop picks up anything dropped here. } }) d.Billing.Subscribe(func(ev billing.Event) { select { case b.payEvents <- ev: default: // The reconcile loop picks up unfulfilled purchases. } }) return b, nil } // Username returns the bot's @username without the at sign. func (b *Bot) Username() string { return b.username } // SetTimings overrides the reconcile interval and the minimum gap between // status edits. Tests use it to run fast. func (b *Bot) SetTimings(reconcile, statusGap time.Duration) { b.reconcileEvery = reconcile b.statusMinGap = statusGap b.invoiceGrace = 4 * reconcile b.broadcastGap = time.Millisecond } // Admins returns the group admin checker, shared with the Mini App API. func (b *Bot) Admins() *groups.Admins { return b.admins } // Run processes updates and job events until ctx ends, then waits for // in-flight work to finish. func (b *Bot) Run(ctx context.Context, updates <-chan telego.Update) { b.baseCtx = ctx n := b.cfg.Telegram.UpdateWorkers if n < 1 { n = 1 } // Updates of one chat always go to the same worker, so they are // handled in order. lanes := make([]chan telego.Update, n) var wg sync.WaitGroup for i := range lanes { lanes[i] = make(chan telego.Update, 64) wg.Add(1) go func(ch <-chan telego.Update) { defer wg.Done() for u := range ch { b.safely("update", func() { b.HandleUpdate(ctx, u) }) } }(lanes[i]) } wg.Add(1) go func() { defer wg.Done() b.eventLoop(ctx) }() loop: for { select { case <-ctx.Done(): break loop case u, ok := <-updates: if !ok { break loop } key := updateChatID(u) if key < 0 { key = -key } select { case lanes[int(key%int64(n))] <- u: case <-ctx.Done(): break loop } } } for _, ch := range lanes { close(ch) } wg.Wait() b.bg.Wait() } // goBG runs fn in the background and tracks it for shutdown. func (b *Bot) goBG(name string, fn func()) { b.bg.Add(1) go func() { defer b.bg.Done() b.safely(name, fn) }() } func (b *Bot) safely(name string, fn func()) { defer func() { if r := recover(); r != nil { b.log.Error("panic recovered", "where", name, "panic", fmt.Sprint(r), "stack", string(debug.Stack())) } }() fn() } func updateChatID(u telego.Update) int64 { switch { case u.Message != nil: return u.Message.Chat.ID case u.CallbackQuery != nil: if u.CallbackQuery.Message != nil { return u.CallbackQuery.Message.GetChat().ID } return u.CallbackQuery.From.ID case u.MyChatMember != nil: return u.MyChatMember.Chat.ID case u.WidgetQuery != nil: if u.WidgetQuery.Chat != nil { return u.WidgetQuery.Chat.ID } return u.WidgetQuery.From.ID } return int64(u.UpdateID) } // HandleUpdate routes one update. func (b *Bot) HandleUpdate(ctx context.Context, u telego.Update) { b.metrics.Update(updateType(u)) switch { case u.Message != nil: b.handleMessage(ctx, u.Message) case u.CallbackQuery != nil: b.handleCallback(ctx, u.CallbackQuery) case u.MyChatMember != nil: b.handleMyChatMember(ctx, u.MyChatMember) case u.WidgetQuery != nil: b.handleWidgetQuery(ctx, u.WidgetQuery) } } func updateType(u telego.Update) string { switch { case u.Message != nil: return "message" case u.CallbackQuery != nil: return "callback_query" case u.MyChatMember != nil: return "my_chat_member" case u.WidgetQuery != nil: return "widget_query" } return "other" } // actor is the user behind an update, with the language to answer in. type actor struct { user *db.User lang string } func (b *Bot) actorFor(ctx context.Context, from *telego.User) (actor, error) { u, err := b.store.UpsertUser(ctx, from.ID, from.Username, from.FirstName, from.LanguageCode) if err != nil { return actor{}, err } lang := u.LangOverride if lang == "" { lang = b.tr.Resolve(u.Lang) } return actor{user: u, lang: lang}, nil } func isPrivate(chatType string) bool { return chatType == telego.ChatTypePrivate } // --- sending helpers ------------------------------------------------------- func chatID(id int64) telego.ChatID { return telego.ChatID{ID: id} } func replyParams(messageID int64) *telego.ReplyParameters { if messageID == 0 { return nil } return &telego.ReplyParameters{MessageID: int(messageID), AllowSendingWithoutReply: true} } var noPreview = &telego.LinkPreviewOptions{IsDisabled: true} // send posts an HTML message, optionally as a reply and with buttons. func (b *Bot) send(ctx context.Context, chat, replyTo int64, text string, kb *telego.InlineKeyboardMarkup) (*telego.Message, error) { p := &telego.SendMessageParams{ ChatID: chatID(chat), Text: text, ParseMode: telego.ModeHTML, LinkPreviewOptions: noPreview, ReplyParameters: replyParams(replyTo), } if kb != nil { p.ReplyMarkup = kb } msg, err := b.api.SendMessage(ctx, p) if err != nil { b.log.Warn("sendMessage failed", "chat_id", chat, "err", err) } return msg, err } // edit changes the text (or the caption, for photo cards) and the buttons // of a message. A nil keyboard removes the buttons. func (b *Bot) edit(ctx context.Context, chat, messageID int64, isPhoto bool, text string, kb *telego.InlineKeyboardMarkup) error { if messageID == 0 { return nil } var err error if isPhoto { _, err = b.api.EditMessageCaption(ctx, &telego.EditMessageCaptionParams{ ChatID: chatID(chat), MessageID: int(messageID), Caption: clip(text, 1024), ParseMode: telego.ModeHTML, ReplyMarkup: kb, }) } else { _, err = b.api.EditMessageText(ctx, &telego.EditMessageTextParams{ ChatID: chatID(chat), MessageID: int(messageID), Text: clip(text, 4096), ParseMode: telego.ModeHTML, LinkPreviewOptions: noPreview, ReplyMarkup: kb, }) } if err != nil && !tg.IsNotModified(err) { if !tg.IsMessageGone(err) { b.log.Warn("edit failed", "chat_id", chat, "message_id", messageID, "err", err) } return err } return nil } // answer acknowledges a button press, optionally with a short notice. func (b *Bot) answer(ctx context.Context, q *telego.CallbackQuery, text string, alert bool) { err := b.api.AnswerCallbackQuery(ctx, &telego.AnswerCallbackQueryParams{ CallbackQueryID: q.ID, Text: clip(text, 200), ShowAlert: alert, }) if err != nil { b.log.Debug("answerCallbackQuery failed", "err", err) } } func (b *Bot) deleteMessage(ctx context.Context, chat, messageID int64) { if messageID == 0 { return } if err := b.api.DeleteMessage(ctx, &telego.DeleteMessageParams{ChatID: chatID(chat), MessageID: int(messageID)}); err != nil { b.log.Debug("deleteMessage failed", "chat_id", chat, "err", err) } } func (b *Bot) chatAction(ctx context.Context, chat int64, action string) { _ = b.api.SendChatAction(ctx, &telego.SendChatActionParams{ChatID: chatID(chat), Action: action}) }