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:
co-authored by
Claude Fable 5.2
parent
7d4893bc3f
commit
51371da0e0
@@ -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)
|
||||
}
|
||||
Reference in New Issue
Block a user