Files
scrabble-game/platform/telegram/internal/bot/bot.go
T
Ilia Denisov 6aeb529f13
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 15s
CI / ui (pull_request) Successful in 53s
CI / gate (pull_request) Successful in 1s
CI / deploy (pull_request) Failing after 2m6s
feat(telegram): split connector into home validator + remote bot
Move all Telegram egress off the main host. The single connector held the
bot token, long-polled Telegram and answered the gateway/backend over the
trusted internal network, so the whole component (including login validation)
shared fate with its VPN sidecar. Split it into two binaries that share the
token:

- cmd/validator (home, no VPN): Mini App initData + Login Widget HMAC only,
  never calls the Bot API. The gateway dials it for Telegram auth, so game
  login is now independent of Telegram reachability.
- cmd/bot (remote): Bot API long-poll + sendMessage, the only component
  reaching Telegram. It holds no inbound port — it dials the gateway over a
  new reverse mTLS bot-link (pkg/proto/botlink/v1) and executes the send
  commands the gateway pushes.

The gateway funnels sends to the bot-link: out-of-app push is fire-and-forget
(at-most-once, dropped if no bot is connected); the backend admin broadcasts
reach a gateway-served relay that forwards them and awaits the bot's ack
(SendToUser/SendToGameChannel contract preserved). mTLS (pkg/mtls) is the one
inter-service link that leaves the trusted segment; validator<->gateway and
the relay stay plaintext internal. The bot is Telegram-rate-limited.

One bot now; the gateway bot registry, an owns_updates flag and per-command
ids leave seams for N later. Webhook rejected (one URL per token, adds inbound
+ a static address).

The unified test contour runs the split (the bot keeps its VPN sidecar and
dials the gateway by its internal name; bot-link certs from deploy/gen-certs.sh,
generated in CI). The prod wiring — the bot on a separate host (no VPN), the
gateway bot-link port published, PROD_ certs with scheduled rotation, an SSH
deploy of both hosts together — is the deferred final stage (PRERELEASE.md TX,
Stage 18).

Docs: ARCHITECTURE, PRERELEASE (phase TX), platform/telegram + gateway +
backend + deploy READMEs, FUNCTIONAL(+ru), CLAUDE.md, .env.example.
2026-06-21 00:19:07 +02:00

179 lines
5.6 KiB
Go

