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>
This commit is contained in:
Michilis
2026-11-18 09:46:32 +00:00
co-authored by Claude Fable 5.2
parent 7d4893bc3f
commit 51371da0e0
23 changed files with 3231 additions and 81 deletions
+27
View File
@@ -17,6 +17,7 @@ import (
"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/sched"
"github.com/noderunners/dlbot/internal/service"
@@ -41,6 +42,10 @@ type Deps struct {
// 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
}
// Bot handles Telegram updates and job events.
@@ -53,6 +58,7 @@ type Bot struct {
bill *billing.Billing
cashu billing.Cashu
cache *cache.Cache
admins *groups.Admins
storage storage.Storage
tr *i18n.Bundle
log *slog.Logger
@@ -75,6 +81,11 @@ type Bot struct {
// 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
@@ -122,10 +133,18 @@ func New(ctx context.Context, d Deps) (*Bot, error) {
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)
}
d.Service.SetAdmins(b.admins)
d.Sched.Subscribe(func(ev sched.Event) {
select {
case b.events <- ev:
@@ -152,8 +171,12 @@ 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) {
@@ -236,6 +259,8 @@ func updateChatID(u telego.Update) int64 {
return u.CallbackQuery.Message.GetChat().ID
}
return u.CallbackQuery.From.ID
case u.MyChatMember != nil:
return u.MyChatMember.Chat.ID
}
return int64(u.UpdateID)
}
@@ -247,6 +272,8 @@ func (b *Bot) HandleUpdate(ctx context.Context, u telego.Update) {
b.handleMessage(ctx, u.Message)
case u.CallbackQuery != nil:
b.handleCallback(ctx, u.CallbackQuery)
case u.MyChatMember != nil:
b.handleMyChatMember(ctx, u.MyChatMember)
}
}
+7
View File
@@ -51,6 +51,13 @@ func (b *Bot) startLink(ctx context.Context, lr linkRequest) {
}
return
}
// Whether the requester may use the bot here at all is settled before
// anything is looked up: maintenance, and a group's own rules.
who := service.Who{UserID: lr.act.user.ID, ChatID: lr.chatID, ChatType: lr.chatType}
if err := b.svc.Gate(ctx, who); err != nil {
b.refuse(ctx, lr.chatID, lr.sourceID, lr.act.lang, err)
return
}
b.goBG("link", func() { b.linkFlow(ctx, lr) })
}
+181 -62
View File
@@ -10,6 +10,7 @@ import (
"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"
@@ -33,79 +34,55 @@ func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) {
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
}
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 "fresh":
b.cmdLink(ctx, m, act, linkRequest{fresh: true})
case "subs":
b.cmdLink(ctx, m, act, linkRequest{subs: true})
case "history":
b.cmdHistory(ctx, m, act)
case "purge":
if b.isOwner(m) {
b.cmdPurge(ctx, m, act)
}
case "cache":
if b.isOwner(m) {
b.cmdCache(ctx, m, act)
}
case "workers":
if b.isOwner(m) {
b.cmdWorkers(ctx, m, act)
}
case "drain":
if b.isOwner(m) {
b.cmdDrain(ctx, m, act)
}
case "ytdlp":
if b.isOwner(m) {
b.cmdYtDlp(ctx, m, act)
}
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)
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 // groups are driven by commands; auto-detect is an admin opt-in
return
}
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
@@ -116,10 +93,131 @@ func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) {
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 {
@@ -184,6 +282,12 @@ func (b *Bot) cmdStart(ctx context.Context, m *telego.Message, act actor) {
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
@@ -380,8 +484,23 @@ func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) {
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:
+619
View File
@@ -0,0 +1,619 @@
package bot
import (
"context"
"strconv"
"strings"
"time"
"github.com/mymmrac/telego"
"github.com/noderunners/dlbot/internal/billing"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/groups"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/service"
)
const (
cbGroupSetting = "gs" // gs:<key>
cbGroupBuy = "gb" // gb:<product>:<chat id>[:<amount>]
cbQuality = "ql" // ql:<profile or "ask">
cbLanguage = "lg" // lg:<language or "auto">
)
// handleMyChatMember records the groups the bot is in. Telegram sends this
// update whenever the bot is added, removed, promoted or demoted.
func (b *Bot) handleMyChatMember(ctx context.Context, u *telego.ChatMemberUpdated) {
if !groups.IsGroup(u.Chat.Type) || u.NewChatMember == nil {
return
}
g := &db.Group{
ChatID: u.Chat.ID, Title: u.Chat.Title, Type: u.Chat.Type,
BotStatus: u.NewChatMember.MemberStatus(), AddedBy: u.From.ID,
}
if err := b.store.UpsertGroup(ctx, g); err != nil {
b.log.Error("record group", "chat_id", u.Chat.ID, "err", err)
return
}
b.admins.Forget(u.Chat.ID)
b.log.Info("group status changed", "chat_id", g.ChatID, "status", g.BotStatus, "by", u.From.ID)
}
// noteGroup makes sure a group the bot is used in is on record, also when
// the my_chat_member update was missed, and notes who uses it.
func (b *Bot) noteGroup(ctx context.Context, chat telego.Chat, userID int64) {
if _, err := b.store.GetGroup(ctx, chat.ID); err != nil {
_ = b.store.UpsertGroup(ctx, &db.Group{ChatID: chat.ID, Title: chat.Title, Type: chat.Type, BotStatus: "member"})
}
if err := b.store.SeeGroupUser(ctx, chat.ID, userID); err != nil {
b.log.Debug("note group user", "err", err)
}
}
// requireAdmin checks that a command was sent in a group by one of its
// admins, and tells the sender when it was not.
func (b *Bot) requireAdmin(ctx context.Context, m *telego.Message, act actor) bool {
if !groups.IsGroup(m.Chat.Type) {
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "notice.group_only", nil), nil)
return false
}
if !b.admins.IsAdmin(ctx, m.Chat.ID, act.user.ID) {
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "notice.admins_only", nil), nil)
return false
}
return true
}
func (b *Bot) requireGroup(ctx context.Context, m *telego.Message, act actor) bool {
if groups.IsGroup(m.Chat.Type) {
return true
}
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "notice.group_only", nil), nil)
return false
}
func (b *Bot) onOff(lang string, on bool) string {
if on {
return b.tr.T(lang, "word.on", nil)
}
return b.tr.T(lang, "word.off", nil)
}
func (b *Bot) qualityName(lang, q string) string {
if q == "" {
return b.tr.T(lang, "quality.ask", nil)
}
p, err := media.Parse(q)
if err != nil {
return q
}
return b.profileLabel(lang, p)
}
// groupSettingsLink opens the full settings of a group: the Mini App page
// when the Mini App is set up, the private chat otherwise. Web app buttons
// do not work in groups, so this is always a plain link.
func (b *Bot) groupSettingsLink(chatID int64) string {
id := strconv.FormatInt(chatID, 10)
if b.cfg.MiniAppEnabled() {
return "https://t.me/" + b.username + "?startapp=group_" + id
}
return "https://t.me/" + b.username + "?start=gs_" + id
}
func (b *Bot) groupWalletLink(chatID int64) string {
return "https://t.me/" + b.username + "?start=gw_" + strconv.FormatInt(chatID, 10)
}
// settingsView renders the quick settings of a group.
func (b *Bot) settingsView(ctx context.Context, lang string, st *db.GroupSettings) (string, *telego.InlineKeyboardMarkup) {
wallet, _ := b.bill.State(ctx, db.OwnerGroup, st.ChatID)
pass := b.tr.T(lang, "word.none", nil)
if wallet.PassUntil > 0 {
pass = b.tr.DateTime(lang, time.UnixMilli(wallet.PassUntil))
}
groupLang := st.Lang
if groupLang == "" {
groupLang = b.tr.T(lang, "settings.lang_auto", nil)
}
sites := func(list string) string {
if list == "" {
return b.tr.T(lang, "word.none", nil)
}
return strings.Join(db.Sites(list), ", ")
}
text := b.tr.HTML(lang, "settings.text", i18n.Args{
"Balance": b.tr.Sats(lang, wallet.Credits),
"Pass": pass,
"Lang": groupLang,
"Allowed": sites(st.Allowed),
"Blocked": sites(st.Blocked),
"SpendCap": b.tr.Sats(lang, st.SpendCap),
"DailyCap": b.capSats(lang, st.DailyCap),
})
row := func(key, label, value string) []telego.InlineKeyboardButton {
return []telego.InlineKeyboardButton{button(
b.tr.T(lang, "settings.button", i18n.Args{"Label": label, "Value": value}), cbData(cbGroupSetting, key))}
}
kb := keyboard(
row("en", b.tr.T(lang, "settings.enabled", nil), b.onOff(lang, st.Enabled)),
row("ad", b.tr.T(lang, "settings.auto_detect", nil), b.onOff(lang, st.AutoDetect)),
row("dc", b.tr.T(lang, "settings.delete_commands", nil), b.onOff(lang, st.DeleteCmds)),
row("wu", b.tr.T(lang, "settings.who", nil), b.tr.T(lang, "settings.who_"+st.WhoCanUse, nil)),
row("sp", b.tr.T(lang, "settings.spend", nil), b.tr.T(lang, "settings.spend_"+st.SpendRule, nil)),
row("dq", b.tr.T(lang, "settings.quality", nil), b.qualityName(lang, st.Quality)),
[]telego.InlineKeyboardButton{urlButton(b.tr.T(lang, "btn.full_settings", nil), b.groupSettingsLink(st.ChatID))},
)
return text, kb
}
func (b *Bot) capSats(lang string, n int64) string {
if n <= 0 {
return b.tr.T(lang, "account.unlimited", nil)
}
return b.tr.Sats(lang, n)
}
func (b *Bot) cmdSettings(ctx context.Context, m *telego.Message, act actor) {
if !b.requireAdmin(ctx, m, act) {
return
}
st, err := b.store.GetGroupSettings(ctx, m.Chat.ID)
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
text, kb := b.settingsView(ctx, act.lang, st)
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), text, kb)
}
// next returns the value after cur in a cycle.
func next(cur string, cycle ...string) string {
for i, v := range cycle {
if v == cur {
return cycle[(i+1)%len(cycle)]
}
}
return cycle[0]
}
// cbSetting handles a quick toggle under /settings. The admin check runs
// on every press: the buttons are visible to everyone in the group.
func (b *Bot) cbSetting(ctx context.Context, q *telego.CallbackQuery, act actor, key string) {
if q.Message == nil || !groups.IsGroup(q.Message.GetChat().Type) {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
chat := q.Message.GetChat().ID
if !b.admins.IsAdmin(ctx, chat, act.user.ID) {
b.answer(ctx, q, b.tr.T(act.lang, "notice.admins_only", nil), true)
return
}
st, err := b.store.GetGroupSettings(ctx, chat)
if err != nil {
b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true)
return
}
switch key {
case "en":
st.Enabled = !st.Enabled
case "ad":
st.AutoDetect = !st.AutoDetect
case "dc":
st.DeleteCmds = !st.DeleteCmds
case "wu":
st.WhoCanUse = next(st.WhoCanUse, db.UseEveryone, db.UsePassHolders, db.UseAdmins)
case "sp":
st.SpendRule = next(st.SpendRule, db.SpendAdmins, db.SpendAnyone, db.SpendCapped)
if st.SpendRule == db.SpendCapped && st.SpendCap == 0 {
st.SpendCap = 4 * b.cfg.Prices.CreditPerDownload
}
case "dq":
st.Quality = next(st.Quality, "", string(media.Best), string(media.P720), string(media.P480), string(media.MP3))
default:
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
if err := b.store.SaveGroupSettings(ctx, st); err != nil {
b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true)
return
}
b.log.Info("group setting changed", "chat_id", chat, "key", key, "by", act.user.ID)
// The group may have its own language; the view follows it.
lang := act.lang
if st.Lang != "" {
lang = st.Lang
}
text, kb := b.settingsView(ctx, lang, st)
b.answer(ctx, q, b.tr.T(lang, "notice.saved", nil), false)
_ = b.edit(ctx, chat, int64(q.Message.GetMessageID()), false, text, kb)
}
// changeSettings loads, changes and saves a group's settings for an admin
// command, and confirms with the given message.
func (b *Bot) changeSettings(ctx context.Context, m *telego.Message, act actor, change func(*db.GroupSettings) (key string, args i18n.Args)) {
st, err := b.store.GetGroupSettings(ctx, m.Chat.ID)
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
key, args := change(st)
if key == "" {
return
}
if strings.HasPrefix(key, "!") { // a refusal: nothing to save
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, key[1:], args), nil)
return
}
if err := b.store.SaveGroupSettings(ctx, st); err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
lang := act.lang
if st.Lang != "" {
lang = st.Lang
}
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(lang, key, args), nil)
}
func (b *Bot) cmdGroupLang(ctx context.Context, m *telego.Message, act actor) {
if !b.requireAdmin(ctx, m, act) {
return
}
arg := strings.ToLower(strings.TrimSpace(commandArgs(m)))
b.changeSettings(ctx, m, act, func(st *db.GroupSettings) (string, i18n.Args) {
if arg == "" {
return "!grouplang.usage", i18n.Args{"Langs": strings.Join(b.tr.Langs(), ", ")}
}
if arg == "auto" {
st.Lang = ""
return "grouplang.auto", nil
}
for _, l := range b.tr.Langs() {
if l == arg {
st.Lang = l
return "grouplang.set", i18n.Args{"Lang": b.tr.T(l, "language.name", nil)}
}
}
return "!grouplang.usage", i18n.Args{"Langs": strings.Join(b.tr.Langs(), ", ")}
})
}
func (b *Bot) cmdAutoDetect(ctx context.Context, m *telego.Message, act actor) {
if !b.requireAdmin(ctx, m, act) {
return
}
arg := strings.ToLower(strings.TrimSpace(commandArgs(m)))
b.changeSettings(ctx, m, act, func(st *db.GroupSettings) (string, i18n.Args) {
switch arg {
case "on":
st.AutoDetect = true
return "autodetect.on", nil
case "off":
st.AutoDetect = false
return "autodetect.off", nil
}
return "!autodetect.usage", nil
})
}
// cmdSiteList handles /allow and /block: no argument shows the list, a
// host adds it, "remove <host>" removes it, "clear" empties the list.
func (b *Bot) cmdSiteList(ctx context.Context, m *telego.Message, act actor, allow bool) {
if !b.requireAdmin(ctx, m, act) {
return
}
name := "block"
if allow {
name = "allow"
}
fields := strings.Fields(commandArgs(m))
b.changeSettings(ctx, m, act, func(st *db.GroupSettings) (string, i18n.Args) {
list := &st.Blocked
if allow {
list = &st.Allowed
}
show := func() i18n.Args {
v := strings.Join(db.Sites(*list), ", ")
if v == "" {
v = b.tr.T(act.lang, "word.none", nil)
}
return i18n.Args{"Sites": v}
}
switch {
case len(fields) == 0:
return "!" + name + ".list", show()
case fields[0] == "clear":
*list = ""
return name + ".list", show()
}
remove := fields[0] == "remove"
if remove {
fields = fields[1:]
}
if len(fields) == 0 {
return "!" + name + ".list", show()
}
host := groups.CleanHost(fields[0])
if host == "" {
return "!sites.bad_host", nil
}
var kept []string
for _, h := range db.Sites(*list) {
if h != host {
kept = append(kept, h)
}
}
if !remove && len(kept) < 50 {
kept = append(kept, host)
}
*list = strings.Join(kept, ",")
return name + ".list", show()
})
}
// cmdSpending handles /spending anyone | admins | capped <sats> and
// /spending daily <sats>.
func (b *Bot) cmdSpending(ctx context.Context, m *telego.Message, act actor) {
if !b.requireAdmin(ctx, m, act) {
return
}
fields := strings.Fields(strings.ToLower(commandArgs(m)))
b.changeSettings(ctx, m, act, func(st *db.GroupSettings) (string, i18n.Args) {
amount := func(i int) (int64, bool) {
if len(fields) <= i {
return 0, false
}
n, err := strconv.ParseInt(fields[i], 10, 64)
return n, err == nil && n >= 0 && n <= billing.MaxAmount
}
if len(fields) == 0 {
return "!spending.usage", nil
}
switch fields[0] {
case db.SpendAnyone, db.SpendAdmins:
st.SpendRule = fields[0]
case db.SpendCapped:
n, ok := amount(1)
if !ok || n == 0 {
return "!spending.usage", nil
}
st.SpendRule, st.SpendCap = db.SpendCapped, n
case "daily":
n, ok := amount(1)
if !ok {
return "!spending.usage", nil
}
st.DailyCap = n
default:
return "!spending.usage", nil
}
return "spending.set", i18n.Args{
"Rule": b.tr.T(act.lang, "settings.spend_"+st.SpendRule, nil),
"SpendCap": b.tr.Sats(act.lang, st.SpendCap),
"DailyCap": b.capSats(act.lang, st.DailyCap),
}
})
}
// cmdGroupWallet shows the group's balance and pass to anyone, with links
// to top it up. Paying happens in the private chat.
func (b *Bot) cmdGroupWallet(ctx context.Context, m *telego.Message, act actor, passOnly bool) {
if !b.requireGroup(ctx, m, act) {
return
}
lang := act.lang
wallet, err := b.bill.State(ctx, db.OwnerGroup, m.Chat.ID)
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
st, err := b.store.GetGroupSettings(ctx, m.Chat.ID)
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
pass := b.tr.T(lang, "groupwallet.pass_none", nil)
if wallet.PassUntil > 0 {
pass = b.tr.T(lang, "groupwallet.pass_until", i18n.Args{"Until": b.tr.DateTime(lang, time.UnixMilli(wallet.PassUntil))})
}
key := "groupwallet.text"
if passOnly {
key = "grouppass.text"
}
text := b.tr.HTML(lang, key, i18n.Args{
"Balance": b.tr.Sats(lang, wallet.Credits),
"Pass": pass,
"Rule": b.tr.T(lang, "settings.spend_"+st.SpendRule, nil),
})
var kb *telego.InlineKeyboardMarkup
if b.bill.Enabled() {
label := "btn.add_group_credits"
if passOnly {
label = "btn.buy_group_pass"
}
kb = keyboard([]telego.InlineKeyboardButton{urlButton(b.tr.T(lang, label, nil), b.groupWalletLink(m.Chat.ID))})
}
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), text, kb)
}
func (b *Bot) cmdGroupStats(ctx context.Context, m *telego.Message, act actor) {
if !b.requireAdmin(ctx, m, act) {
return
}
lang := act.lang
since := service.Day(time.Now().AddDate(0, 0, -6))
usage, err := b.store.GroupUsage(ctx, m.Chat.ID, since, 15)
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
if len(usage) == 0 {
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(lang, "groupstats.empty", nil), nil)
return
}
var sb strings.Builder
sb.WriteString(b.tr.HTML(lang, "groupstats.header", nil))
for _, u := range usage {
name := u.Name
if name == "" {
name = strconv.FormatInt(u.UserID, 10)
}
sb.WriteString("\n")
sb.WriteString(b.tr.HTML(lang, "groupstats.line", i18n.Args{
"Name": shorten(name, 30), "Count": u.Downloads,
"Size": b.tr.Size(lang, u.Bytes), "Sats": b.tr.Sats(lang, u.Sats),
}))
}
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), sb.String(), nil)
}
// --- paying for a group, in the private chat --------------------------------
// startGroupLink handles /start gw_<chat id> and gs_<chat id>, the deep
// links from a group. The target wallet is the group's, pre-selected.
func (b *Bot) startGroupLink(ctx context.Context, m *telego.Message, act actor, arg string, settings bool) {
lang := act.lang
chatID, err := strconv.ParseInt(arg, 10, 64)
g, gerr := b.store.GetGroup(ctx, chatID)
if err != nil || gerr != nil || !g.Present() {
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "groupbuy.unknown", nil), nil)
return
}
if settings {
// Without the Mini App the full settings are the admin commands.
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "settings.commands", i18n.Args{"Group": g.Title}), nil)
return
}
if !b.bill.Enabled() {
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "buy.unavailable", nil), nil)
return
}
wallet, _ := b.bill.State(ctx, db.OwnerGroup, chatID)
gid := strconv.FormatInt(chatID, 10)
rows := b.passButtons(lang, func(product string) string { return cbData(cbGroupBuy, product, gid) })
var packs []telego.InlineKeyboardButton
for _, a := range b.cfg.Prices.CreditPacks {
packs = append(packs, button(b.tr.Sats(lang, a), cbData(cbGroupBuy, billing.ProductCredits, gid, strconv.FormatInt(a, 10))))
}
rows = append(rows, packs)
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "groupbuy.intro", i18n.Args{
"Group": g.Title, "Balance": b.tr.Sats(lang, wallet.Credits),
}), keyboard(rows...))
}
// cbGroupBuyProduct creates an invoice whose target is a group wallet.
// Anyone may pay for a group; what they buy belongs to the group.
func (b *Bot) cbGroupBuyProduct(ctx context.Context, q *telego.CallbackQuery, act actor, product, rest string) {
gidArg, amountArg, _ := strings.Cut(rest, ":")
chatID, err := strconv.ParseInt(gidArg, 10, 64)
g, gerr := b.store.GetGroup(ctx, chatID)
if err != nil || gerr != nil || !g.Present() {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
b.answer(ctx, q, "", false)
amount, _ := strconv.ParseInt(amountArg, 10, 64)
b.startPurchase(ctx, act.user.ID, act, product, amount, purchaseContext{groupID: chatID})
}
// --- personal preferences ---------------------------------------------------
func (b *Bot) cmdQuality(ctx context.Context, m *telego.Message, act actor) {
lang := act.lang
opt := func(value string) telego.InlineKeyboardButton {
label := b.qualityName(lang, value)
if value == act.user.Quality {
label = "✓ " + label
}
data := value
if data == "" {
data = "ask"
}
return button(label, cbData(cbQuality, data))
}
kb := keyboard(
[]telego.InlineKeyboardButton{opt("")},
[]telego.InlineKeyboardButton{opt(string(media.Best)), opt(string(media.P1080)), opt(string(media.P720)), opt(string(media.P480))},
[]telego.InlineKeyboardButton{opt(string(media.MP3))},
)
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(lang, "quality.pick", nil), kb)
}
func (b *Bot) cbSetQuality(ctx context.Context, q *telego.CallbackQuery, act actor, value string) {
if value == "ask" {
value = ""
}
if value != "" {
if p, err := media.Parse(value); err != nil || (p.Kind() != media.KindVideo && p.Kind() != media.KindAudio) {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
}
if err := b.store.SetUserQuality(ctx, act.user.ID, value); err != nil {
b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true)
return
}
b.answer(ctx, q, b.tr.T(act.lang, "notice.saved", nil), false)
if q.Message != nil {
_ = b.edit(ctx, q.Message.GetChat().ID, int64(q.Message.GetMessageID()), false,
b.tr.HTML(act.lang, "quality.set", i18n.Args{"Quality": b.qualityName(act.lang, value)}), nil)
}
}
func (b *Bot) cmdLanguage(ctx context.Context, m *telego.Message, act actor) {
var row []telego.InlineKeyboardButton
var rows [][]telego.InlineKeyboardButton
for _, l := range b.tr.Langs() {
if b.tr.Hidden(l) {
continue
}
// Each language is listed under its own name.
row = append(row, button(b.tr.T(l, "language.name", nil), cbData(cbLanguage, l)))
if len(row) == 3 {
rows = append(rows, row)
row = nil
}
}
rows = append(rows, row, []telego.InlineKeyboardButton{button(b.tr.T(act.lang, "language.auto", nil), cbData(cbLanguage, "auto"))})
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "language.pick", nil), keyboard(rows...))
}
func (b *Bot) cbSetLanguage(ctx context.Context, q *telego.CallbackQuery, act actor, value string) {
lang := ""
if value != "auto" {
for _, l := range b.tr.Langs() {
if l == value {
lang = l
}
}
if lang == "" {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
}
if err := b.store.SetUserLang(ctx, act.user.ID, lang); err != nil {
b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true)
return
}
shown := lang
if shown == "" {
shown = b.tr.Resolve(act.user.Lang)
}
b.answer(ctx, q, b.tr.T(shown, "notice.saved", nil), false)
if q.Message != nil {
_ = b.edit(ctx, q.Message.GetChat().ID, int64(q.Message.GetMessageID()), false,
b.tr.HTML(shown, "language.set", i18n.Args{"Lang": b.tr.T(shown, "language.name", nil)}), nil)
}
}
// cmdStatic answers /privacy, /terms and /support from the catalog.
func (b *Bot) cmdStatic(ctx context.Context, m *telego.Message, act actor, key string) {
contact := b.cfg.Support
if contact == "" {
contact = "@" + b.username
}
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, key, i18n.Args{"Contact": contact}), nil)
}
+41 -5
View File
@@ -305,6 +305,8 @@ type purchaseContext struct {
requestID string
profile string
deliveryID string
// groupID makes a group's wallet the target instead of the payer's.
groupID int64
}
// startPurchase creates the invoice and shows it in the private chat.
@@ -316,7 +318,12 @@ func (b *Bot) startPurchase(ctx context.Context, chat int64, act actor, product
_, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "buy.bad_amount", nil), nil)
return
}
w, err := b.bill.Wallet(ctx, db.OwnerUser, act.user.ID)
// Every purchase has a target: the payer's own wallet or a group's.
ownerType, ownerID := db.OwnerUser, act.user.ID
if pc.groupID != 0 {
ownerType, ownerID = db.OwnerGroup, pc.groupID
}
w, err := b.bill.Wallet(ctx, ownerType, ownerID)
if err != nil {
b.internalError(ctx, chat, act, err)
return
@@ -347,12 +354,30 @@ func (b *Bot) startPurchase(ctx context.Context, chat int64, act actor, product
func (b *Bot) invoiceText(p *db.Purchase) string {
lang := p.Lang
minutes := b.cfg.LNbits.InvoiceExpiry.D()
return b.tr.HTML(lang, "invoice.caption", i18n.Args{
text := b.tr.HTML(lang, "invoice.caption", i18n.Args{
"Title": b.productTitle(lang, p.Product),
"Amount": b.tr.Sats(lang, p.AmountSats),
"Invoice": p.Bolt11,
"Valid": b.tr.Span(lang, minutes),
})
if title := b.groupTitle(p); title != "" {
text = b.tr.HTML(lang, "invoice.for_group", i18n.Args{"Group": title}) + "\n" + text
}
return text
}
// groupTitle returns the title of the group a purchase is for, or "" when
// its target is the payer's own wallet.
func (b *Bot) groupTitle(p *db.Purchase) string {
w, err := b.store.GetWallet(b.baseCtx, p.WalletID)
if err != nil || w.OwnerType != db.OwnerGroup {
return ""
}
g, err := b.store.GetGroup(b.baseCtx, w.OwnerID)
if err != nil || g.Title == "" {
return strconv.FormatInt(w.OwnerID, 10)
}
return g.Title
}
func (b *Bot) invoiceKeyboard(p *db.Purchase) *telego.InlineKeyboardMarkup {
@@ -544,12 +569,18 @@ func (b *Bot) paidText(ctx context.Context, p *db.Purchase) string {
if err != nil {
return text
}
// The same facts, worded for whose wallet it is.
balanceKey, passKey := "invoice.balance", "invoice.pass_until"
if w.OwnerType == db.OwnerGroup {
balanceKey, passKey = "invoice.group_balance", "invoice.group_pass_until"
text = b.tr.HTML(lang, "invoice.for_group", i18n.Args{"Group": b.groupTitle(p)}) + "\n" + text
}
switch p.Product {
case billing.ProductCredits:
text += "\n" + b.tr.HTML(lang, "invoice.balance", i18n.Args{"Balance": b.tr.Sats(lang, w.Balance)})
text += "\n" + b.tr.HTML(lang, balanceKey, i18n.Args{"Balance": b.tr.Sats(lang, w.Balance)})
case billing.ProductPassDay, billing.ProductPassWeek, billing.ProductPassMonth:
if until, err := b.store.PassUntil(ctx, w.ID, db.NowMilli()); err == nil && until > 0 {
text += "\n" + b.tr.HTML(lang, "invoice.pass_until", i18n.Args{"Until": b.tr.DateTime(lang, time.UnixMilli(until))})
text += "\n" + b.tr.HTML(lang, passKey, i18n.Args{"Until": b.tr.DateTime(lang, time.UnixMilli(until))})
}
case billing.ProductDonation:
text += "\n" + b.tr.HTML(lang, "invoice.thanks", nil)
@@ -712,8 +743,13 @@ func (b *Bot) offerUpgrade(ctx context.Context, chat, replyTo int64, lang string
})
}
} else {
// Two targets, both pre-selected by the link: the requester's own
// wallet, or the group's.
link := "https://t.me/" + b.username + "?start=buy_" + req.ID + "_" + encodeProfile(string(profile))
rows = append(rows, []telego.InlineKeyboardButton{urlButton(b.tr.T(lang, "btn.buy_for_me", nil), link)})
rows = append(rows,
[]telego.InlineKeyboardButton{urlButton(b.tr.T(lang, "btn.buy_for_me", nil), link)},
[]telego.InlineKeyboardButton{urlButton(b.tr.T(lang, "btn.add_group_credits", nil), b.groupWalletLink(chat))},
)
}
_, _ = b.send(ctx, chat, replyTo, text, keyboard(rows...))
}
+538
View File
@@ -0,0 +1,538 @@
package bot
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"strconv"
"strings"
"time"
"github.com/mymmrac/telego"
"github.com/noderunners/dlbot/internal/billing"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/groups"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/service"
"github.com/noderunners/dlbot/internal/tg"
)
const cbBroadcast = "bc" // bc:<token>
// ownerCommand runs an owner command and reports whether cmd was one.
// Owner commands only work in a private chat for the configured owners;
// for everyone else they do not exist.
func (b *Bot) ownerCommand(ctx context.Context, m *telego.Message, act actor, cmd string) bool {
if !b.isOwner(m) {
return false
}
switch cmd {
case "purge":
b.cmdPurge(ctx, m, act)
case "cache":
b.cmdCache(ctx, m, act)
case "workers":
b.cmdWorkers(ctx, m, act)
case "drain":
b.cmdDrain(ctx, m, act)
case "ytdlp":
b.cmdYtDlp(ctx, m, act)
case "stats":
b.cmdStats(ctx, m, act)
case "user":
b.cmdUser(ctx, m, act)
case "group":
b.cmdGroup(ctx, m, act)
case "ban", "unban":
b.cmdBan(ctx, m, act, cmd == "ban")
case "grant":
b.cmdGrant(ctx, m, act)
case "credit":
b.cmdCredit(ctx, m, act, false)
case "refund":
b.cmdCredit(ctx, m, act, true)
case "blocklist":
b.cmdBlocklist(ctx, m, act)
case "broadcast":
b.cmdBroadcast(ctx, m, act)
case "maint":
b.cmdMaint(ctx, m, act)
case "reload":
b.cmdReload(ctx, m, act)
default:
return false
}
return true
}
func (b *Bot) ownerReply(ctx context.Context, m *telego.Message, act actor, key string, args i18n.Args) {
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, key, args), nil)
}
func (b *Bot) cmdStats(ctx context.Context, m *telego.Message, act actor) {
lang := act.lang
now := time.Now()
users, _ := b.store.CountUsers(ctx)
jobs, _ := b.store.JobCounts(ctx, now.Add(-24*time.Hour).UnixMilli())
paid, free, oldest, _ := b.store.QueueDepth(ctx, now.UnixMilli())
running, _ := b.store.CountRunning(ctx)
sats, _ := b.store.SatsReceived(ctx)
bst := b.bill.Stats()
cst := b.cache.Stats()
rate := "0%"
if t := cst.Hits + cst.Misses; t > 0 {
rate = b.tr.Percent(lang, float64(cst.Hits)/float64(t))
}
books := b.tr.T(lang, "owner.books_ok", nil)
if bad, err := b.store.VerifyWallets(ctx); err != nil || len(bad) > 0 {
books = b.tr.T(lang, "owner.books_bad", i18n.Args{"Count": len(bad)})
}
ln := b.tr.T(lang, "word.off", nil)
if b.bill.Enabled() {
ln = b.tr.T(lang, "owner.ln_ok", nil)
if !b.bill.Reachable() {
ln = b.tr.T(lang, "owner.ln_down", nil)
}
}
maint, _ := b.store.GetKV(ctx, "maintenance")
b.ownerReply(ctx, m, act, "owner.stats", i18n.Args{
"Users": b.tr.Number(lang, users),
"Done": b.tr.Number(lang, jobs[db.JobDone]),
"Failed": b.tr.Number(lang, jobs[db.JobFailed]),
"Paid": paid, "Free": free, "Running": running, "Slots": b.sched.Capacity(),
"Oldest": b.tr.Span(lang, time.Duration(oldest)*time.Millisecond),
"Rate": rate,
"Saved": b.tr.Size(lang, cst.BytesSaved),
"Sats": b.tr.Sats(lang, sats),
"Created": bst.InvoicesCreated, "Settled": bst.InvoicesSettled,
"Lightning": ln, "Books": books, "Maint": b.onOff(lang, maint == "1"),
})
}
// cmdQueueAll is /queue all for owners: every queued and running job.
func (b *Bot) cmdQueueAll(ctx context.Context, m *telego.Message, act actor) {
jobs, err := b.store.ActiveJobs(ctx, 30)
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
if len(jobs) == 0 {
b.ownerReply(ctx, m, act, "owner.queue_empty", nil)
return
}
var sb strings.Builder
sb.WriteString(b.tr.HTML(act.lang, "owner.queue_header", i18n.Args{"Count": len(jobs)}))
for _, j := range jobs {
worker := j.WorkerID
if worker == "" {
worker = "-"
}
tags := j.RequiredTags
if tags == "" {
tags = "-"
}
sb.WriteString("\n")
sb.WriteString(b.tr.HTML(act.lang, "owner.queue_line", i18n.Args{
"ID": j.ID[len(j.ID)-6:], "Status": j.Status, "Lane": j.Lane, "Profile": j.Profile,
"Worker": worker, "Tags": tags, "Title": shorten(j.Title, 40),
}))
}
_, _ = b.send(ctx, m.Chat.ID, 0, sb.String(), nil)
}
func idArg(m *telego.Message) (id int64, rest []string, ok bool) {
fields := strings.Fields(commandArgs(m))
if len(fields) == 0 {
return 0, nil, false
}
id, err := strconv.ParseInt(fields[0], 10, 64)
return id, fields[1:], err == nil && id != 0
}
func (b *Bot) cmdUser(ctx context.Context, m *telego.Message, act actor) {
lang := act.lang
id, _, ok := idArg(m)
if !ok {
b.ownerReply(ctx, m, act, "owner.user_usage", nil)
return
}
u, err := b.store.GetUser(ctx, id)
if err != nil {
b.ownerReply(ctx, m, act, "owner.not_found", nil)
return
}
st, _ := b.bill.State(ctx, db.OwnerUser, id)
usage, _ := b.svc.Usage(ctx, id)
refs, _ := b.store.CountReferrals(ctx, id)
pass := b.tr.T(lang, "word.none", nil)
if st.PassUntil > 0 {
pass = b.tr.DateTime(lang, time.UnixMilli(st.PassUntil))
}
b.ownerReply(ctx, m, act, "owner.user", i18n.Args{
"ID": id, "Name": u.FirstName, "Username": u.Username, "Lang": u.Lang + "/" + u.LangOverride,
"Banned": b.onOff(lang, u.Banned), "Pass": pass, "Balance": b.tr.Sats(lang, st.Credits),
"Downloads": usage.Downloads, "Volume": b.tr.Size(lang, usage.Bytes), "Referrals": refs,
"Since": b.tr.DateTime(lang, time.UnixMilli(u.CreatedAt)),
})
}
func (b *Bot) cmdGroup(ctx context.Context, m *telego.Message, act actor) {
lang := act.lang
id, _, ok := idArg(m)
if !ok {
b.ownerReply(ctx, m, act, "owner.group_usage", nil)
return
}
g, err := b.store.GetGroup(ctx, id)
if err != nil {
b.ownerReply(ctx, m, act, "owner.not_found", nil)
return
}
st, _ := b.store.GetGroupSettings(ctx, id)
w, _ := b.bill.State(ctx, db.OwnerGroup, id)
pass := b.tr.T(lang, "word.none", nil)
if w.PassUntil > 0 {
pass = b.tr.DateTime(lang, time.UnixMilli(w.PassUntil))
}
b.ownerReply(ctx, m, act, "owner.group", i18n.Args{
"ID": id, "Title": g.Title, "Status": g.BotStatus, "Enabled": b.onOff(lang, st.Enabled),
"Who": st.WhoCanUse, "Spend": st.SpendRule, "Pass": pass, "Balance": b.tr.Sats(lang, w.Credits),
})
}
func (b *Bot) cmdBan(ctx context.Context, m *telego.Message, act actor, ban bool) {
id, _, ok := idArg(m)
if !ok {
b.ownerReply(ctx, m, act, "owner.ban_usage", nil)
return
}
if ban && b.cfg.IsOwner(id) {
b.ownerReply(ctx, m, act, "owner.ban_owner", nil)
return
}
found, err := b.store.SetUserBanned(ctx, id, ban)
switch {
case err != nil:
b.internalError(ctx, m.Chat.ID, act, err)
case !found:
b.ownerReply(ctx, m, act, "owner.not_found", nil)
case ban:
b.log.Info("user banned", "user_id", id, "by", act.user.ID)
b.ownerReply(ctx, m, act, "owner.banned", i18n.Args{"ID": id})
default:
b.ownerReply(ctx, m, act, "owner.unbanned", i18n.Args{"ID": id})
}
}
// walletFor returns the wallet of a user (positive ID) or group (negative).
func (b *Bot) walletFor(ctx context.Context, id int64) (*db.Wallet, error) {
if id < 0 {
if _, err := b.store.GetGroup(ctx, id); err != nil {
return nil, err
}
return b.bill.Wallet(ctx, db.OwnerGroup, id)
}
if _, err := b.store.GetUser(ctx, id); err != nil {
return nil, err
}
return b.bill.Wallet(ctx, db.OwnerUser, id)
}
func uniqueRef() string {
var raw [8]byte
_, _ = rand.Read(raw[:])
return hex.EncodeToString(raw[:])
}
// cmdGrant handles
//
// /grant <id> day|week|month a pass for a user or a group
// /grant code credits <sats> [uses] a gift code for credits
// /grant code day|week|month [uses] a gift code for a pass
func (b *Bot) cmdGrant(ctx context.Context, m *telego.Message, act actor) {
lang := act.lang
fields := strings.Fields(strings.ToLower(commandArgs(m)))
if len(fields) >= 2 && fields[0] == "code" {
kind, rest := fields[1], fields[2:]
var amount int64
if kind == billing.GiftCredits {
if len(rest) == 0 {
b.ownerReply(ctx, m, act, "owner.grant_usage", nil)
return
}
amount, _ = strconv.ParseInt(rest[0], 10, 64)
rest = rest[1:]
}
uses := 1
if len(rest) > 0 {
uses, _ = strconv.Atoi(rest[0])
}
g, err := b.bill.NewGiftCode(ctx, kind, amount, uses, 0, act.user.ID)
if err != nil {
b.ownerReply(ctx, m, act, "owner.grant_usage", nil)
return
}
b.ownerReply(ctx, m, act, "owner.gift_code", i18n.Args{"Code": g.Code, "Uses": g.MaxUses})
return
}
id, rest, ok := idArg(m)
if !ok || len(rest) != 1 || billing.PassLength(strings.ToLower(rest[0])) == 0 {
b.ownerReply(ctx, m, act, "owner.grant_usage", nil)
return
}
w, err := b.walletFor(ctx, id)
if err != nil {
b.ownerReply(ctx, m, act, "owner.not_found", nil)
return
}
pass, err := b.bill.GrantPass(ctx, w.ID, strings.ToLower(rest[0]), "owner:"+strconv.FormatInt(act.user.ID, 10))
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
b.log.Info("pass granted", "target", id, "kind", rest[0], "by", act.user.ID)
b.ownerReply(ctx, m, act, "owner.granted", i18n.Args{"ID": id, "Until": b.tr.DateTime(lang, time.UnixMilli(pass.ExpiresAt))})
}
// cmdCredit handles /credit <id> <sats> and /refund <id> <sats>, and
// /refund <id> pass <duration> which extends a running pass.
func (b *Bot) cmdCredit(ctx context.Context, m *telego.Message, act actor, refund bool) {
lang := act.lang
usage := "owner.credit_usage"
if refund {
usage = "owner.refund_usage"
}
id, rest, ok := idArg(m)
if !ok || len(rest) == 0 {
b.ownerReply(ctx, m, act, usage, nil)
return
}
w, err := b.walletFor(ctx, id)
if err != nil {
b.ownerReply(ctx, m, act, "owner.not_found", nil)
return
}
if refund && rest[0] == "pass" {
if len(rest) != 2 {
b.ownerReply(ctx, m, act, usage, nil)
return
}
d, err := time.ParseDuration(rest[1])
if err != nil || d <= 0 || d > 90*24*time.Hour {
b.ownerReply(ctx, m, act, usage, nil)
return
}
extended, err := b.store.ExtendPass(ctx, w.ID, d.Milliseconds(), db.NowMilli())
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
if !extended {
b.ownerReply(ctx, m, act, "owner.no_pass", nil)
return
}
until, _ := b.store.PassUntil(ctx, w.ID, db.NowMilli())
b.ownerReply(ctx, m, act, "owner.granted", i18n.Args{"ID": id, "Until": b.tr.DateTime(lang, time.UnixMilli(until))})
return
}
sats, err := strconv.ParseInt(rest[0], 10, 64)
if err != nil || sats <= 0 || sats > billing.MaxAmount {
b.ownerReply(ctx, m, act, usage, nil)
return
}
ref := uniqueRef()
if refund {
_, err = b.bill.Refund(ctx, w.ID, sats, "owner_refund", ref, "owner-refund:"+ref, act.user.ID)
} else {
_, err = b.bill.Credit(ctx, w.ID, sats, "owner_grant", ref, "owner-grant:"+ref, act.user.ID)
}
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
nw, _ := b.store.GetWallet(ctx, w.ID)
b.log.Info("wallet credited by owner", "target", id, "sats", sats, "refund", refund, "by", act.user.ID)
b.ownerReply(ctx, m, act, "owner.credited", i18n.Args{
"ID": id, "Amount": b.tr.Sats(lang, sats), "Balance": b.tr.Sats(lang, nw.Balance),
})
}
// cmdBlocklist handles /blocklist, /blocklist add site|key <value> [reason]
// and /blocklist remove site|key <value>.
func (b *Bot) cmdBlocklist(ctx context.Context, m *telego.Message, act actor) {
fields := strings.Fields(commandArgs(m))
if len(fields) == 0 || fields[0] == "list" {
list, err := b.store.ListBlocks(ctx, 50)
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
if len(list) == 0 {
b.ownerReply(ctx, m, act, "owner.blocklist_empty", nil)
return
}
var sb strings.Builder
sb.WriteString(b.tr.HTML(act.lang, "owner.blocklist_header", nil))
for _, e := range list {
sb.WriteString("\n")
sb.WriteString(b.tr.HTML(act.lang, "owner.blocklist_line", i18n.Args{"Kind": e.Kind, "Value": e.Value, "Reason": e.Reason}))
}
_, _ = b.send(ctx, m.Chat.ID, 0, sb.String(), nil)
return
}
if len(fields) < 3 || (fields[1] != db.BlockSite && fields[1] != db.BlockKey) {
b.ownerReply(ctx, m, act, "owner.blocklist_usage", nil)
return
}
kind, value := fields[1], fields[2]
if kind == db.BlockSite {
if value = groups.CleanHost(value); value == "" {
b.ownerReply(ctx, m, act, "owner.blocklist_usage", nil)
return
}
}
switch fields[0] {
case "add":
if err := b.store.AddBlock(ctx, kind, value, strings.Join(fields[3:], " "), act.user.ID); err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
b.ownerReply(ctx, m, act, "owner.blocked", i18n.Args{"Value": value})
case "remove":
found, err := b.store.RemoveBlock(ctx, kind, value)
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
if !found {
b.ownerReply(ctx, m, act, "owner.not_found", nil)
return
}
b.ownerReply(ctx, m, act, "owner.unblocked", i18n.Args{"Value": value})
default:
b.ownerReply(ctx, m, act, "owner.blocklist_usage", nil)
}
}
func (b *Bot) cmdMaint(ctx context.Context, m *telego.Message, act actor) {
arg := strings.ToLower(strings.TrimSpace(commandArgs(m)))
if arg != "on" && arg != "off" {
b.ownerReply(ctx, m, act, "owner.maint_usage", nil)
return
}
v := "0"
if arg == "on" {
v = "1"
}
if err := b.store.SetKV(ctx, "maintenance", v); err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
b.log.Info("maintenance mode", "on", arg == "on", "by", act.user.ID)
b.ownerReply(ctx, m, act, "owner.maint_"+arg, nil)
}
func (b *Bot) cmdReload(ctx context.Context, m *telego.Message, act actor) {
if strings.TrimSpace(commandArgs(m)) != "i18n" {
b.ownerReply(ctx, m, act, "owner.reload_usage", nil)
return
}
if b.reloadI18n == nil {
b.ownerReply(ctx, m, act, "owner.reload_builtin", nil)
return
}
if err := b.reloadI18n(); err != nil {
b.log.Error("reload catalogs", "err", err)
b.ownerReply(ctx, m, act, "owner.reload_failed", i18n.Args{"Error": err.Error()})
return
}
b.RegisterCommands(ctx)
b.ownerReply(ctx, m, act, "owner.reloaded", i18n.Args{"Langs": strings.Join(b.tr.Langs(), ", ")})
}
// cmdBroadcast shows a preview with a confirm button. Nothing is sent
// until the owner presses it.
func (b *Bot) cmdBroadcast(ctx context.Context, m *telego.Message, act actor) {
text := strings.TrimSpace(commandArgs(m))
if text == "" {
b.ownerReply(ctx, m, act, "owner.broadcast_usage", nil)
return
}
users, _ := b.store.CountUsers(ctx)
token := uniqueRef()
b.statusMu.Lock()
b.broadcasts[token] = text
b.statusMu.Unlock()
kb := keyboard([]telego.InlineKeyboardButton{
button(b.tr.T(act.lang, "owner.broadcast_send", i18n.Args{"Count": users}), cbData(cbBroadcast, token)),
})
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "owner.broadcast_preview", i18n.Args{"Text": text}), kb)
}
func (b *Bot) cbBroadcastSend(ctx context.Context, q *telego.CallbackQuery, act actor, token string) {
if !b.cfg.IsOwner(act.user.ID) {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
b.statusMu.Lock()
text, ok := b.broadcasts[token]
delete(b.broadcasts, token)
b.statusMu.Unlock()
if !ok {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
b.answer(ctx, q, "", false)
b.goBG("broadcast", func() {
sent, failed := b.broadcast(ctx, text)
b.log.Info("broadcast finished", "sent", sent, "failed", failed, "by", act.user.ID)
_, _ = b.send(ctx, act.user.ID, 0, b.tr.HTML(act.lang, "owner.broadcast_done", i18n.Args{"Sent": sent, "Failed": failed}), nil)
})
}
// broadcast sends a plain text message to every user, at a pace well
// under Telegram's limit of about 30 messages per second.
func (b *Bot) broadcast(ctx context.Context, text string) (sent, failed int) {
var after int64
for ctx.Err() == nil {
ids, err := b.store.UserIDs(ctx, after, 200)
if err != nil || len(ids) == 0 {
return
}
for _, id := range ids {
after = id
_, err := b.api.SendMessage(ctx, &telego.SendMessageParams{ChatID: chatID(id), Text: text, LinkPreviewOptions: noPreview})
switch {
case err == nil:
sent++
case tg.RetryAfter(err) > 0:
sleepCtx(ctx, tg.RetryAfter(err))
failed++
default:
failed++
}
sleepCtx(ctx, b.broadcastGap)
if ctx.Err() != nil {
return
}
}
}
return
}
// refuse answers a link with the reason it cannot be handled here. Some
// refusals are silent: a group that switched the bot off does not want to
// hear from it.
func (b *Bot) refuse(ctx context.Context, chat, replyTo int64, lang string, err error) {
var le *service.LimitError
if !errors.As(err, &le) {
b.log.Error("gate", "err", err)
return
}
if le.Code == service.LimitGroupDisabled {
return
}
_, _ = b.send(ctx, chat, replyTo, b.tr.HTML(lang, "limit."+le.Code, nil), nil)
}