Files
Media-download-telegram-bot/internal/bot/commands.go
T
MichilisandClaude Fable 5.2 0d50f453a0 Phase 2: money
Lightning payments through LNbits, wallets, passes, credits, the
entitlement resolver and priority lanes.

- internal/entitle: pure resolver (one-off, own pass, group pass, group
  credits, own credits, free) with a table-driven suite and an invariant
  check over every input combination
- internal/billing: wallets, append-only ledger with dedupe keys, stacking
  passes, purchases, gift codes, referral reward
- LNbits client verified against v0.12.12 and v1.7.1 source
- Settlement by one conditional UPDATE: idempotent under any mix of
  webhooks, polls and the check button. Webhooks are unsigned, so every
  payment is confirmed with LNbits before it is credited
- Polling fallback, reconciliation of all unsettled invoices at startup,
  late payments still honored, no expiry while LNbits is unreachable
- Charge, quota and job are written in one transaction; failed, cancelled
  and undeliverable downloads are refunded exactly once
- Paid lane first with one slot of the fleet reserved for free users
- Daily download quota and daily volume cap, per-user and per-group rate
  limits
- Bot: /buy /account /limits /credits /redeem /referral /donate, QR invoice
  message that flips to paid, over-limit offer (passes or this file only),
  deep links from groups, skip the queue
- Fake LNbits server for tests; end-to-end money flows including a payment
  made while the core was down

Cashu redemption is behind an interface and not implemented.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 08:09:35 +00:00

374 lines
11 KiB
Go

