Files
Media-download-telegram-bot/internal/bot/commands.go
T
MichilisandClaude Fable 5.2 51371da0e0 Phase 5: groups
Group wallets, group passes, spending rules and admin-only settings.

- Groups recorded from my_chat_member; admin rights verified with
  getChatMember and cached for five minutes
- Group context in entitlement resolution: group pass, group credits under
  the spending rule (anyone, admins only, capped per person per day) and
  the group's daily cap; refunds go back to the wallet that paid
- Group gate before any lookup: bot on or off, who may use it, allowed
  and blocked sites, plus the owner's maintenance mode
- /settings with inline toggles checked on every press, /grouplang,
  /autodetect, /allow, /block, /spending, /groupwallet, /grouppass,
  /groupstats
- Deep links with the target pre-selected: paying for a group happens in
  the private chat; a refused download in a group offers "Buy for me" and
  "Add group credits"
- Optional link detection, tidy mode, default quality and language per
  group; per-member usage
- /quality, /language, /app, /privacy, /terms, /support
- Remaining owner tools: /stats, /queue all, /user, /group, /ban, /unban,
  /grant (passes and gift codes), /credit, /refund, /blocklist,
  /broadcast with confirmation, /maint, /reload i18n

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

554 lines
17 KiB
Go

package bot
import (
"context"
"errors"
"strconv"
"strings"
"time"
"github.com/mymmrac/telego"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/groups"
"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)
inGroup := groups.IsGroup(m.Chat.Type)
var gset *db.GroupSettings
if inGroup {
if gset, err = b.store.GetGroupSettings(ctx, m.Chat.ID); err != nil {
b.log.Error("load group settings", "chat_id", m.Chat.ID, "err", err)
return
}
// A group can pin its own language for everything said in it.
if gset.Lang != "" {
act.lang = gset.Lang
}
}
cmd, forUs, isCmd := b.parseCommand(m)
if isCmd {
if !forUs {
return // addressed to another bot in the group
}
if inGroup {
b.noteGroup(ctx, m.Chat, act.user.ID)
// A group that switched the bot off only hears from it when an
// admin opens the settings to switch it back on.
if !gset.Enabled && cmd != "settings" {
return
}
}
if b.ownerCommand(ctx, m, act, cmd) {
return
}
b.runCommand(ctx, m, act, cmd, gset)
return
}
urls := messageLinks(m)
if inGroup {
// Without a command the bot only acts when the admins turned on
// link detection. It then needs to see ordinary messages, which
// means group privacy mode off or the bot being an admin.
if !gset.Enabled || !gset.AutoDetect || len(urls) == 0 {
return
}
b.noteGroup(ctx, m.Chat, act.user.ID)
b.startLink(ctx, linkRequest{
chatID: m.Chat.ID, chatType: m.Chat.Type, sourceID: int64(m.MessageID), act: act, url: urls[0],
preset: presetFor(act, gset),
})
return
}
if !private {
return
}
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,
preset: presetFor(act, nil),
})
}
}
// presetFor returns the format to start without showing the card: the
// group's default quality in a group, the user's own in a private chat.
func presetFor(act actor, gset *db.GroupSettings) media.Profile {
q := act.user.Quality
if gset != nil {
q = gset.Quality
}
if p, err := media.Parse(q); err == nil {
return p
}
return ""
}
// runCommand dispatches the commands everyone can use.
func (b *Bot) runCommand(ctx context.Context, m *telego.Message, act actor, cmd string, gset *db.GroupSettings) {
// Commands that carry a link. In a group their message can be removed
// afterwards when the admins asked for a tidy chat.
tidy := func() {
if gset != nil && gset.DeleteCmds {
b.deleteMessage(ctx, m.Chat.ID, int64(m.MessageID))
}
}
switch cmd {
case "start":
b.cmdStart(ctx, m, act)
case "help":
b.cmdHelp(ctx, m, act)
case "dl":
b.cmdDownload(ctx, m, act, presetFor(act, gset))
tidy()
case "audio":
b.cmdDownload(ctx, m, act, media.MP3)
tidy()
case "thumb":
b.cmdDownload(ctx, m, act, media.Thumb)
tidy()
case "fresh":
b.cmdLink(ctx, m, act, linkRequest{fresh: true})
tidy()
case "subs":
b.cmdLink(ctx, m, act, linkRequest{subs: true})
tidy()
case "info":
b.cmdInfo(ctx, m, act)
case "history":
b.cmdHistory(ctx, m, act)
case "queue":
if b.isOwner(m) && strings.TrimSpace(commandArgs(m)) == "all" {
b.cmdQueueAll(ctx, m, act)
return
}
b.cmdQueue(ctx, m, act)
case "cancel":
b.cmdCancel(ctx, m, act)
case "quality":
b.cmdQuality(ctx, m, act)
case "language":
b.cmdLanguage(ctx, m, act)
case "app":
b.cmdApp(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)
case "privacy", "terms", "support":
if b.privateOnly(ctx, m, act) {
b.cmdStatic(ctx, m, act, "static."+cmd)
}
case "settings":
b.cmdSettings(ctx, m, act)
case "grouplang":
b.cmdGroupLang(ctx, m, act)
case "autodetect":
b.cmdAutoDetect(ctx, m, act)
case "allow":
b.cmdSiteList(ctx, m, act, true)
case "block":
b.cmdSiteList(ctx, m, act, false)
case "spending":
b.cmdSpending(ctx, m, act)
case "groupwallet":
b.cmdGroupWallet(ctx, m, act, false)
case "grouppass":
b.cmdGroupWallet(ctx, m, act, true)
case "groupstats":
b.cmdGroupStats(ctx, m, act)
default:
if isPrivate(m.Chat.Type) {
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "cmd.unknown", nil), nil)
}
}
}
// cmdApp points to the Mini App. In a private chat the button opens it in
// place; in a group it has to be a plain link, because web app buttons do
// not work there.
func (b *Bot) cmdApp(ctx context.Context, m *telego.Message, act actor) {
if !b.cfg.MiniAppEnabled() {
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "app.unavailable", nil), nil)
return
}
label := b.tr.T(act.lang, "btn.open_app", nil)
btn := urlButton(label, "https://t.me/"+b.username+"?startapp")
if isPrivate(m.Chat.Type) {
btn = telego.InlineKeyboardButton{Text: label, WebApp: &telego.WebAppInfo{URL: b.cfg.PublicURL + "/app/"}}
}
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "app.open", nil),
keyboard([]telego.InlineKeyboardButton{btn}))
}
// 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 strings.HasPrefix(payload, "gw_"):
b.startGroupLink(ctx, m, act, strings.TrimPrefix(payload, "gw_"), false)
return
case strings.HasPrefix(payload, "gs_"):
b.startGroupLink(ctx, m, act, strings.TrimPrefix(payload, "gs_"), true)
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,
})
}
// cmdLink handles the commands that take a link and differ only in how
// the link flow runs: /fresh and /subs.
func (b *Bot) cmdLink(ctx context.Context, m *telego.Message, act actor, lr linkRequest) {
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
}
lr.chatID, lr.chatType, lr.sourceID, lr.act, lr.url = m.Chat.ID, m.Chat.Type, source, act, urls[0]
b.startLink(ctx, lr)
}
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) {
n := 0
// Playlist items that have not started go first. Cancelling a running
// download frees a slot, and the next waiting item would take it.
b.statusMu.Lock()
b.cancelledAt[act.user.ID] = time.Now()
b.statusMu.Unlock()
if waiting, err := b.store.CancelWaitingRequests(ctx, act.user.ID); err == nil {
n += int(waiting)
}
dels, err := b.store.ActiveDeliveriesForUser(ctx, act.user.ID)
if err != nil {
b.log.Error("list deliveries", "err", err)
return
}
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 {
bg := context.WithoutCancel(ctx)
refunded, err := b.svc.Release(bg, d.ID)
if err != nil {
b.log.Error("release delivery", "delivery_id", d.ID, "err", err)
return ""
}
if refunded <= 0 {
// Another path may have released it a moment ago.
refunded = b.svc.Refunded(bg, d.ID)
}
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
}
if q.Message != nil && groups.IsGroup(q.Message.GetChat().Type) {
if gset, err := b.store.GetGroupSettings(ctx, q.Message.GetChat().ID); err == nil && gset.Lang != "" {
act.lang = gset.Lang
}
}
action, id, arg := parseCallback(q.Data)
switch action {
case cbGroupSetting:
b.cbSetting(ctx, q, act, id)
case cbGroupBuy:
b.cbGroupBuyProduct(ctx, q, act, id, arg)
case cbQuality:
b.cbSetQuality(ctx, q, act, id)
case cbLanguage:
b.cbSetLanguage(ctx, q, act, id)
case cbBroadcast:
b.cbBroadcastSend(ctx, q, act, id)
case cbDownload:
b.cbDownload(ctx, q, act, id, arg)
case cbCancelCard:
b.cbCancelCard(ctx, q, act, id)
case cbPlaylist:
b.cbPlaylistStart(ctx, q, act, id, arg)
case cbResend:
b.cbResendFile(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,
})
}