Files
scrabble-game/platform/telegram/internal/botlink/executor.go
T
Ilia Denisov e71e40eef5
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 19s
CI / ui (pull_request) Successful in 57s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m39s
feat(telegram): promo bot + channel-chat moderation gate
Add a second standalone promo bot to the bot container (answers /start with a
localized message + a URL button into the main bot's Mini App) and gate write
access in a channel's linked discussion chat: grant on join when the Telegram
user is registered and neither admin-suspended nor holding a new chat_muted
role, and revoke/grant on the matching moderation change for a member currently
in the chat.

Eligibility (registered AND NOT suspended AND NOT chat_muted; the game
suspension dominates) is resolved once in the backend and reached two ways: the
bot's join-time unary ResolveChatEligibility over the existing mTLS bot-link,
and a backend chat_access_changed event -> gateway -> ChatGate command
(idempotent; a temporary-block-expiry sweeper may over-emit). The bot guards the
block/unblock path with getChatMember, since bots cannot list members.

A web_app button cannot open another bot's Mini App (it signs initData with the
sending bot's token), so the promo button is a t.me ?startapp URL reusing the
UI's VITE_TELEGRAM_LINK. The bot must be a chat admin with the restrict-members
right and chat_member in its allowed updates.

No schema change: chat_muted reuses the data-driven account_roles table.
2026-06-21 14:46:51 +02:00

134 lines
4.8 KiB
Go

// Package botlink is the bot side of the reverse Telegram channel: the bot dials
// the gateway over mTLS (pkg/proto/botlink/v1), opens one long-lived Link stream,
// and executes the send Commands the gateway pushes, replying with an Ack per
// command. It keeps the Bot API token and egress on the remote bot host with no
// inbound port. See docs/ARCHITECTURE.md.
package botlink
import (
"context"
"fmt"
"strconv"
"go.uber.org/zap"
botlinkv1 "scrabble/pkg/proto/botlink/v1"
telegramv1 "scrabble/pkg/proto/telegram/v1"
"scrabble/platform/telegram/internal/render"
)
// Sender delivers Telegram messages to a chat. *bot.Bot implements it.
type Sender interface {
// Notify sends a notification with a Mini App launch button to chatID.
Notify(ctx context.Context, chatID int64, text, buttonText, startParam string) error
// SendText sends a plain text message to chatID.
SendText(ctx context.Context, chatID int64, text string) error
// ApplyChatGate sets the Telegram user's write access in the moderated discussion
// chat, but only when they are currently in it; it reports whether a restriction
// was applied.
ApplyChatGate(ctx context.Context, userID int64, allow bool) (bool, error)
}
// Executor turns a bot-link Command into a Bot API send. The delivered flag mirrors
// the former connector semantics (false when the kind is not rendered out-of-app,
// the user never started the bot, or no channel is configured); a returned error is
// an unexpected or malformed failure carried back in the Ack error field, distinct
// from a clean not-delivered.
type Executor struct {
sender Sender
channelID int64
log *zap.Logger
}
// NewExecutor builds the executor over a bot sender and the optional game channel.
func NewExecutor(sender Sender, channelID int64, log *zap.Logger) *Executor {
if log == nil {
log = zap.NewNop()
}
return &Executor{sender: sender, channelID: channelID, log: log}
}
// Handle dispatches one command to the matching Bot API send.
func (e *Executor) Handle(ctx context.Context, cmd *botlinkv1.Command) (bool, error) {
switch p := cmd.GetPayload().(type) {
case *botlinkv1.Command_Notify:
return e.notify(ctx, p.Notify)
case *botlinkv1.Command_SendToUser:
return e.sendToUser(ctx, p.SendToUser)
case *botlinkv1.Command_SendToChannel:
return e.sendToChannel(ctx, p.SendToChannel)
case *botlinkv1.Command_ChatGate:
return e.chatGate(ctx, p.ChatGate)
default:
return false, fmt.Errorf("botlink: empty command")
}
}
// chatGate applies a chat-gate command: it parses the target Telegram user id and
// sets their write access in the moderated chat (a no-op when they are not in it). A
// Bot API failure is logged and reported as not-delivered, not a hard error.
func (e *Executor) chatGate(ctx context.Context, req *botlinkv1.ChatGateCommand) (bool, error) {
userID, err := parseChatID(req.GetExternalId())
if err != nil {
return false, err
}
applied, err := e.sender.ApplyChatGate(ctx, userID, req.GetAllow())
if err != nil {
e.log.Warn("chat gate apply failed",
zap.String("external_id", req.GetExternalId()), zap.Bool("allow", req.GetAllow()), zap.Error(err))
return false, nil
}
return applied, nil
}
// notify renders an out-of-app push and sends it with a Mini App launch button.
func (e *Executor) notify(ctx context.Context, req *telegramv1.NotifyRequest) (bool, error) {
msg, ok := render.Render(req.GetKind(), req.GetPayload(), req.GetLanguage())
if !ok {
return false, nil
}
chat, err := parseChatID(req.GetExternalId())
if err != nil {
return false, err
}
if err := e.sender.Notify(ctx, chat, msg.Text, msg.ButtonText, msg.StartParam); err != nil {
e.log.Warn("notify delivery failed", zap.String("kind", req.GetKind()), zap.Error(err))
return false, nil
}
return true, nil
}
// sendToUser sends an admin text message to one user.
func (e *Executor) sendToUser(ctx context.Context, req *telegramv1.SendToUserRequest) (bool, error) {
chat, err := parseChatID(req.GetExternalId())
if err != nil {
return false, err
}
if err := e.sender.SendText(ctx, chat, req.GetText()); err != nil {
e.log.Warn("send to user failed", zap.Error(err))
return false, nil
}
return true, nil
}
// sendToChannel posts an admin text message to the bot's game channel.
func (e *Executor) sendToChannel(ctx context.Context, req *telegramv1.SendToGameChannelRequest) (bool, error) {
if e.channelID == 0 {
return false, fmt.Errorf("botlink: game channel is not configured")
}
if err := e.sender.SendText(ctx, e.channelID, req.GetText()); err != nil {
e.log.Warn("send to channel failed", zap.Error(err))
return false, nil
}
return true, nil
}
// parseChatID converts a Telegram identity external_id into a numeric chat id.
func parseChatID(externalID string) (int64, error) {
id, err := strconv.ParseInt(externalID, 10, 64)
if err != nil {
return 0, fmt.Errorf("invalid external_id %q", externalID)
}
return id, nil
}