package bot
import (
"context"
"errors"
"strconv"
"strings"
"github.com/mymmrac/telego"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/links"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/sched"
"github.com/noderunners/dlbot/internal/service"
)
// maxLinksPerMessage caps how many links of one message get a card.
const maxLinksPerMessage = 3
func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) {
if m.From == nil || m.From.IsBot {
return
}
act, err := b.actorFor(ctx, m.From)
if err != nil {
b.log.Error("load user", "user_id", m.From.ID, "err", err)
return
}
if act.user.Banned {
return
}
private := isPrivate(m.Chat.Type)
cmd, forUs, isCmd := b.parseCommand(m)
if isCmd {
if !forUs {
return // addressed to another bot in the group
}
switch cmd {
case "start":
b.cmdStart(ctx, m, act)
case "help":
b.cmdHelp(ctx, m, act)
case "dl":
b.cmdDownload(ctx, m, act, "")
case "audio":
b.cmdDownload(ctx, m, act, media.MP3)
case "thumb":
b.cmdDownload(ctx, m, act, media.Thumb)
case "info":
b.cmdInfo(ctx, m, act)
case "queue":
b.cmdQueue(ctx, m, act)
case "cancel":
b.cmdCancel(ctx, m, act)
case "buy":
b.cmdBuy(ctx, m, act)
case "account":
b.cmdAccount(ctx, m, act)
case "limits":
b.cmdLimits(ctx, m, act)
case "credits":
b.cmdCredits(ctx, m, act)
case "donate":
b.cmdDonate(ctx, m, act)
case "redeem":
b.cmdRedeem(ctx, m, act, commandArgs(m))
case "referral":
b.cmdReferral(ctx, m, act)
default:
if private {
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "cmd.unknown", nil), nil)
}
}
return
}
if !private {
return // groups are driven by commands; auto-detect is an admin opt-in
}
urls := messageLinks(m)
if len(urls) == 0 {
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "hint.send_link", nil), nil)
return
}
if len(urls) > maxLinksPerMessage {
urls = urls[:maxLinksPerMessage]
}
for _, u := range urls {
b.startLink(ctx, linkRequest{
chatID: m.Chat.ID, chatType: m.Chat.Type, sourceID: int64(m.MessageID), act: act, url: u,
})
}
}
// commandArgs returns the text after the command of a message.
func commandArgs(m *telego.Message) string {
for _, e := range m.Entities {
if e.Type == telego.EntityTypeBotCommand && e.Offset == 0 && e.Length <= len(m.Text) {
return strings.TrimSpace(m.Text[e.Length:])
}
}
return ""
}
// parseCommand finds a bot command at the start of the message. forUs is
// false when the command names a different bot (/dl@otherbot).
func (b *Bot) parseCommand(m *telego.Message) (cmd string, forUs, isCmd bool) {
for _, e := range m.Entities {
if e.Type != telego.EntityTypeBotCommand || e.Offset != 0 {
continue
}
// Commands are ASCII, so the UTF-16 length is also the byte length.
if e.Length > len(m.Text) || e.Length < 2 {
return "", false, false
}
full := m.Text[1:e.Length]
name, target, hasTarget := strings.Cut(full, "@")
if hasTarget && !strings.EqualFold(target, b.username) {
return "", false, true
}
return strings.ToLower(name), true, true
}
return "", false, false
}
func toLinkEntities(ents []telego.MessageEntity) []links.Entity {
out := make([]links.Entity, 0, len(ents))
for _, e := range ents {
out = append(out, links.Entity{Type: e.Type, Offset: e.Offset, Length: e.Length, URL: e.URL})
}
return out
}
// messageLinks extracts links from the text or the caption of a message.
func messageLinks(m *telego.Message) []string {
if m == nil {
return nil
}
if urls := links.Extract(m.Text, toLinkEntities(m.Entities)); len(urls) > 0 {
return urls
}
return links.Extract(m.Caption, toLinkEntities(m.CaptionEntities))
}
func (b *Bot) cmdStart(ctx context.Context, m *telego.Message, act actor) {
if !isPrivate(m.Chat.Type) {
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "start.group", nil), nil)
return
}
// Deep links arrive as "/start <payload>".
payload := commandArgs(m)
switch {
case strings.HasPrefix(payload, "buy_"):
b.startBuyLink(ctx, m, act, strings.TrimPrefix(payload, "buy_"))
return
case strings.HasPrefix(payload, "skip_"):
b.startSkipLink(ctx, m, act, strings.TrimPrefix(payload, "skip_"))
return
case payload == "buy":
b.showBuy(ctx, m.Chat.ID, act)
return
case strings.HasPrefix(payload, "ref_"):
// Only somebody who is new to the bot can be referred.
if referrer, err := strconv.ParseInt(strings.TrimPrefix(payload, "ref_"), 10, 64); err == nil && act.user.IsNew {
if _, err := b.store.SetReferrer(ctx, act.user.ID, referrer); err != nil {
b.log.Error("set referrer", "user_id", act.user.ID, "err", err)
}
}
}
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "start.private", i18n.Args{"Name": act.user.FirstName}), nil)
}
func (b *Bot) cmdHelp(ctx context.Context, m *telego.Message, act actor) {
dec, err := b.svc.Entitlement(ctx, service.Who{UserID: act.user.ID, ChatID: m.Chat.ID, ChatType: m.Chat.Type}, false)
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "help.text", i18n.Args{
"MaxSize": b.tr.Size(act.lang, dec.Limits.MaxSize),
"MaxDuration": b.tr.Span(act.lang, secondsDuration(dec.Limits.MaxDuration)),
}), nil)
}
// cmdDownload handles /dl, /audio and /thumb. The link comes from the
// command itself or from the message the command replies to. The bot
// answers under the message that holds the link.
func (b *Bot) cmdDownload(ctx context.Context, m *telego.Message, act actor, preset media.Profile) {
urls := messageLinks(m)
source := int64(m.MessageID)
if len(urls) == 0 && m.ReplyToMessage != nil {
urls = messageLinks(m.ReplyToMessage)
source = int64(m.ReplyToMessage.MessageID)
}
if len(urls) == 0 {
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "dl.usage", nil), nil)
return
}
b.startLink(ctx, linkRequest{
chatID: m.Chat.ID, chatType: m.Chat.Type, sourceID: source, act: act, url: urls[0], preset: preset,
})
}
func (b *Bot) cmdInfo(ctx context.Context, m *telego.Message, act actor) {
urls := messageLinks(m)
if len(urls) == 0 && m.ReplyToMessage != nil {
urls = messageLinks(m.ReplyToMessage)
}
if len(urls) == 0 {
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "info.usage", nil), nil)
return
}
url := urls[0]
b.goBG("info", func() {
b.chatAction(ctx, m.Chat.ID, telego.ChatActionTyping)
info, err := b.svc.Probe(ctx, url)
if err != nil {
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.probeErrorText(act.lang, err), nil)
return
}
var sb strings.Builder
sb.WriteString(b.cardText(act.lang, info, false))
sb.WriteString("\n")
profiles := append([]media.Profile{}, media.VideoProfiles...)
if info.HasAudio {
profiles = append(profiles, media.MP3, media.M4A)
}
for _, p := range profiles {
if h := p.Height(); h > 0 && info.MaxHeight > 0 && info.MaxHeight < h {
continue
}
size := b.tr.T(act.lang, "info.size_unknown", nil)
if n := info.Sizes[string(p)]; n > 0 {
size = b.tr.Size(act.lang, n)
}
sb.WriteString("\n")
sb.WriteString(b.tr.HTML(act.lang, "info.line", i18n.Args{"Label": b.profileLabel(act.lang, p), "Size": size}))
}
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), sb.String(), nil)
})
}
func (b *Bot) cmdQueue(ctx context.Context, m *telego.Message, act actor) {
dels, err := b.store.ActiveDeliveriesForUser(ctx, act.user.ID)
if err != nil {
b.log.Error("list deliveries", "err", err)
return
}
if len(dels) == 0 {
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "queue.empty", nil), nil)
return
}
var sb strings.Builder
sb.WriteString(b.tr.HTML(act.lang, "queue.header", i18n.Args{"Count": len(dels)}))
for _, d := range dels {
job, err := b.store.GetJob(ctx, d.JobID)
if err != nil {
continue
}
text, _, _ := b.renderStatus(ctx, d, job)
sb.WriteString("\n\n")
sb.WriteString(text)
}
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), sb.String(), nil)
}
func (b *Bot) cmdCancel(ctx context.Context, m *telego.Message, act actor) {
dels, err := b.store.ActiveDeliveriesForUser(ctx, act.user.ID)
if err != nil {
b.log.Error("list deliveries", "err", err)
return
}
n := 0
for _, d := range dels {
if b.cancelDelivery(ctx, d.ID, act.user.ID) == nil {
n++
}
}
key := "cancel.done"
if n == 0 {
key = "cancel.nothing"
}
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, key, i18n.Args{"Count": n}), nil)
}
// cancelDelivery withdraws one delivery and updates its status message.
func (b *Bot) cancelDelivery(ctx context.Context, deliveryID string, userID int64) error {
d, err := b.sched.CancelDelivery(ctx, deliveryID, userID)
if err != nil {
return err
}
note := b.release(ctx, d)
job, err := b.store.GetJob(ctx, d.JobID)
if err != nil {
return nil
}
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.cancelled", nil)+note)
return nil
}
// release gives back what an undelivered download took and returns a line
// to append to the status when sats were refunded.
func (b *Bot) release(ctx context.Context, d *db.Delivery) string {
refunded, err := b.svc.Release(context.WithoutCancel(ctx), d.ID)
if err != nil {
b.log.Error("release delivery", "delivery_id", d.ID, "err", err)
return ""
}
if refunded <= 0 {
return ""
}
return "\n" + b.tr.HTML(d.Lang, "status.refunded", i18n.Args{"Amount": b.tr.Sats(d.Lang, refunded)})
}
func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) {
act, err := b.actorFor(ctx, &q.From)
if err != nil {
b.log.Error("load user", "user_id", q.From.ID, "err", err)
return
}
if act.user.Banned {
b.answer(ctx, q, "", false)
return
}
action, id, arg := parseCallback(q.Data)
switch action {
case cbDownload:
b.cbDownload(ctx, q, act, id, arg)
case cbCancelCard:
b.cbCancelCard(ctx, q, act, id)
case cbSkipQueue:
b.cbSkip(ctx, q, act, id)
case cbBuy:
b.cbBuyProduct(ctx, q, act, id, arg)
case cbOfferBuy:
b.cbOffer(ctx, q, act, id, arg)
case cbPayCheck:
b.cbPayCheck(ctx, q, act, id)
case cbPayCancel:
b.cbPayCancel(ctx, q, act, id)
case cbCancelJob:
err := b.cancelDelivery(ctx, id, act.user.ID)
switch {
case err == nil:
b.answer(ctx, q, b.tr.T(act.lang, "notice.cancelled", nil), false)
case errors.Is(err, sched.ErrNotOwner):
b.answer(ctx, q, b.tr.T(act.lang, "notice.not_yours", nil), false)
case errors.Is(err, sched.ErrTooLate), errors.Is(err, db.ErrNotFound):
b.answer(ctx, q, b.tr.T(act.lang, "notice.too_late", nil), false)
default:
b.log.Error("cancel delivery", "delivery_id", id, "err", err)
b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true)
}
default:
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
}
}
// limitText renders a limit refusal for the user as plain text.
func (b *Bot) limitText(lang string, le *service.LimitError) string {
l := le.Decision.Limits
count := l.ActiveJobs
if le.Code == service.LimitDailyDownloads {
count = l.DailyDownloads
}
return b.tr.T(lang, "limit."+le.Code, i18n.Args{
"MaxSize": b.tr.Size(lang, l.MaxSize),
"MaxDuration": b.tr.Span(lang, secondsDuration(l.MaxDuration)),
"MaxVolume": b.tr.Size(lang, l.DailyBytes),
"Count": count,
})
}