Compare commits

...
2 Commits
Author SHA1 Message Date
sam 87337522df docs(telegram): plain the deliver comment (#2085)
publish / publish (push) Successful in 1m17s
2026-11-21 15:21:51 +11:00
sam 6fec20896b feat(telegram): declare the chat_message delivery (#2085) 2026-11-21 15:18:07 +11:00
2 changed files with 111 additions and 22 deletions

No files matched your search

+69 -22
View File
@@ -64,6 +64,8 @@ var (
messageSchema = []byte(`{"type":"object","additionalProperties":false,"required":["title"],"properties":{` +
`"title":{"type":"string"},"body":{"type":"string"},` +
`"approval_request_id":{"type":"string","description":"Present on an approval request: adds Approve and Deny buttons."}}}`)
chatMessageSchema = []byte(`{"type":"object","additionalProperties":false,"required":["chat_id","text"],"properties":{` +
`"chat_id":{"type":"string","description":"The Telegram user id of an allowed user."},"text":{"type":"string"}}}`)
answerSchema = []byte(`{"type":"object","required":["request_id","approved","by"],"properties":{` +
`"request_id":{"type":"string"},"approved":{"type":"boolean"},` +
`"by":{"type":"string","description":"telegram:<user id>"},"by_name":{"type":"string"}}}`)
@@ -73,6 +75,8 @@ func (t *telegram) Describe() connector.Description {
return connector.Description{
Deliveries: []*connectorv1.DeliveryType{{
Name: "message", Description: "A message to every allowed user's private chat.", InputSchema: messageSchema,
}, {
Name: "chat_message", Description: "Text to one allowed user's private chat.", InputSchema: chatMessageSchema,
}},
Events: []*connectorv1.EventType{{
Name: answerType, Description: "An allowed user tapped Approve or Deny.", Schema: answerSchema,
@@ -86,15 +90,24 @@ type message struct {
ApprovalRequestID string `json:"approval_request_id"`
}
// Deliver writes the message to each allowed user. One message holds at most
// 4096 UTF-16 code units, so a longer body goes out as several messages in
// order, with an approval request's buttons on the last. Telegram can't dedupe
// a send, so a delivery fails only when no chat got it: retrying a partial one
// Deliver sends the named delivery. "message" writes to each allowed user and
// "chat_message" to one of them. One message holds at most 4096 UTF-16 code
// units, so a longer text goes out as several messages in order, with an
// approval request's buttons on the last. Telegram cannot deduplicate a send, so a
// "message" delivery fails only when no chat got it: retrying a partial one
// would repeat it to the users who already have it.
func (t *telegram) Deliver(ctx context.Context, delivery string, input jsontext.Value, _ string) (string, error) {
if delivery != "message" {
switch delivery {
case "message":
return t.deliverMessage(ctx, input)
case "chat_message":
return t.deliverChatMessage(ctx, input)
default:
return "", fmt.Errorf("no delivery named %q", delivery)
}
}
func (t *telegram) deliverMessage(ctx context.Context, input jsontext.Value) (string, error) {
var m message
if err := json.Unmarshal(input, &m, json.RejectUnknownMembers(true)); err != nil {
return "", fmt.Errorf("message: %w", err)
@@ -105,24 +118,11 @@ func (t *telegram) Deliver(ctx context.Context, delivery string, input jsontext.
}
var ids []string
var failed []error
parts := telegramtext.Split(text, telegramtext.MaxLen)
for _, chat := range t.users {
for i, part := range parts {
body := map[string]any{"chat_id": chat, "text": part, "link_preview_options": map[string]any{"is_disabled": true}}
if i == len(parts)-1 && m.ApprovalRequestID != "" {
body["reply_markup"] = map[string]any{"inline_keyboard": [][]map[string]any{{
{"text": "Approve", "callback_data": answerPrefix + "yes:" + m.ApprovalRequestID},
{"text": "Deny", "callback_data": answerPrefix + "no:" + m.ApprovalRequestID},
}}}
}
var sent struct {
MessageID int64 `json:"message_id"`
}
if err := t.call(ctx, "sendMessage", body, &sent); err != nil {
failed = append(failed, fmt.Errorf("chat %d: %w", chat, err))
break
}
ids = append(ids, strconv.FormatInt(chat, 10)+"/"+strconv.FormatInt(sent.MessageID, 10))
sent, err := t.sendText(ctx, chat, text, m.ApprovalRequestID)
ids = append(ids, sent...)
if err != nil {
failed = append(failed, fmt.Errorf("chat %d: %w", chat, err))
}
}
if len(ids) == 0 {
@@ -131,6 +131,53 @@ func (t *telegram) Deliver(ctx context.Context, delivery string, input jsontext.
return strings.Join(ids, ","), nil
}
type chatMessage struct {
ChatID string `json:"chat_id"`
Text string `json:"text"`
}
// deliverChatMessage sends text to one chat. Only an allowed user's chat is
// addressable, so a workflow can't make the bot message anyone else.
func (t *telegram) deliverChatMessage(ctx context.Context, input jsontext.Value) (string, error) {
var m chatMessage
if err := json.Unmarshal(input, &m, json.RejectUnknownMembers(true)); err != nil {
return "", fmt.Errorf("chat_message: %w", err)
}
chat, err := strconv.ParseInt(m.ChatID, 10, 64)
if err != nil || !slices.Contains(t.users, chat) {
return "", connector.Permanent(fmt.Errorf("chat %q is not an allowed user", m.ChatID))
}
sent, err := t.sendText(ctx, chat, m.Text, "")
if err != nil {
return "", err
}
return strings.Join(sent, ","), nil
}
// sendText sends text to one chat in parts that fit a message, and returns the
// id of each message sent before any failure.
func (t *telegram) sendText(ctx context.Context, chat int64, text, approvalRequestID string) ([]string, error) {
var ids []string
parts := telegramtext.Split(text, telegramtext.MaxLen)
for i, part := range parts {
body := map[string]any{"chat_id": chat, "text": part, "link_preview_options": map[string]any{"is_disabled": true}}
if i == len(parts)-1 && approvalRequestID != "" {
body["reply_markup"] = map[string]any{"inline_keyboard": [][]map[string]any{{
{"text": "Approve", "callback_data": answerPrefix + "yes:" + approvalRequestID},
{"text": "Deny", "callback_data": answerPrefix + "no:" + approvalRequestID},
}}}
}
var sent struct {
MessageID int64 `json:"message_id"`
}
if err := t.call(ctx, "sendMessage", body, &sent); err != nil {
return ids, err
}
ids = append(ids, strconv.FormatInt(chat, 10)+"/"+strconv.FormatInt(sent.MessageID, 10))
}
return ids, nil
}
type update struct {
UpdateID int64 `json:"update_id"`
Callback *struct {
+42
View File
@@ -5,6 +5,7 @@ import (
json "encoding/json/v2"
"net/http"
"net/http/httptest"
"slices"
"strconv"
"strings"
"sync"
@@ -196,3 +197,44 @@ func TestAFailedCallNeverShowsTheToken(t *testing.T) {
t.Fatalf("err = %v, want an error without the token", err)
}
}
// TestAChatMessageReachesOnlyAnAllowedUser guards the chat_message delivery: a
// workflow names the chat, and a chat that isn't an allowed user's is refused
// permanently, so the bot can't be made to message anyone else.
func TestAChatMessageReachesOnlyAnAllowedUser(t *testing.T) {
tests := []struct {
name string
chatID string
wantSent []string
wantErr bool
}{
{name: "an allowed user's chat gets the text", chatID: "42", wantSent: []string{"cleaned web-1"}},
{name: "another chat is refused", chatID: "7", wantErr: true},
{name: "a chat id that isn't a number is refused", chatID: "ops", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
bot := &fakeBot{}
srv := httptest.NewServer(bot)
defer srv.Close()
tg, err := newTelegram(connector.Config{
Settings: map[string]string{"user_ids": "42"}, Secrets: map[string]string{"bot.token": fakeToken},
})
if err != nil {
t.Fatal(err)
}
tg.api = srv.URL
input, err := json.Marshal(map[string]string{"chat_id": tt.chatID, "text": "cleaned web-1"})
if err != nil {
t.Fatal(err)
}
_, err = tg.Deliver(t.Context(), "chat_message", input, "k")
if tt.wantErr != (err != nil) || (err != nil && !connector.IsPermanent(err)) {
t.Fatalf("deliver error = %v, want an error: %v, permanent", err, tt.wantErr)
}
if got := textsOf(bot.sent); !slices.Equal(got, tt.wantSent) {
t.Fatalf("sent %q, want %q", got, tt.wantSent)
}
})
}
}