feat(telegram): promo bot + channel-chat moderation gate
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

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.
This commit is contained in:
Ilia Denisov
2026-06-21 14:46:51 +02:00
parent 41d21f3f6f
commit e71e40eef5
42 changed files with 2082 additions and 68 deletions
+156 -2
View File
@@ -8,6 +8,7 @@ package bot
import (
"context"
"net/url"
"strconv"
"strings"
tgbot "github.com/go-telegram/bot"
@@ -30,8 +31,19 @@ type Config struct {
// Telegram Bot API flood limits; 0 disables the limiter. The burst equals the
// per-second rate.
SendRatePerSecond int
// ChatID is the moderated discussion chat the bot gates write access in; 0
// disables chat gating (and the chat_member long-poll subscription). Gating needs
// the bot to be an administrator there with the restrict-members right.
ChatID int64
}
// EligibilityResolver answers whether the Telegram user identified by externalID
// (the decimal user id) may write in the moderated chat: registered and neither
// admin-suspended nor chat-muted. The bot calls it when a user joins the chat. It is
// late-bound (SetEligibilityResolver) because it is backed by the bot-link client,
// which is built after the bot.
type EligibilityResolver func(ctx context.Context, externalID string) (eligible bool, err error)
// Bot wraps a Telegram Bot API client and the Mini App launch URL.
type Bot struct {
api *tgbot.Bot
@@ -40,6 +52,11 @@ type Bot struct {
// limiter throttles outbound sends to stay under the Bot API flood limits; nil
// disables throttling.
limiter *rate.Limiter
// chatID is the moderated discussion chat (0 disables gating).
chatID int64
// eligibility resolves a joining user's chat write eligibility; nil leaves a
// joiner muted (fail-closed) until it is wired.
eligibility EligibilityResolver
}
// New builds the bot wrapper, registering the /start handler and a default handler
@@ -49,15 +66,25 @@ func New(cfg Config, log *zap.Logger) (*Bot, error) {
if log == nil {
log = zap.NewNop()
}
t := &Bot{miniAppURL: cfg.MiniAppURL, log: log}
t := &Bot{miniAppURL: cfg.MiniAppURL, log: log, chatID: cfg.ChatID}
if cfg.SendRatePerSecond > 0 {
t.limiter = rate.NewLimiter(rate.Limit(cfg.SendRatePerSecond), cfg.SendRatePerSecond)
}
opts := []tgbot.Option{
tgbot.WithDefaultHandler(t.handleStart),
tgbot.WithDefaultHandler(t.handleUpdate),
tgbot.WithMessageTextHandler("/start", tgbot.MatchTypePrefix, t.handleStart),
}
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{
models.AllowedUpdateMessage,
models.AllowedUpdateMyChatMember,
models.AllowedUpdateChatMember,
}))
}
if cfg.TestEnv {
// Route to the Bot API test environment (.../bot<token>/test/METHOD).
opts = append(opts, tgbot.UseTestEnvironment())
@@ -176,3 +203,130 @@ func startPayload(text string) string {
}
return strings.TrimSpace(strings.TrimPrefix(text, cmd))
}
// handleUpdate is the default-handler dispatcher: a chat-member change in the
// moderated chat drives the write-access gate; anything else is treated as a message
// and gets the Mini App launch reply.
func (t *Bot) handleUpdate(ctx context.Context, api *tgbot.Bot, update *models.Update) {
if update.ChatMember != nil {
t.handleChatMember(ctx, update.ChatMember)
return
}
t.handleStart(ctx, api, update)
}
// SetEligibilityResolver wires the chat-eligibility resolver after construction (the
// bot-link client backing it is built after the bot).
func (t *Bot) SetEligibilityResolver(resolve EligibilityResolver) {
t.eligibility = resolve
}
// handleChatMember grants write access to a user who joins the moderated chat when
// they are registered and not blocked. A non-eligible joiner is left muted (the chat
// defaults to no-send), and a resolve failure fails closed (also left muted). Other
// status changes (leaves, restrictions, admin edits) are ignored.
func (t *Bot) handleChatMember(ctx context.Context, cm *models.ChatMemberUpdated) {
if t.chatID == 0 || cm.Chat.ID != t.chatID {
return
}
// Only a transition into plain membership is a join to evaluate.
if cm.NewChatMember.Type != models.ChatMemberTypeMember || cm.OldChatMember.Type == models.ChatMemberTypeMember {
return
}
user := chatMemberUser(cm.NewChatMember)
if user == nil || user.IsBot {
return
}
if t.eligibility == nil {
return // resolver not wired: leave muted (fail closed)
}
eligible, err := t.eligibility(ctx, strconv.FormatInt(user.ID, 10))
if err != nil {
t.log.Warn("chat join eligibility failed", zap.Int64("user_id", user.ID), zap.Error(err))
return
}
if !eligible {
return // not registered or blocked: leave muted
}
if err := t.setChatWrite(ctx, user.ID, true); err != nil {
t.log.Warn("grant chat write failed", zap.Int64("user_id", user.ID), zap.Error(err))
}
}
// ApplyChatGate applies a chat-gate command (an admin block/unblock or chat_muted
// change relayed by the gateway): it sets the user's write access, but only when they
// are currently in the chat. Bots cannot list members, so it probes the single user
// with getChatMember and is a no-op when they are absent (left/kicked) or an
// administrator (who cannot be restricted). It reports whether a restriction was
// applied.
func (t *Bot) ApplyChatGate(ctx context.Context, userID int64, allow bool) (bool, error) {
if t.chatID == 0 {
return false, nil
}
member, err := t.api.GetChatMember(ctx, &tgbot.GetChatMemberParams{ChatID: t.chatID, UserID: userID})
if err != nil {
return false, err
}
switch member.Type {
case models.ChatMemberTypeMember, models.ChatMemberTypeRestricted:
if err := t.setChatWrite(ctx, userID, allow); err != nil {
return false, err
}
return true, nil
default:
return false, nil // absent, or an admin/owner who cannot be restricted
}
}
// setChatWrite restricts the user in the moderated chat to either the full send
// permission set (allow) or none (mute); the non-send permissions stay at their
// default-deny either way.
func (t *Bot) setChatWrite(ctx context.Context, userID int64, allow bool) error {
perms := models.ChatPermissions{}
if allow {
perms = chatWritePerms()
}
_, err := t.api.RestrictChatMember(ctx, &tgbot.RestrictChatMemberParams{
ChatID: t.chatID,
UserID: userID,
Permissions: &perms,
})
return err
}
// chatWritePerms grants a member the ability to send every kind of message; the
// non-send permissions stay denied.
func chatWritePerms() models.ChatPermissions {
return models.ChatPermissions{
CanSendMessages: true,
CanSendAudios: true,
CanSendDocuments: true,
CanSendPhotos: true,
CanSendVideos: true,
CanSendVideoNotes: true,
CanSendVoiceNotes: true,
CanSendPolls: true,
CanSendOtherMessages: true,
CanAddWebPagePreviews: true,
}
}
// chatMemberUser returns the user a ChatMember refers to across the union variants,
// or nil for an unrecognised type.
func chatMemberUser(m models.ChatMember) *models.User {
switch m.Type {
case models.ChatMemberTypeOwner:
return m.Owner.User
case models.ChatMemberTypeAdministrator:
return &m.Administrator.User
case models.ChatMemberTypeMember:
return m.Member.User
case models.ChatMemberTypeRestricted:
return m.Restricted.User
case models.ChatMemberTypeLeft:
return m.Left.User
case models.ChatMemberTypeBanned:
return m.Banned.User
}
return nil
}
+165
View File
@@ -0,0 +1,165 @@
package bot
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/go-telegram/bot/models"
"go.uber.org/zap"
)
const testChatID = 555
// chatAPI is a fake Bot API for the chat-gating tests: it answers getMe, returns a
// scripted getChatMember status, and records restrictChatMember calls.
type chatAPI struct {
memberStatus string // the status getChatMember reports (default "left")
restricts []restrictCall
}
type restrictCall struct {
userID string
canSend bool // can_send_messages in the applied permissions
}
func (a *chatAPI) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, "/getMe"):
io.WriteString(w, `{"ok":true,"result":{"id":1,"is_bot":true,"first_name":"t","username":"tb"}}`)
case strings.HasSuffix(r.URL.Path, "/getChatMember"):
status := a.memberStatus
if status == "" {
status = "left"
}
io.WriteString(w, `{"ok":true,"result":{"status":"`+status+`","user":{"id":`+r.FormValue("user_id")+`,"is_bot":false,"first_name":"u"}}}`)
case strings.HasSuffix(r.URL.Path, "/restrictChatMember"):
var perms struct {
CanSendMessages bool `json:"can_send_messages"`
}
_ = json.Unmarshal([]byte(r.FormValue("permissions")), &perms)
a.restricts = append(a.restricts, restrictCall{userID: r.FormValue("user_id"), canSend: perms.CanSendMessages})
io.WriteString(w, `{"ok":true,"result":true}`)
default:
io.WriteString(w, `{"ok":true,"result":true}`)
}
}
// newChatBot builds a gating bot (ChatID set) over the fake API, without an
// eligibility resolver — each test wires the one it needs.
func newChatBot(t *testing.T, api *chatAPI) *Bot {
t.Helper()
srv := httptest.NewServer(api)
t.Cleanup(srv.Close)
b, err := New(Config{Token: "123:ABC", APIBaseURL: srv.URL, MiniAppURL: "https://example.com/", ChatID: testChatID}, zap.NewNop())
if err != nil {
t.Fatalf("new bot: %v", err)
}
return b
}
// chatMemberUpdate builds a status transition oldType -> member for userID in chatID.
func chatMemberUpdate(chatID, userID int64, oldType models.ChatMemberType) *models.ChatMemberUpdated {
return &models.ChatMemberUpdated{
Chat: models.Chat{ID: chatID},
OldChatMember: models.ChatMember{Type: oldType, Left: &models.ChatMemberLeft{User: &models.User{ID: userID}}},
NewChatMember: models.ChatMember{Type: models.ChatMemberTypeMember, Member: &models.ChatMemberMember{User: &models.User{ID: userID}}},
}
}
func TestHandleChatMemberGrantsEligibleJoin(t *testing.T) {
api := &chatAPI{}
b := newChatBot(t, api)
b.SetEligibilityResolver(func(context.Context, string) (bool, error) { return true, nil })
b.handleChatMember(context.Background(), chatMemberUpdate(testChatID, 777, models.ChatMemberTypeLeft))
if len(api.restricts) != 1 || api.restricts[0].userID != "777" || !api.restricts[0].canSend {
t.Fatalf("restricts = %+v, want one grant (can_send=true) for 777", api.restricts)
}
}
func TestHandleChatMemberSkipsIneligibleJoin(t *testing.T) {
api := &chatAPI{}
b := newChatBot(t, api)
b.SetEligibilityResolver(func(context.Context, string) (bool, error) { return false, nil })
b.handleChatMember(context.Background(), chatMemberUpdate(testChatID, 777, models.ChatMemberTypeLeft))
if len(api.restricts) != 0 {
t.Fatalf("an ineligible joiner was restricted: %+v (want left muted, no call)", api.restricts)
}
}
func TestHandleChatMemberFailsClosedOnResolveError(t *testing.T) {
api := &chatAPI{}
b := newChatBot(t, api)
b.SetEligibilityResolver(func(context.Context, string) (bool, error) { return true, context.DeadlineExceeded })
b.handleChatMember(context.Background(), chatMemberUpdate(testChatID, 777, models.ChatMemberTypeLeft))
if len(api.restricts) != 0 {
t.Fatalf("a resolve error still granted write: %+v (want fail-closed)", api.restricts)
}
}
func TestHandleChatMemberIgnoresOtherChatAndNonJoins(t *testing.T) {
api := &chatAPI{}
b := newChatBot(t, api)
b.SetEligibilityResolver(func(context.Context, string) (bool, error) { return true, nil })
ctx := context.Background()
// A different chat is ignored.
b.handleChatMember(ctx, chatMemberUpdate(999, 777, models.ChatMemberTypeLeft))
// A non-join transition (already a member) is ignored.
b.handleChatMember(ctx, chatMemberUpdate(testChatID, 777, models.ChatMemberTypeMember))
if len(api.restricts) != 0 {
t.Fatalf("restricts = %+v, want none for a foreign chat / non-join", api.restricts)
}
}
func TestApplyChatGatePresentMember(t *testing.T) {
for _, tc := range []struct {
name string
allow bool
}{{"grant", true}, {"mute", false}} {
t.Run(tc.name, func(t *testing.T) {
api := &chatAPI{memberStatus: "member"}
b := newChatBot(t, api)
applied, err := b.ApplyChatGate(context.Background(), 777, tc.allow)
if err != nil {
t.Fatalf("apply: %v", err)
}
if !applied {
t.Fatal("applied = false, want true for a present member")
}
if len(api.restricts) != 1 || api.restricts[0].canSend != tc.allow {
t.Fatalf("restricts = %+v, want one with can_send=%v", api.restricts, tc.allow)
}
})
}
}
func TestApplyChatGateSkipsAbsentAndAdmin(t *testing.T) {
for _, status := range []string{"left", "kicked", "administrator", "creator"} {
t.Run(status, func(t *testing.T) {
api := &chatAPI{memberStatus: status}
b := newChatBot(t, api)
applied, err := b.ApplyChatGate(context.Background(), 777, false)
if err != nil {
t.Fatalf("apply: %v", err)
}
if applied {
t.Errorf("applied = true for status %q, want a no-op", status)
}
if len(api.restricts) != 0 {
t.Errorf("restricts = %+v for status %q, want none", api.restricts, status)
}
})
}
}
+34 -19
View File
@@ -37,27 +37,25 @@ type ClientConfig struct {
}
// Client maintains the long-lived bot-link to the gateway, executing the commands
// it receives and re-dialing after any break.
// it receives and re-dialing after any break. The same mTLS connection also serves
// the unary chat-eligibility query the bot makes on a chat join.
type Client struct {
cfg ClientConfig
exec *Executor
log *zap.Logger
cfg ClientConfig
exec *Executor
log *zap.Logger
conn *grpc.ClientConn
client botlinkv1.BotLinkClient
}
// NewClient builds the bot-link client over the executor.
func NewClient(cfg ClientConfig, exec *Executor, log *zap.Logger) *Client {
// NewClient builds the bot-link client over the executor, dialing the gateway. The
// gRPC connection is lazy, so the dial does not block on the gateway being up; the
// caller must Close it. The bot-link command stream is opened by Run.
func NewClient(cfg ClientConfig, exec *Executor, log *zap.Logger) (*Client, error) {
if log == nil {
log = zap.NewNop()
}
return &Client{cfg: cfg, exec: exec, log: log}
}
// Run dials the gateway and keeps the bot-link open, re-dialing after each break,
// until ctx is cancelled. The gRPC connection auto-reconnects the transport; this
// loop re-opens the Link stream on top of it.
func (c *Client) Run(ctx context.Context) error {
conn, err := grpc.NewClient(c.cfg.GatewayAddr,
grpc.WithTransportCredentials(c.cfg.Creds),
conn, err := grpc.NewClient(cfg.GatewayAddr,
grpc.WithTransportCredentials(cfg.Creds),
grpc.WithStatsHandler(otelgrpc.NewClientHandler()),
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: clientKeepaliveTime,
@@ -66,13 +64,30 @@ func (c *Client) Run(ctx context.Context) error {
}),
)
if err != nil {
return err
return nil, err
}
defer func() { _ = conn.Close() }()
client := botlinkv1.NewBotLinkClient(conn)
return &Client{cfg: cfg, exec: exec, log: log, conn: conn, client: botlinkv1.NewBotLinkClient(conn)}, nil
}
// Close releases the bot-link connection.
func (c *Client) Close() error { return c.conn.Close() }
// ResolveChatEligibility asks the gateway whether the Telegram user identified by
// externalID may write in the moderated chat. The bot calls it on a chat join, over
// the same mTLS connection as the command stream.
func (c *Client) ResolveChatEligibility(ctx context.Context, externalID string) (bool, error) {
resp, err := c.client.ResolveChatEligibility(ctx, &botlinkv1.ChatEligibilityRequest{ExternalId: externalID})
if err != nil {
return false, err
}
return resp.GetEligible(), nil
}
// Run keeps the bot-link command stream open, re-opening it after each break, until
// ctx is cancelled. The gRPC connection auto-reconnects the transport underneath.
func (c *Client) Run(ctx context.Context) error {
for ctx.Err() == nil {
if err := c.serve(ctx, client); err != nil && ctx.Err() == nil {
if err := c.serve(ctx, c.client); err != nil && ctx.Err() == nil {
c.log.Warn("bot-link stream ended", zap.Error(err))
}
if !sleep(ctx, c.cfg.ReconnectDelay) {
@@ -63,12 +63,16 @@ func TestClientServesCommands(t *testing.T) {
t.Cleanup(srv.Stop)
sender := &fakeSender{}
client := NewClient(ClientConfig{
client, err := NewClient(ClientConfig{
GatewayAddr: lis.Addr().String(),
InstanceID: "test",
Creds: insecure.NewCredentials(),
ReconnectDelay: 50 * time.Millisecond,
}, NewExecutor(sender, 0, nil), nil)
if err != nil {
t.Fatalf("new client: %v", err)
}
t.Cleanup(func() { _ = client.Close() })
go func() { _ = client.Run(t.Context()) }()
@@ -23,6 +23,10 @@ type Sender interface {
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
@@ -53,11 +57,30 @@ func (e *Executor) Handle(ctx context.Context, cmd *botlinkv1.Command) (bool, er
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())
@@ -13,9 +13,11 @@ import (
// fakeSender records the delivery calls the executor makes.
type fakeSender struct {
notify []notifyCall
text []textCall
err error
notify []notifyCall
text []textCall
gate []gateCall
applied bool // ApplyChatGate's reported result
err error
}
type notifyCall struct {
@@ -26,6 +28,10 @@ type textCall struct {
chatID int64
text string
}
type gateCall struct {
userID int64
allow bool
}
func (f *fakeSender) Notify(_ context.Context, chatID int64, text, buttonText, startParam string) error {
f.notify = append(f.notify, notifyCall{chatID, text, buttonText, startParam})
@@ -37,6 +43,11 @@ func (f *fakeSender) SendText(_ context.Context, chatID int64, text string) erro
return f.err
}
func (f *fakeSender) ApplyChatGate(_ context.Context, userID int64, allow bool) (bool, error) {
f.gate = append(f.gate, gateCall{userID, allow})
return f.applied, f.err
}
func yourTurnPayload(gameID string) []byte {
b := flatbuffers.NewBuilder(0)
gid := b.CreateString(gameID)
@@ -106,6 +117,46 @@ func TestExecutorSendToUser(t *testing.T) {
}
}
func chatGateCmd(externalID string, allow bool) *botlinkv1.Command {
return &botlinkv1.Command{Payload: &botlinkv1.Command_ChatGate{ChatGate: &botlinkv1.ChatGateCommand{
ExternalId: externalID, Allow: allow,
}}}
}
func TestExecutorChatGateApplied(t *testing.T) {
sender := &fakeSender{applied: true}
exec := NewExecutor(sender, 0, nil)
delivered, err := exec.Handle(context.Background(), chatGateCmd("777", true))
if err != nil {
t.Fatalf("handle: %v", err)
}
if !delivered || len(sender.gate) != 1 || sender.gate[0].userID != 777 || !sender.gate[0].allow {
t.Errorf("chat gate = %v / calls %+v", delivered, sender.gate)
}
}
func TestExecutorChatGateNotInChat(t *testing.T) {
sender := &fakeSender{applied: false} // user not in the chat
exec := NewExecutor(sender, 0, nil)
delivered, err := exec.Handle(context.Background(), chatGateCmd("888", false))
if err != nil {
t.Fatalf("handle: %v", err)
}
if delivered {
t.Error("expected delivered=false when the user is not in the chat")
}
if len(sender.gate) != 1 {
t.Errorf("gate calls = %d, want 1", len(sender.gate))
}
}
func TestExecutorChatGateInvalidExternalID(t *testing.T) {
exec := NewExecutor(&fakeSender{}, 0, nil)
if _, err := exec.Handle(context.Background(), chatGateCmd("not-a-number", true)); err == nil {
t.Error("expected an error for a non-numeric external_id")
}
}
func TestExecutorSendToChannel(t *testing.T) {
channelCmd := &botlinkv1.Command{Payload: &botlinkv1.Command_SendToChannel{SendToChannel: &telegramv1.SendToGameChannelRequest{Text: "news"}}}
@@ -37,6 +37,24 @@ type BotConfig struct {
// GameChannelID is the chat id of the bot's game channel for the admin channel
// post (TELEGRAM_GAME_CHANNEL_ID, optional; 0 disables channel posts).
GameChannelID int64
// ChatID is the chat id of the moderated discussion supergroup (a channel's linked
// chat) whose write access the bot gates by registration and moderation
// (TELEGRAM_CHAT_ID, optional; 0 disables chat gating). The bot must be an admin
// there with the "Ban users" right, and "chat_member" in its allowed updates.
ChatID int64
// PromoBotToken is the API token of the optional standalone promo bot run in this
// container — a second bot whose only job is to answer /start with a button that
// opens the main bot's Mini App (TELEGRAM_PROMO_BOT_TOKEN, optional; empty disables
// the promo bot).
PromoBotToken string
// BotUsername is the main bot's @username without the leading @, used in the promo
// bot's message text (TELEGRAM_BOT_USERNAME; required when the promo bot runs).
BotUsername string
// BotLinkURL is the main bot's Mini App direct link — the same value the UI builds
// share links from (VITE_TELEGRAM_LINK), e.g. https://t.me/<bot>/<app>. The promo
// button appends ?startapp=<payload> to it (TELEGRAM_BOT_LINK; required when the
// promo bot runs). It is distinct from the BotLink mTLS dial config below.
BotLinkURL string
// MiniAppURL is the HTTPS origin of the Mini App registered with BotFather; it is
// the base of every launch button (TELEGRAM_MINIAPP_URL, required).
MiniAppURL string
@@ -114,6 +132,9 @@ func LoadBot() (BotConfig, error) {
TestEnv: os.Getenv("TELEGRAM_TEST_ENV") == "true",
OwnsUpdates: os.Getenv("TELEGRAM_OWNS_UPDATES") != "false",
SendRatePerSecond: defaultSendRatePerSecond,
PromoBotToken: os.Getenv("TELEGRAM_PROMO_BOT_TOKEN"),
BotUsername: strings.TrimPrefix(os.Getenv("TELEGRAM_BOT_USERNAME"), "@"),
BotLinkURL: os.Getenv("TELEGRAM_BOT_LINK"),
LogLevel: envOr("TELEGRAM_LOG_LEVEL", "info"),
BotLink: BotLinkClientConfig{
GatewayAddr: os.Getenv("TELEGRAM_GATEWAY_ADDR"),
@@ -128,6 +149,9 @@ func LoadBot() (BotConfig, error) {
if cfg.GameChannelID, err = envInt64("TELEGRAM_GAME_CHANNEL_ID", 0); err != nil {
return BotConfig{}, err
}
if cfg.ChatID, err = envInt64("TELEGRAM_CHAT_ID", 0); err != nil {
return BotConfig{}, err
}
if cfg.SendRatePerSecond, err = envInt("TELEGRAM_SEND_RATE_PER_SECOND", defaultSendRatePerSecond); err != nil {
return BotConfig{}, err
}
@@ -155,6 +179,9 @@ func LoadBot() (BotConfig, error) {
if cfg.BotLink.CertFile == "" || cfg.BotLink.KeyFile == "" || cfg.BotLink.CAFile == "" {
return BotConfig{}, fmt.Errorf("config: TELEGRAM_BOTLINK_TLS_CERT, _KEY and _CA are required")
}
if cfg.PromoBotToken != "" && (cfg.BotUsername == "" || cfg.BotLinkURL == "") {
return BotConfig{}, fmt.Errorf("config: TELEGRAM_BOT_USERNAME and TELEGRAM_BOT_LINK are required when TELEGRAM_PROMO_BOT_TOKEN is set")
}
return cfg, nil
}
@@ -103,6 +103,54 @@ func TestLoadBotRequired(t *testing.T) {
}
}
// TestLoadBotChatAndPromo verifies the moderated-chat id and the promo-bot
// configuration parse, the @-prefix is stripped from the username, and a promo token
// without a username/link is rejected.
func TestLoadBotChatAndPromo(t *testing.T) {
t.Run("parsed", func(t *testing.T) {
setBotRequired(t)
t.Setenv("TELEGRAM_CHAT_ID", "-100222")
t.Setenv("TELEGRAM_PROMO_BOT_TOKEN", "promo-token")
t.Setenv("TELEGRAM_BOT_USERNAME", "@ScrabbleBot")
t.Setenv("TELEGRAM_BOT_LINK", "https://t.me/ScrabbleBot/app")
c, err := LoadBot()
if err != nil {
t.Fatalf("LoadBot: %v", err)
}
if c.ChatID != -100222 {
t.Errorf("ChatID = %d, want -100222", c.ChatID)
}
if c.PromoBotToken != "promo-token" {
t.Errorf("PromoBotToken = %q", c.PromoBotToken)
}
if c.BotUsername != "ScrabbleBot" {
t.Errorf("BotUsername = %q, want the leading @ stripped", c.BotUsername)
}
if c.BotLinkURL != "https://t.me/ScrabbleBot/app" {
t.Errorf("BotLinkURL = %q", c.BotLinkURL)
}
})
t.Run("promo token requires username and link", func(t *testing.T) {
setBotRequired(t)
t.Setenv("TELEGRAM_PROMO_BOT_TOKEN", "promo-token")
if _, err := LoadBot(); err == nil {
t.Fatal("LoadBot: expected an error for a promo token without username/link")
}
})
t.Run("disabled by default", func(t *testing.T) {
setBotRequired(t)
c, err := LoadBot()
if err != nil {
t.Fatalf("LoadBot: %v", err)
}
if c.PromoBotToken != "" || c.ChatID != 0 {
t.Errorf("defaults: promo=%q chat=%d, want empty/0", c.PromoBotToken, c.ChatID)
}
})
}
// TestLoadRejectsUnsupportedExporter verifies an exporter outside the supported set
// fails validation (the validator path).
func TestLoadRejectsUnsupportedExporter(t *testing.T) {
@@ -0,0 +1,164 @@
// Package promobot is the standalone promo bot: a second Telegram bot in the bot
// container whose only job is to answer /start with a localized message and a button
// that opens the MAIN bot's Mini App. It is self-contained — it never calls the
// gateway or the game — so onboarding works even when the game is down. The button is
// a URL to the main bot's direct Mini App link: a web_app button would launch the Mini
// App under the promo bot's identity (its token would sign the initData), which the
// main bot's validator would reject, so the cross-bot launch must be a t.me link. It
// reuses the same link the UI builds invitation links from (VITE_TELEGRAM_LINK).
package promobot
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 promo bot.
type Config struct {
// Token is the promo bot's 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
// BotUsername is the main bot's @username without the leading @, named in the
// message text.
BotUsername string
// BotLinkURL is the main bot's Mini App direct link; the button appends
// ?startapp=<payload> to it.
BotLinkURL string
// SendRatePerSecond caps outbound sends to respect the Bot API flood limits; 0
// disables the limiter. The burst equals the per-second rate.
SendRatePerSecond int
}
// Bot is the promo bot wrapper around a Telegram Bot API client.
type Bot struct {
api *tgbot.Bot
username string
linkURL string
log *zap.Logger
limiter *rate.Limiter
}
// New builds the promo bot, registering a /start (and default) handler that replies
// with the 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{username: cfg.BotUsername, linkURL: cfg.BotLinkURL, 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 {
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 command, 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("promo: set commands failed", zap.Error(err))
}
t.api.Start(ctx)
}
// handleStart replies to any message (typically /start) with the localized promo text
// and a button that opens the main bot's Mini App, forwarding any /start payload.
func (t *Bot) handleStart(ctx context.Context, api *tgbot.Bot, update *models.Update) {
if update.Message == nil {
return
}
if err := t.throttle(ctx); err != nil {
return
}
lang := ""
if update.Message.From != nil {
lang = update.Message.From.LanguageCode
}
text, button := promoText(lang, t.username)
if _, err := api.SendMessage(ctx, &tgbot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: text,
ReplyMarkup: t.launchMarkup(button, startPayload(update.Message.Text)),
}); err != nil {
t.log.Warn("promo: reply to start failed", zap.Error(err))
}
}
// launchMarkup builds the single URL button that opens the main bot's Mini App at the
// optional startapp payload.
func (t *Bot) launchMarkup(buttonText, startParam string) *models.InlineKeyboardMarkup {
return &models.InlineKeyboardMarkup{
InlineKeyboard: [][]models.InlineKeyboardButton{{
{Text: buttonText, URL: t.launchURL(startParam)},
}},
}
}
// launchURL appends the startapp payload to the main bot's Mini App link; an empty
// payload returns the base link unchanged.
func (t *Bot) launchURL(startParam string) string {
if startParam == "" {
return t.linkURL
}
u, err := url.Parse(t.linkURL)
if err != nil {
return t.linkURL
}
q := u.Query()
q.Set("startapp", startParam)
u.RawQuery = q.Encode()
return u.String()
}
// 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)
}
// 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))
}
// promoText returns the localized message body and button label, naming the main bot
// (Russian for a "ru" language code, English otherwise).
func promoText(lang, username string) (text, button string) {
if strings.HasPrefix(strings.ToLower(lang), "ru") {
return "Откройте @" + username + " и выберите в настройках профиля нужный вариант игры.", "🤩 Хочу играть!"
}
return "Open @" + username + " and choose your game variant in the profile settings.", "🤩 I want to play!"
}
@@ -0,0 +1,105 @@
package promobot
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/go-telegram/bot/models"
"go.uber.org/zap"
)
func TestPromoTextLocalization(t *testing.T) {
en, enBtn := promoText("en", "ScrabbleBot")
if !strings.Contains(en, "@ScrabbleBot") || !strings.Contains(en, "profile settings") {
t.Errorf("en text = %q", en)
}
if enBtn != "🤩 I want to play!" {
t.Errorf("en button = %q", enBtn)
}
ru, ruBtn := promoText("ru-RU", "ScrabbleBot")
if !strings.Contains(ru, "@ScrabbleBot") || !strings.Contains(ru, "Откройте") {
t.Errorf("ru text = %q", ru)
}
if ruBtn != "🤩 Хочу играть!" {
t.Errorf("ru button = %q", ruBtn)
}
// An unknown language falls back to English.
if got, _ := promoText("de", "B"); !strings.Contains(got, "Open @B") {
t.Errorf("fallback text = %q, want English", got)
}
}
func TestLaunchURLAppendsStartapp(t *testing.T) {
b := &Bot{linkURL: "https://t.me/bot/app"}
if got := b.launchURL(""); got != "https://t.me/bot/app" {
t.Errorf("empty payload = %q, want the base link unchanged", got)
}
if got := b.launchURL("g123"); got != "https://t.me/bot/app?startapp=g123" {
t.Errorf("launchURL = %q, want startapp=g123 appended", got)
}
}
func TestLaunchMarkupIsURLButton(t *testing.T) {
b := &Bot{linkURL: "https://t.me/bot/app"}
btn := b.launchMarkup("Play", "f99").InlineKeyboard[0][0]
if btn.WebApp != nil {
t.Error("the promo button must not be a web_app button (it would sign initData with the promo token, which the main bot rejects)")
}
if !strings.Contains(btn.URL, "startapp=f99") {
t.Errorf("button URL = %q, want startapp=f99", btn.URL)
}
}
// fakeAPI answers getMe (so New succeeds offline) and records the last sendMessage.
type fakeAPI struct {
chatID, text, replyMarkup string
}
func (f *fakeAPI) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, "/getMe"):
io.WriteString(w, `{"ok":true,"result":{"id":1,"is_bot":true,"first_name":"t","username":"promo"}}`)
case strings.HasSuffix(r.URL.Path, "/sendMessage"):
f.chatID = r.FormValue("chat_id")
f.text = r.FormValue("text")
f.replyMarkup = r.FormValue("reply_markup")
io.WriteString(w, `{"ok":true,"result":{"message_id":1}}`)
default:
io.WriteString(w, `{"ok":true,"result":true}`)
}
}
func TestHandleStartReplies(t *testing.T) {
api := &fakeAPI{}
srv := httptest.NewServer(api)
t.Cleanup(srv.Close)
b, err := New(Config{Token: "1:2", APIBaseURL: srv.URL, BotUsername: "ScrabbleBot", BotLinkURL: "https://t.me/bot/app"}, zap.NewNop())
if err != nil {
t.Fatalf("new: %v", err)
}
b.handleStart(context.Background(), b.api, &models.Update{Message: &models.Message{
Chat: models.Chat{ID: 42},
From: &models.User{LanguageCode: "ru"},
Text: "/start f99",
}})
if api.chatID != "42" {
t.Errorf("chat_id = %q, want 42", api.chatID)
}
if !strings.Contains(api.text, "@ScrabbleBot") {
t.Errorf("text = %q, want the @mention", api.text)
}
if strings.Contains(api.replyMarkup, "web_app") {
t.Errorf("reply_markup = %q has a web_app button; want a url button", api.replyMarkup)
}
if !strings.Contains(api.replyMarkup, "startapp=f99") {
t.Errorf("reply_markup = %q, want startapp=f99 (the /start payload forwarded)", api.replyMarkup)
}
}