// Package bot wraps the Telegram Bot API client (github.com/go-telegram/bot): it
// runs the long-poll update loop — replying to /start (with an optional deep-link
// payload) and any other message with a Mini App launch button — and sends the
// notification and admin messages the connector requests. The bot token lives only
// in this process.
package bot
import (
"context"
"net/url"
"strings"
tgbot "github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
"go.uber.org/zap"
"golang.org/x/time/rate"
)
// Config configures the bot wrapper.
type Config struct {
// Token is the Bot API token.
Token string
// APIBaseURL overrides the Bot API host ("" uses https://api.telegram.org).
APIBaseURL string
// TestEnv routes requests to the Bot API test environment.
TestEnv bool
// MiniAppURL is the base URL of the Mini App launch button.
MiniAppURL string
// SendRatePerSecond caps outbound sends (Notify and SendText) to respect the
// Telegram Bot API flood limits; 0 disables the limiter. The burst equals the
// per-second rate.
SendRatePerSecond int
}
// Bot wraps a Telegram Bot API client and the Mini App launch URL.
type Bot struct {
api *tgbot.Bot
miniAppURL string
log *zap.Logger
// limiter throttles outbound sends to stay under the Bot API flood limits; nil
// disables throttling.
limiter *rate.Limiter
}
// New builds the bot wrapper, registering the /start handler and a default handler
// that both reply with a Mini App launch button. It does not start polling; call
// Run for that.
func New(cfg Config, log *zap.Logger) (*Bot, error) {
if log == nil {
log = zap.NewNop()
}
t := &Bot{miniAppURL: cfg.MiniAppURL, log: log}
if cfg.SendRatePerSecond > 0 {
t.limiter = rate.NewLimiter(rate.Limit(cfg.SendRatePerSecond), cfg.SendRatePerSecond)
}
opts := []tgbot.Option{
tgbot.WithDefaultHandler(t.handleStart),
tgbot.WithMessageTextHandler("/start", tgbot.MatchTypePrefix, t.handleStart),
}
if cfg.TestEnv {
// Route to the Bot API test environment (.../bot<token>/test/METHOD).
opts = append(opts, tgbot.UseTestEnvironment())
}
if cfg.APIBaseURL != "" {
opts = append(opts, tgbot.WithServerURL(cfg.APIBaseURL))
}
api, err := tgbot.New(cfg.Token, opts...)
if err != nil {
return nil, err
}
t.api = api
return t, nil
}
// Run sets the bot commands and the Mini App menu button, then blocks on the
// long-poll update loop until ctx is cancelled.
func (t *Bot) Run(ctx context.Context) {
if _, err := t.api.SetMyCommands(ctx, &tgbot.SetMyCommandsParams{
Commands: []models.BotCommand{{Command: "start", Description: "Open Scrabble"}},
}); err != nil {
t.log.Warn("set commands failed", zap.Error(err))
}
if _, err := t.api.SetChatMenuButton(ctx, &tgbot.SetChatMenuButtonParams{
MenuButton: models.MenuButtonWebApp{
Type: models.MenuButtonTypeWebApp,
Text: "Play",
WebApp: models.WebAppInfo{URL: t.miniAppURL},
},
}); err != nil {
t.log.Warn("set menu button failed", zap.Error(err))
}
t.api.Start(ctx)
}
// Notify sends a notification message with a Mini App launch button that opens the
// app at startParam (empty opens the lobby).
func (t *Bot) Notify(ctx context.Context, chatID int64, text, buttonText, startParam string) error {
if err := t.throttle(ctx); err != nil {
return err
}
_, err := t.api.SendMessage(ctx, &tgbot.SendMessageParams{
ChatID: chatID,
Text: text,
ReplyMarkup: t.launchMarkup(buttonText, startParam),
})
return err
}
// SendText sends a plain text message with no markup (admin use).
func (t *Bot) SendText(ctx context.Context, chatID int64, text string) error {
if err := t.throttle(ctx); err != nil {
return err
}
_, err := t.api.SendMessage(ctx, &tgbot.SendMessageParams{ChatID: chatID, Text: text})
return err
}
// throttle blocks until the rate limiter admits one send, or ctx is cancelled. It
// is a no-op when no limiter is configured.
func (t *Bot) throttle(ctx context.Context) error {
if t.limiter == nil {
return nil
}
return t.limiter.Wait(ctx)
}
// handleStart replies to /start (with an optional deep-link payload) and to any
// other message with a Mini App launch button.
func (t *Bot) handleStart(ctx context.Context, api *tgbot.Bot, update *models.Update) {
if update.Message == nil {
return
}
startParam := startPayload(update.Message.Text)
if _, err := api.SendMessage(ctx, &tgbot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Tap to open Scrabble.",
ReplyMarkup: t.launchMarkup("Open Scrabble", startParam),
}); err != nil {
t.log.Warn("reply to start failed", zap.Error(err))
}
}
// launchMarkup builds the single-button inline keyboard that opens the Mini App at
// startParam.
func (t *Bot) launchMarkup(buttonText, startParam string) *models.InlineKeyboardMarkup {
return &models.InlineKeyboardMarkup{
InlineKeyboard: [][]models.InlineKeyboardButton{{
{Text: buttonText, WebApp: &models.WebAppInfo{URL: t.launchURL(startParam)}},
}},
}
}
// launchURL appends the deep-link start parameter to the Mini App URL as a startapp
// query parameter; an empty parameter returns the base URL unchanged.
func (t *Bot) launchURL(startParam string) string {
if startParam == "" {
return t.miniAppURL
}
u, err := url.Parse(t.miniAppURL)
if err != nil {
return t.miniAppURL
}
q := u.Query()
q.Set("startapp", startParam)
u.RawQuery = q.Encode()
return u.String()
}
// startPayload extracts the deep-link payload from a "/start <payload>" command;
// any other text yields an empty payload (open the lobby).
func startPayload(text string) string {
const cmd = "/start"
if !strings.HasPrefix(text, cmd) {
return ""
}
return strings.TrimSpace(strings.TrimPrefix(text, cmd))
}