- Stars as a second payment method for passes and credit packs, next to Lightning (STARS_ENABLED, prices in [stars_prices] / STARS_PRICES, set on their own). Invoices in XTR with no provider token and one price; pre-checkout checks payer, state, currency and amount; successful_payment settles through the same transaction as Lightning, so entitlement is identical. Idempotent by telegram_payment_charge_id (unique index). - Migration 00009: payment_method on purchases and ledger entries, plus stars_amount, tg_charge_id and refunded_at on purchases. Stars purchases never reach LNbits. - Chat: buy screen, /credits, /account and the over-limit offer show Lightning first and a Pay with Stars button. - Mini App: Lightning and Stars switch on Buy; Stars use createInvoiceLink and WebApp.openInvoice, confirmed by the server-side payment event. - Owner /refund <purchase or charge ID> calls refundStarPayment and takes back the credits or pass; refunded_payment messages do the same once. /stats shows revenue by payment method. - The sats referral reward counts Lightning purchases only. - The bot now asks Telegram for pre_checkout_query updates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
520 lines
15 KiB
Go
520 lines
15 KiB
Go
// 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/thumb"
|
|
"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
|
|
// Thumbnails makes the thumbnail uploaded with a video. Nil gets the
|
|
// default, which fetches the source's thumbnail image.
|
|
Thumbnails Thumbnailer
|
|
}
|
|
|
|
// Thumbnailer turns a thumbnail URL into a JPEG Telegram accepts as the
|
|
// thumbnail of a video, or nil.
|
|
type Thumbnailer interface {
|
|
Fetch(ctx context.Context, url string) []byte
|
|
}
|
|
|
|
// 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
|
|
thumbs Thumbnailer
|
|
// 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
|
|
// menuButtons is the language each private chat's menu button was
|
|
// last labelled in.
|
|
menuButtons map[int64]string
|
|
// 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,
|
|
thumbs: d.Thumbnails,
|
|
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{},
|
|
menuButtons: map[int64]string{},
|
|
reloadI18n: d.ReloadI18n,
|
|
broadcastGap: 50 * time.Millisecond,
|
|
admins: d.Admins,
|
|
reconcileEvery: 5 * time.Second,
|
|
statusMinGap: 2500 * time.Millisecond,
|
|
invoiceGrace: 5 * time.Second,
|
|
}
|
|
if b.admins == nil {
|
|
b.admins = groups.NewAdmins(d.API, 0)
|
|
}
|
|
if b.thumbs == nil {
|
|
b.thumbs = thumb.New()
|
|
}
|
|
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
|
|
b.svc.SetProbeRetryDelay(10 * time.Millisecond)
|
|
}
|
|
|
|
// SetThumbnails replaces the thumbnail maker. Tests use it to stay off the
|
|
// network.
|
|
func (b *Bot) SetThumbnails(t Thumbnailer) { b.thumbs = t }
|
|
|
|
// 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.PreCheckoutQuery != nil:
|
|
return u.PreCheckoutQuery.From.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. The user behind it and the language to
|
|
// answer in are resolved once, here, and travel with the context.
|
|
func (b *Bot) HandleUpdate(ctx context.Context, u telego.Update) {
|
|
b.metrics.Update(updateType(u))
|
|
if from, chat := updateUser(u); from != nil {
|
|
act, err := b.resolveActor(ctx, from, chat)
|
|
if err != nil {
|
|
b.log.Error("load user", "user_id", from.ID, "err", err)
|
|
return
|
|
}
|
|
ctx = withActor(ctx, act)
|
|
}
|
|
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)
|
|
case u.PreCheckoutQuery != nil:
|
|
b.handlePreCheckout(ctx, u.PreCheckoutQuery)
|
|
}
|
|
}
|
|
|
|
// updateUser returns the person behind an update that needs an answer in
|
|
// their language, and the chat it happened in.
|
|
func updateUser(u telego.Update) (*telego.User, *telego.Chat) {
|
|
switch {
|
|
case u.Message != nil && u.Message.From != nil && !u.Message.From.IsBot:
|
|
return u.Message.From, &u.Message.Chat
|
|
case u.CallbackQuery != nil:
|
|
if m := u.CallbackQuery.Message; m != nil {
|
|
chat := m.GetChat()
|
|
return &u.CallbackQuery.From, &chat
|
|
}
|
|
return &u.CallbackQuery.From, nil
|
|
case u.PreCheckoutQuery != nil:
|
|
return &u.PreCheckoutQuery.From, nil
|
|
}
|
|
return nil, nil
|
|
}
|
|
|
|
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"
|
|
case u.PreCheckoutQuery != nil:
|
|
return "pre_checkout_query"
|
|
}
|
|
return "other"
|
|
}
|
|
|
|
// actor is the user behind an update, with the language to answer in.
|
|
type actor struct {
|
|
user *db.User
|
|
lang string
|
|
// group holds the settings of the group the update came from, nil in
|
|
// a private chat.
|
|
group *db.GroupSettings
|
|
}
|
|
|
|
type actorKey struct{}
|
|
|
|
func withActor(ctx context.Context, act actor) context.Context {
|
|
return context.WithValue(ctx, actorKey{}, act)
|
|
}
|
|
|
|
// actorFrom returns the actor HandleUpdate resolved for this update.
|
|
func actorFrom(ctx context.Context) (actor, bool) {
|
|
act, ok := ctx.Value(actorKey{}).(actor)
|
|
return act, ok
|
|
}
|
|
|
|
// resolveActor loads the user and picks the language to answer in: the
|
|
// language the user chose, then Telegram's language_code, then English.
|
|
// In a group with a language of its own, that language wins.
|
|
func (b *Bot) resolveActor(ctx context.Context, from *telego.User, chat *telego.Chat) (actor, error) {
|
|
act, err := b.actorFor(ctx, from)
|
|
if err != nil {
|
|
return act, err
|
|
}
|
|
if chat != nil && groups.IsGroup(chat.Type) {
|
|
gset, err := b.store.GetGroupSettings(ctx, chat.ID)
|
|
if err != nil {
|
|
return act, err
|
|
}
|
|
act.group = gset
|
|
if gset.Lang != "" {
|
|
act.lang = gset.Lang
|
|
}
|
|
}
|
|
return act, nil
|
|
}
|
|
|
|
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
|
|
}
|
|
return actor{user: u, lang: b.userLang(u)}, nil
|
|
}
|
|
|
|
// userLang is the language a user reads in a private chat.
|
|
func (b *Bot) userLang(u *db.User) string {
|
|
if u.LangOverride != "" {
|
|
return u.LangOverride
|
|
}
|
|
return b.tr.Resolve(u.Lang)
|
|
}
|
|
|
|
func isPrivate(chatType string) bool { return chatType == telego.ChatTypePrivate }
|
|
|
|
// --- sending helpers -------------------------------------------------------
|
|
|
|
func chatID(id int64) telego.ChatID { return telego.ChatID{ID: id} }
|
|
|
|
// replyParams quotes a message, in groups only. In a private chat there
|
|
// is one conversation and a quote only adds noise. Private chats have the
|
|
// user's own, positive ID; groups have negative IDs.
|
|
func replyParams(chat, messageID int64) *telego.ReplyParameters {
|
|
if messageID == 0 || chat > 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(chat, 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})
|
|
}
|