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
+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)
}
})
}
}