feat(telegram): bot support relay — per-user forum topics
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 12s
CI / integration (pull_request) Successful in 16s
CI / ui (pull_request) Successful in 56s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m20s

Users who DM the bot anything but /start are relayed into a private
forum supergroup, one topic per user. Operators (the chat's admins)
reply in the topic and the bot copies it back to the user; an info card
opening each topic carries a Block/Unblock toggle and a Clear button.
State is a small JSON file on a new /data volume — the bot host has no
database. Off by default (TELEGRAM_SUPPORT_CHAT_ID=0): the prod bot is
unchanged until the operator sets the chat id and adds the bot as a
forum admin.

- internal/support: concurrency-safe JSON store (topic map, block list,
  relayed message ids) with field-targeted mutators and atomic save
- bot/support.go: relay both ways via copyMessage, short-TTL admin
  cache, callback buttons, per-user topic-create lock, loop guard
  (skip the bot's own posts), reopen a deleted topic on the next message
- config + compose + CI/prod-deploy: TELEGRAM_SUPPORT_CHAT_ID per
  contour + TELEGRAM_SUPPORT_STATE_DIR; bot-state named volume; /data
  pre-owned by UID 65532 so a fresh volume is writable under distroless
- docs: ARCHITECTURE §15 + decision record, FUNCTIONAL (+ru), README
This commit is contained in:
Ilia Denisov
2026-06-23 17:47:00 +02:00
parent e6277dcd43
commit 6a602aefae
18 changed files with 1465 additions and 7 deletions
+61 -7
View File
@@ -15,6 +15,8 @@ import (
"github.com/go-telegram/bot/models"
"go.uber.org/zap"
"golang.org/x/time/rate"
"scrabble/platform/telegram/internal/support"
)
// Config configures the bot wrapper.
@@ -39,6 +41,14 @@ type Config struct {
// GameChannelID is the game channel whose public @username the /start welcome links
// to (resolved from this id via getChat at startup); 0 omits that follow link.
GameChannelID int64
// SupportChatID is the private forum supergroup the bot relays direct user messages
// into (one topic per user) and reads operator replies from; 0 disables the support
// relay. The bot must be an administrator there with the manage-topics and
// delete-messages rights.
SupportChatID int64
// SupportStore persists the support relay's state (topic mapping, block list,
// relayed message ids); required when SupportChatID is set, ignored otherwise.
SupportStore *support.Store
}
// EligibilityResolver answers whether the Telegram user identified by externalID
@@ -66,11 +76,21 @@ type Bot struct {
channelUsername string
chatUsername string
// botID is the bot's own Telegram user id (resolved at startup); it skips the
// chat_member updates the bot's own restrict actions generate — the grant loop guard.
// chat_member updates the bot's own restrict actions generate — the grant loop guard
// and the bot's own relayed copies in the support chat.
botID int64
// eligibility resolves a joining user's chat write eligibility; nil leaves a
// joiner muted (fail-closed) until it is wired.
eligibility EligibilityResolver
// supportChatID is the support relay's forum supergroup (0 disables the relay).
supportChatID int64
// support persists the support relay's per-user state; nil when the relay is off.
support *support.Store
// supportLocks serialises per-user topic creation so a burst of a new user's
// messages opens exactly one topic.
supportLocks *keyedMutex
// admins caches the support chat's administrator ids (who may reply and act).
admins *adminCache
}
// New builds the bot wrapper, registering the /start handler and a default handler
@@ -80,7 +100,14 @@ func New(cfg Config, log *zap.Logger) (*Bot, error) {
if log == nil {
log = zap.NewNop()
}
t := &Bot{miniAppURL: cfg.MiniAppURL, log: log, chatID: cfg.ChatID, channelID: cfg.GameChannelID}
t := &Bot{
miniAppURL: cfg.MiniAppURL,
log: log,
chatID: cfg.ChatID,
channelID: cfg.GameChannelID,
supportChatID: cfg.SupportChatID,
support: cfg.SupportStore,
}
if cfg.SendRatePerSecond > 0 {
t.limiter = rate.NewLimiter(rate.Limit(cfg.SendRatePerSecond), cfg.SendRatePerSecond)
}
@@ -89,15 +116,26 @@ func New(cfg Config, log *zap.Logger) (*Bot, error) {
tgbot.WithDefaultHandler(t.handleUpdate),
tgbot.WithMessageTextHandler("/start", tgbot.MatchTypePrefix, t.handleStart),
}
if t.supportEnabled() {
t.supportLocks = newKeyedMutex()
t.admins = &adminCache{}
// The info-card buttons are callback_query updates; route them to the support
// callback handler by their "sup:" data prefix.
opts = append(opts, tgbot.WithCallbackQueryDataHandler(supportCallbackPrefix, tgbot.MatchTypePrefix, t.handleSupportCallback))
}
// Allowed updates default to "all except chat_member". Specify an explicit set only
// when we need chat_member (moderated chat) — and then re-add callback_query (which
// the explicit set would otherwise drop) when the support relay needs it.
if cfg.ChatID != 0 {
// chat_member updates are off by default; subscribe explicitly (alongside
// messages) so the bot sees joins in the moderated chat. The bot must also be an
// administrator there for Telegram to deliver them.
opts = append(opts, tgbot.WithAllowedUpdates(tgbot.AllowedUpdates{
allowed := tgbot.AllowedUpdates{
models.AllowedUpdateMessage,
models.AllowedUpdateMyChatMember,
models.AllowedUpdateChatMember,
}))
}
if t.supportEnabled() {
allowed = append(allowed, models.AllowedUpdateCallbackQuery)
}
opts = append(opts, tgbot.WithAllowedUpdates(allowed))
}
if cfg.TestEnv {
// Route to the Bot API test environment (.../bot<token>/test/METHOD).
@@ -134,6 +172,9 @@ func (t *Bot) Run(ctx context.Context) {
if t.chatID != 0 {
t.logChatAdminStatus(ctx)
}
if t.supportEnabled() {
t.initSupport(ctx)
}
t.resolveWelcomeHandles(ctx)
t.api.Start(ctx)
}
@@ -305,6 +346,19 @@ func (t *Bot) handleUpdate(ctx context.Context, api *tgbot.Bot, update *models.U
t.handleChatMember(ctx, update.ChatMember)
return
}
// Support relay (when enabled): a non-/start message — /start has its own handler —
// is either an operator's reply in the support chat or a user's direct message to
// relay. Everything else falls through to the Mini App launch reply.
if t.supportEnabled() && update.Message != nil {
switch {
case update.Message.Chat.ID == t.supportChatID:
t.handleSupportGroupMessage(ctx, update.Message)
return
case update.Message.Chat.Type == models.ChatTypePrivate:
t.handleSupportUserMessage(ctx, update.Message)
return
}
}
t.handleStart(ctx, api, update)
}