Files
archipelago/connectors/telegram/telegram.go
T
sam 48019ec868
publish / publish (push) Successful in 1m22s
fix(telegram): a long message goes out in parts instead of failing for ever
The connector sent title and body as one sendMessage, so any notification
over Telegram's 4096 UTF-16 unit limit was refused with 'message is too
long' and, because a delivery is retried until the channel confirms it,
retried every ten minutes for ever without ever arriving. The chat channel
had its own splitter; both now share one in sdk/telegramtext, which counts
UTF-16 units rather than runes so an emoji-heavy body isn't over the limit
either.
2026-11-18 00:36:44 +11:00

296 lines
8.9 KiB
Go

package main
import (
"bytes"
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"slices"
"strconv"
"strings"
"time"
"github.com/samcharles93/archipelago/sdk/connector"
connectorv1 "github.com/samcharles93/archipelago/sdk/connector/v1"
"github.com/samcharles93/archipelago/sdk/telegramtext"
)
const (
botAPI = "https://api.telegram.org"
pollSeconds = 25
answerPrefix = "answer:"
answerType = "approval.answer"
)
type telegram struct {
token string
users []int64
api string
client *http.Client
}
func newTelegram(cfg connector.Config) (*telegram, error) {
token := cfg.Secrets["bot.token"]
if token == "" {
return nil, errors.New("the bot credential slot needs a token")
}
var users []int64
for f := range strings.SplitSeq(cfg.Settings["user_ids"], ",") {
if f = strings.TrimSpace(f); f == "" {
continue
}
id, err := strconv.ParseInt(f, 10, 64)
if err != nil || id <= 0 {
return nil, fmt.Errorf("user_ids: %q isn't a Telegram user id", f)
}
users = append(users, id)
}
if len(users) == 0 {
return nil, errors.New("user_ids needs at least one Telegram user id")
}
return &telegram{
token: token, users: users, api: botAPI,
client: &http.Client{Timeout: (pollSeconds + 15) * time.Second},
}, nil
}
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."}}}`)
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"}}}`)
)
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,
}},
Events: []*connectorv1.EventType{{
Name: answerType, Description: "An allowed user tapped Approve or Deny.", Schema: answerSchema,
}},
}
}
type message struct {
Title string `json:"title"`
Body string `json:"body"`
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
// 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" {
return "", fmt.Errorf("no delivery named %q", delivery)
}
var m message
if err := json.Unmarshal(input, &m, json.RejectUnknownMembers(true)); err != nil {
return "", fmt.Errorf("message: %w", err)
}
text := m.Title
if m.Body != "" {
text += "\n\n" + m.Body
}
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))
}
}
if len(ids) == 0 {
return "", errors.Join(failed...)
}
return strings.Join(ids, ","), nil
}
type update struct {
UpdateID int64 `json:"update_id"`
Callback *struct {
ID string `json:"id"`
Data string `json:"data"`
Message *struct {
MessageID int64 `json:"message_id"`
Chat struct {
ID int64 `json:"id"`
} `json:"chat"`
} `json:"message"`
From struct {
ID int64 `json:"id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Username string `json:"username"`
} `json:"from"`
} `json:"callback_query"`
}
// Listen long-polls for taps. The cursor is Telegram's next update offset, so
// a batch the host didn't store is fetched again when it listens again.
func (t *telegram) Listen(ctx context.Context, cursor string, emit func([]connector.Event, string) error) error {
offset, _ := strconv.ParseInt(cursor, 10, 64)
for ctx.Err() == nil {
var updates []update
err := t.call(ctx, "getUpdates", map[string]any{
"offset": offset, "timeout": pollSeconds, "allowed_updates": []string{"callback_query"},
}, &updates)
if err != nil {
return err
}
if len(updates) == 0 {
continue
}
var events []connector.Event
var replies []func()
for _, u := range updates {
offset = max(offset, u.UpdateID+1)
e, reply := t.answer(ctx, u)
if e != nil {
events = append(events, *e)
}
if reply != nil {
replies = append(replies, reply)
}
}
if err := emit(events, strconv.FormatInt(offset, 10)); err != nil {
return err
}
// Only once the answers are stored does the person hear they were.
for _, r := range replies {
r()
}
}
return ctx.Err()
}
// answer turns a tap into an event, and says what to tell the person. A tap
// from a user who isn't allowed is no event.
func (t *telegram) answer(ctx context.Context, u update) (*connector.Event, func()) {
q := u.Callback
if q == nil {
return nil, nil
}
tell := func(text string) func() {
return func() {
_ = t.call(ctx, "answerCallbackQuery", map[string]any{"callback_query_id": q.ID, "text": text}, nil)
}
}
if !slices.Contains(t.users, q.From.ID) {
return nil, tell("You're not allowed to answer this.")
}
approved, request, ok := parseAnswer(q.Data)
if !ok {
return nil, tell("That button is out of date.")
}
name := strings.TrimSpace(q.From.FirstName + " " + q.From.LastName)
if name == "" {
name = q.From.Username
}
fields, err := json.Marshal(map[string]any{
"request_id": request, "approved": approved, "by": "telegram:" + strconv.FormatInt(q.From.ID, 10), "by_name": name,
})
if err != nil {
return nil, tell("That answer couldn't be read.")
}
received := tell("Answer received.")
return &connector.Event{
Type: answerType, SourceEventID: "update:" + strconv.FormatInt(u.UpdateID, 10), Fields: fields, OccurredAt: time.Now().UTC(),
}, func() {
received()
// The buttons go once the answer is stored, so nobody taps a settled
// request again.
if q.Message != nil {
_ = t.call(ctx, "editMessageReplyMarkup", map[string]any{
"chat_id": q.Message.Chat.ID, "message_id": q.Message.MessageID,
"reply_markup": map[string]any{"inline_keyboard": [][]any{}},
}, nil)
}
}
}
// parseAnswer reads a button's data: "answer:<yes|no>:<request id>".
func parseAnswer(data string) (approved bool, request string, ok bool) {
rest, found := strings.CutPrefix(data, answerPrefix)
if !found {
return false, "", false
}
verdict, id, found := strings.Cut(rest, ":")
if !found || id == "" {
return false, "", false
}
switch verdict {
case "yes":
return true, id, true
case "no":
return false, id, true
}
return false, "", false
}
// call posts one Bot API method and decodes its result into out.
func (t *telegram) call(ctx context.Context, method string, body, out any) error {
payload, err := json.Marshal(body)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, t.api+"/bot"+t.token+"/"+method, bytes.NewReader(payload))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
res, err := t.client.Do(req)
if err != nil {
// The URL holds the token, so it never goes into an error.
var uerr *url.Error
if errors.As(err, &uerr) {
return fmt.Errorf("%s: %w", method, uerr.Err)
}
return fmt.Errorf("%s failed", method)
}
defer func() { _ = res.Body.Close() }()
raw, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
if err != nil {
return fmt.Errorf("%s: %w", method, err)
}
var env struct {
OK bool `json:"ok"`
Description string `json:"description"`
Result jsontext.Value `json:"result"`
}
if err := json.Unmarshal(raw, &env); err != nil {
return fmt.Errorf("%s: %w", method, err)
}
if !env.OK {
return fmt.Errorf("%s: %s", method, env.Description)
}
if out == nil {
return nil
}
return json.Unmarshal(env.Result, out)
}