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
+308
View File
@@ -0,0 +1,308 @@
package db
import (
"context"
"database/sql"
"errors"
"strings"
)
// Group is a chat the bot was added to.
type Group struct {
ChatID int64
Title string
Type string
BotStatus string // member, administrator, left, kicked
AddedBy int64
CreatedAt int64
UpdatedAt int64
}
// Present reports whether the bot is still in the group.
func (g *Group) Present() bool {
return g.BotStatus == "member" || g.BotStatus == "administrator" || g.BotStatus == "creator" || g.BotStatus == "restricted"
}
// Who may use the bot in a group.
const (
UseEveryone = "everyone"
UsePassHolders = "pass_holders"
UseAdmins = "admins"
)
// Who may spend the group's credits.
const (
SpendAnyone = "anyone"
SpendAdmins = "admins"
SpendCapped = "capped" // anyone, up to a number of sats per person per day
)
// GroupSettings are the per-group options admins control.
type GroupSettings struct {
ChatID int64
Enabled bool
AutoDetect bool
Allowed string // comma separated hosts; empty allows every site
Blocked string // comma separated hosts
WhoCanUse string
MaxSizeMB int64 // 0 means "whatever the tier allows"
MaxDuration int64 // seconds, 0 likewise
SpendRule string
SpendCap int64 // sats per person per day, for SpendCapped
DailyCap int64 // sats per day for the whole group, 0 for no cap
DeleteCmds bool
Quality string // default profile, "" shows the card
Lang string // "" follows each requester
UpdatedAt int64
}
// DefaultGroupSettings are the settings of a group nobody configured.
func DefaultGroupSettings(chatID int64) *GroupSettings {
return &GroupSettings{ChatID: chatID, Enabled: true, WhoCanUse: UseEveryone, SpendRule: SpendAdmins}
}
// Sites splits a comma separated host list.
func Sites(list string) []string {
var out []string
for _, s := range strings.Split(list, ",") {
if s = strings.ToLower(strings.TrimSpace(s)); s != "" {
out = append(out, s)
}
}
return out
}
// UpsertGroup records a group and the bot's status in it.
func (s *Store) UpsertGroup(ctx context.Context, g *Group) error {
now := NowMilli()
_, err := s.exec(ctx, `INSERT INTO groups (chat_id, title, type, bot_status, added_by, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (chat_id) DO UPDATE SET
title = CASE WHEN excluded.title <> '' THEN excluded.title ELSE groups.title END,
type = excluded.type, bot_status = excluded.bot_status, updated_at = excluded.updated_at`,
g.ChatID, g.Title, g.Type, g.BotStatus, g.AddedBy, now, now)
return err
}
// GetGroup loads a group.
func (s *Store) GetGroup(ctx context.Context, chatID int64) (*Group, error) {
var g Group
err := s.row(ctx, `SELECT chat_id, title, type, bot_status, added_by, created_at, updated_at
FROM groups WHERE chat_id = ?`, chatID).Scan(&g.ChatID, &g.Title, &g.Type, &g.BotStatus, &g.AddedBy,
&g.CreatedAt, &g.UpdatedAt)
if err != nil {
return nil, notFound(err)
}
return &g, nil
}
// GetGroupSettings loads a group's settings, or the defaults.
func (s *Store) GetGroupSettings(ctx context.Context, chatID int64) (*GroupSettings, error) {
g := DefaultGroupSettings(chatID)
err := s.row(ctx, `SELECT enabled, auto_detect, allowed_sites, blocked_sites, who_can_use, max_size_mb,
max_duration_s, spend_rule, spend_cap_sats, daily_cap_sats, delete_commands, default_quality, lang, updated_at
FROM group_settings WHERE chat_id = ?`, chatID).Scan(&g.Enabled, &g.AutoDetect, &g.Allowed, &g.Blocked,
&g.WhoCanUse, &g.MaxSizeMB, &g.MaxDuration, &g.SpendRule, &g.SpendCap, &g.DailyCap, &g.DeleteCmds,
&g.Quality, &g.Lang, &g.UpdatedAt)
if errors.Is(err, sql.ErrNoRows) {
return g, nil
}
return g, err
}
// SaveGroupSettings stores a group's settings.
func (s *Store) SaveGroupSettings(ctx context.Context, g *GroupSettings) error {
g.UpdatedAt = NowMilli()
_, err := s.exec(ctx, `INSERT INTO group_settings (chat_id, enabled, auto_detect, allowed_sites, blocked_sites,
who_can_use, max_size_mb, max_duration_s, spend_rule, spend_cap_sats, daily_cap_sats, delete_commands,
default_quality, lang, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (chat_id) DO UPDATE SET
enabled = excluded.enabled, auto_detect = excluded.auto_detect,
allowed_sites = excluded.allowed_sites, blocked_sites = excluded.blocked_sites,
who_can_use = excluded.who_can_use, max_size_mb = excluded.max_size_mb,
max_duration_s = excluded.max_duration_s, spend_rule = excluded.spend_rule,
spend_cap_sats = excluded.spend_cap_sats, daily_cap_sats = excluded.daily_cap_sats,
delete_commands = excluded.delete_commands, default_quality = excluded.default_quality,
lang = excluded.lang, updated_at = excluded.updated_at`,
g.ChatID, g.Enabled, g.AutoDetect, g.Allowed, g.Blocked, g.WhoCanUse, g.MaxSizeMB, g.MaxDuration,
g.SpendRule, g.SpendCap, g.DailyCap, g.DeleteCmds, g.Quality, g.Lang, g.UpdatedAt)
return err
}
// AddGroupUsage adds to a member's counters in a group for a day. Negative
// values give back.
func (s *Store) AddGroupUsage(ctx context.Context, chatID, userID int64, day, downloads int, sats, bytes int64) error {
_, err := s.exec(ctx, `INSERT INTO group_usage_daily (chat_id, user_id, day, downloads, sats, bytes)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT (chat_id, user_id, day) DO UPDATE SET
downloads = group_usage_daily.downloads + excluded.downloads,
sats = group_usage_daily.sats + excluded.sats,
bytes = group_usage_daily.bytes + excluded.bytes`, chatID, userID, day, downloads, sats, bytes)
return err
}
// GroupSpent returns the group credits spent on a day: by one member and
// by everyone.
func (s *Store) GroupSpent(ctx context.Context, chatID, userID int64, day int) (member, total int64, err error) {
var m, t sql.NullInt64
err = s.row(ctx, `SELECT
SUM(CASE WHEN user_id = ? THEN sats ELSE 0 END), SUM(sats)
FROM group_usage_daily WHERE chat_id = ? AND day = ?`, userID, chatID, day).Scan(&m, &t)
return m.Int64, t.Int64, err
}
// MemberUsage is one member's use of a group over a period.
type MemberUsage struct {
UserID int64
Name string
Downloads int64
Sats int64
Bytes int64
}
// GroupUsage sums usage per member since a day, biggest first.
func (s *Store) GroupUsage(ctx context.Context, chatID int64, sinceDay, limit int) ([]MemberUsage, error) {
rows, err := s.rows(ctx, `SELECT g.user_id, COALESCE(u.first_name, ''), SUM(g.downloads), SUM(g.sats), SUM(g.bytes)
FROM group_usage_daily g LEFT JOIN users u ON u.id = g.user_id
WHERE g.chat_id = ? AND g.day >= ?
GROUP BY g.user_id, u.first_name
ORDER BY SUM(g.downloads) DESC, g.user_id LIMIT ?`, chatID, sinceDay, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []MemberUsage
for rows.Next() {
var m MemberUsage
if err := rows.Scan(&m.UserID, &m.Name, &m.Downloads, &m.Sats, &m.Bytes); err != nil {
return nil, err
}
out = append(out, m)
}
return out, rows.Err()
}
// SeeGroupUser records that a user was active in a group.
func (s *Store) SeeGroupUser(ctx context.Context, chatID, userID int64) error {
_, err := s.exec(ctx, `INSERT INTO group_users (chat_id, user_id, last_seen_at) VALUES (?, ?, ?)
ON CONFLICT (chat_id, user_id) DO UPDATE SET last_seen_at = excluded.last_seen_at`,
chatID, userID, NowMilli())
return err
}
// GroupsOfUser lists the groups a user was seen in where the bot still is.
func (s *Store) GroupsOfUser(ctx context.Context, userID int64, limit int) ([]*Group, error) {
rows, err := s.rows(ctx, `SELECT g.chat_id, g.title, g.type, g.bot_status, g.added_by, g.created_at, g.updated_at
FROM groups g JOIN group_users gu ON gu.chat_id = g.chat_id
WHERE gu.user_id = ? AND g.bot_status IN ('member', 'administrator', 'restricted')
ORDER BY gu.last_seen_at DESC LIMIT ?`, userID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Group
for rows.Next() {
var g Group
if err := rows.Scan(&g.ChatID, &g.Title, &g.Type, &g.BotStatus, &g.AddedBy, &g.CreatedAt, &g.UpdatedAt); err != nil {
return nil, err
}
out = append(out, &g)
}
return out, rows.Err()
}
// --- key-value -------------------------------------------------------------
// GetKV reads a value, or "" when the key is not set.
func (s *Store) GetKV(ctx context.Context, key string) (string, error) {
var v string
err := s.row(ctx, `SELECT v FROM kv WHERE k = ?`, key).Scan(&v)
if errors.Is(err, sql.ErrNoRows) {
return "", nil
}
return v, err
}
// SetKV stores a value.
func (s *Store) SetKV(ctx context.Context, key, value string) error {
_, err := s.exec(ctx, `INSERT INTO kv (k, v) VALUES (?, ?) ON CONFLICT (k) DO UPDATE SET v = excluded.v`, key, value)
return err
}
// --- users, extended -------------------------------------------------------
// SetUserQuality stores a user's default format.
func (s *Store) SetUserQuality(ctx context.Context, userID int64, quality string) error {
_, err := s.exec(ctx, `UPDATE users SET default_quality = ? WHERE id = ?`, quality, userID)
return err
}
// SetUserLang stores the language a user chose, "" to follow Telegram.
func (s *Store) SetUserLang(ctx context.Context, userID int64, lang string) error {
_, err := s.exec(ctx, `UPDATE users SET lang_override = ? WHERE id = ?`, lang, userID)
return err
}
// SetUserBanned bans or unbans a user and reports whether the user exists.
func (s *Store) SetUserBanned(ctx context.Context, userID int64, banned bool) (bool, error) {
n, err := s.exec(ctx, `UPDATE users SET banned = ? WHERE id = ?`, banned, userID)
return n == 1, err
}
// CountUsers counts known users.
func (s *Store) CountUsers(ctx context.Context) (int64, error) {
var n int64
err := s.row(ctx, `SELECT COUNT(*) FROM users`).Scan(&n)
return n, err
}
// UserIDs lists users for a broadcast, in ID order after a cursor.
func (s *Store) UserIDs(ctx context.Context, after int64, limit int) ([]int64, error) {
rows, err := s.rows(ctx, `SELECT id FROM users WHERE id > ? AND banned = ? ORDER BY id LIMIT ?`, after, false, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return nil, err
}
out = append(out, id)
}
return out, rows.Err()
}
// JobCounts counts jobs by status that were created since a time.
func (s *Store) JobCounts(ctx context.Context, since int64) (map[string]int64, error) {
rows, err := s.rows(ctx, `SELECT status, COUNT(*) FROM jobs WHERE created_at >= ? GROUP BY status`, since)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]int64{}
for rows.Next() {
var st string
var n int64
if err := rows.Scan(&st, &n); err != nil {
return nil, err
}
out[st] = n
}
return out, rows.Err()
}
// ActiveJobs lists queued and running jobs in claim order.
func (s *Store) ActiveJobs(ctx context.Context, limit int) ([]*Job, error) {
return scanJobs(s.rows(ctx, `SELECT `+jobCols+` FROM jobs WHERE status IN ('queued', 'running')
ORDER BY CASE status WHEN 'running' THEN 0 ELSE 1 END, `+queueOrder+` LIMIT ?`, limit))
}
// SatsReceived sums paid purchases.
func (s *Store) SatsReceived(ctx context.Context) (int64, error) {
var n sql.NullInt64
err := s.row(ctx, `SELECT SUM(amount_sats) FROM purchases WHERE status = 'paid'`).Scan(&n)
return n.Int64, err
}
+70
View File
@@ -0,0 +1,70 @@
-- +goose Up
-- Groups the bot was added to, recorded from my_chat_member updates.
CREATE TABLE groups (
chat_id BIGINT PRIMARY KEY,
title TEXT NOT NULL DEFAULT '',
type TEXT NOT NULL DEFAULT 'supergroup',
bot_status TEXT NOT NULL DEFAULT 'member',
added_by BIGINT NOT NULL DEFAULT 0,
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL
);
-- Per-group settings, changed by group admins only. A group without a row
-- runs on the defaults.
CREATE TABLE group_settings (
chat_id BIGINT PRIMARY KEY,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
auto_detect BOOLEAN NOT NULL DEFAULT FALSE,
allowed_sites TEXT NOT NULL DEFAULT '',
blocked_sites TEXT NOT NULL DEFAULT '',
who_can_use TEXT NOT NULL DEFAULT 'everyone',
max_size_mb BIGINT NOT NULL DEFAULT 0,
max_duration_s BIGINT NOT NULL DEFAULT 0,
spend_rule TEXT NOT NULL DEFAULT 'admins',
spend_cap_sats BIGINT NOT NULL DEFAULT 0,
daily_cap_sats BIGINT NOT NULL DEFAULT 0,
delete_commands BOOLEAN NOT NULL DEFAULT FALSE,
default_quality TEXT NOT NULL DEFAULT '',
lang TEXT NOT NULL DEFAULT '',
updated_at BIGINT NOT NULL DEFAULT 0
);
-- What each member used in a group per UTC day: for spending caps and for
-- the usage-by-member view.
CREATE TABLE group_usage_daily (
chat_id BIGINT NOT NULL,
user_id BIGINT NOT NULL,
day INTEGER NOT NULL,
downloads INTEGER NOT NULL DEFAULT 0,
sats BIGINT NOT NULL DEFAULT 0,
bytes BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (chat_id, user_id, day)
);
-- Which users were seen in which group, so "my groups" can be listed
-- without asking Telegram about every group.
CREATE TABLE group_users (
chat_id BIGINT NOT NULL,
user_id BIGINT NOT NULL,
last_seen_at BIGINT NOT NULL,
PRIMARY KEY (chat_id, user_id)
);
CREATE INDEX group_users_user_idx ON group_users (user_id);
-- Small key-value store for owner switches such as maintenance mode.
CREATE TABLE kv (
k TEXT PRIMARY KEY,
v TEXT NOT NULL
);
-- A user's default format: "" asks every time.
ALTER TABLE users ADD COLUMN default_quality TEXT NOT NULL DEFAULT '';
-- +goose Down
ALTER TABLE users DROP COLUMN default_quality;
DROP TABLE kv;
DROP TABLE group_users;
DROP TABLE group_usage_daily;
DROP TABLE group_settings;
DROP TABLE groups;
+2
View File
@@ -64,6 +64,8 @@ type User struct {
CreatedAt int64
LastSeenAt int64
ReferredBy int64 // user who invited this one, 0 for none
// Quality is the user's default format, "" to be asked every time.
Quality string
// IsNew is set by UpsertUser when the row was just created.
IsNew bool
}
+2 -2
View File
@@ -2,11 +2,11 @@ package db
import "context"
const userCols = `id, username, first_name, lang, lang_override, banned, created_at, last_seen_at, referred_by`
const userCols = `id, username, first_name, lang, lang_override, banned, created_at, last_seen_at, referred_by, default_quality`
func scanUser(sc interface{ Scan(...any) error }) (*User, error) {
var u User
err := sc.Scan(&u.ID, &u.Username, &u.FirstName, &u.Lang, &u.LangOverride, &u.Banned, &u.CreatedAt, &u.LastSeenAt, &u.ReferredBy)
err := sc.Scan(&u.ID, &u.Username, &u.FirstName, &u.Lang, &u.LangOverride, &u.Banned, &u.CreatedAt, &u.LastSeenAt, &u.ReferredBy, &u.Quality)
if err != nil {
return nil, notFound(err)
}