package main import ( "bytes" "cmp" "context" "encoding/json/jsontext" json "encoding/json/v2" "errors" "fmt" "io" "net/http" "net/url" "slices" "strconv" "strings" "sync" "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" linkType = "account.link" ) type telegram struct { token string users []int64 api string client *http.Client mu sync.Mutex username string } 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."}}}`) 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:"},"by_name":{"type":"string"},` + `"chat_id":{"type":"string","description":"The chat to reply to."}}}`) linkSchema = []byte(`{"type":"object","required":["by","code"],"properties":{` + `"by":{"type":"string","description":"telegram:"},"code":{"type":"string"},` + `"name":{"type":"string","description":"The sender's @username, or their name."},` + `"chat_id":{"type":"string","description":"The chat to reply to."}}}`) ) func (t *telegram) Describe() connector.Description { return connector.Description{ Settings: []*connectorv1.Setting{{ Key: "user_ids", Label: "User IDs", Required: true, Type: connectorv1.SettingType_SETTING_TYPE_LIST, Description: "Telegram user IDs that may answer, separated by commas.", }}, 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, }, { Name: linkType, Description: "An allowed user sent the bot a link code.", Schema: linkSchema, }}, } } type message struct { Title string `json:"title"` Body string `json:"body"` ApprovalRequestID string `json:"approval_request_id"` } // 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) { 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) } text := m.Title if m.Body != "" { text += "\n\n" + m.Body } var ids []string var failed []error for _, chat := range t.users { 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 { return "", errors.Join(failed...) } 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 sender struct { ID int64 `json:"id"` FirstName string `json:"first_name"` LastName string `json:"last_name"` Username string `json:"username"` } // displayName is the sender's @username, or their name when they have none. func (s sender) displayName() string { if s.Username != "" { return "@" + s.Username } return strings.TrimSpace(s.FirstName + " " + s.LastName) } type update struct { UpdateID int64 `json:"update_id"` Message *struct { Text string `json:"text"` Chat struct { ID int64 `json:"id"` } `json:"chat"` From sender `json:"from"` } `json:"message"` 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 sender `json:"from"` } `json:"callback_query"` } // Listen long-polls for taps and link codes. 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", "message"}, }, &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.handle(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() } // handle turns an update into an event and says what to tell the person. func (t *telegram) handle(ctx context.Context, u update) (*connector.Event, func()) { if u.Message != nil { return t.link(ctx, u) } return t.answer(ctx, u) } // startCode reads the code from a "/start " message. A bare /start, or // any other text, has none. func startCode(text string) (string, bool) { fields := strings.Fields(text) if len(fields) != 2 { return "", false } command, _, _ := strings.Cut(fields[0], "@") return fields[1], command == "/start" } // link turns "/start " from an allowed user into an account.link event. // The user is told when they aren't allowed, since core can't reach a chat // outside the allowed users to say so. func (t *telegram) link(ctx context.Context, u update) (*connector.Event, func()) { m := u.Message code, ok := startCode(m.Text) if !ok { return nil, nil } chat := m.Chat.ID if !slices.Contains(t.users, m.From.ID) { return nil, func() { _ = t.call(ctx, "sendMessage", map[string]any{"chat_id": chat, "text": "You're not allowed to link this bot."}, nil) } } return &connector.Event{ Type: linkType, SourceEventID: "update:" + strconv.FormatInt(u.UpdateID, 10), Fields: linkFields(m.From, code, chat), OccurredAt: time.Now().UTC(), }, nil } // linkFields is the account.link payload. by names the sender as // "telegram:", the connector's own name, which core requires. func linkFields(from sender, code string, chat int64) jsontext.Value { fields, _ := json.Marshal(map[string]string{ "by": "telegram:" + strconv.FormatInt(from.ID, 10), "code": code, "name": from.displayName(), "chat_id": strconv.FormatInt(chat, 10), }) return fields } // LinkURL returns the link that opens the bot with the code attached. func (t *telegram) LinkURL(ctx context.Context, code string) (string, error) { username, err := t.botUsername(ctx) if err != nil { return "", err } return "https://t.me/" + username + "?start=" + url.QueryEscape(code), nil } // botUsername asks getMe once and keeps the answer for the process. func (t *telegram) botUsername(ctx context.Context) (string, error) { t.mu.Lock() defer t.mu.Unlock() if t.username != "" { return t.username, nil } var me struct { Username string `json:"username"` } if err := t.call(ctx, "getMe", map[string]any{}, &me); err != nil { return "", fmt.Errorf("look up the bot's username: %w", err) } if me.Username == "" { return "", errors.New("look up the bot's username: Telegram returned none") } t.username = me.Username return t.username, nil } // 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, "chat_id": strconv.FormatInt(q.From.ID, 10), }) 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::". 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"` ErrorCode int `json:"error_code"` 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 { err := fmt.Errorf("%s: %s", method, env.Description) // Telegram returns 400, 403 and 404 for requests that will fail again: // an invalid message, a blocked bot or a missing chat. switch cmp.Or(env.ErrorCode, res.StatusCode) { case http.StatusBadRequest, http.StatusForbidden, http.StatusNotFound: return connector.Permanent(err) } return err } if out == nil { return nil } return json.Unmarshal(env.Result, out) }