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
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:
@@ -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"}}}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user