diff --git a/connectors/telegram/main.go b/connectors/telegram/main.go index de814e0..5876a97 100644 --- a/connectors/telegram/main.go +++ b/connectors/telegram/main.go @@ -2,6 +2,7 @@ // Approve and Deny buttons on an approval request, to the private chats of // the users an operator allows, and listens for their taps. A tap becomes an // approval.answer event, so an answer reaches Archie the way every event does. +// A /start code a user sends the bot becomes an account.link event. package main import "github.com/samcharles93/archipelago/sdk/connector" diff --git a/connectors/telegram/package.yaml b/connectors/telegram/package.yaml index 3e83b6f..6efa841 100644 --- a/connectors/telegram/package.yaml +++ b/connectors/telegram/package.yaml @@ -1,6 +1,6 @@ apiVersion: dev.archie.package.v1 displayName: Telegram -description: Delivers messages and approval requests to the Telegram users an operator allows, and turns their Approve and Deny taps into approval.answer events. The user_ids setting lists who may answer; the bot credential slot holds the bot token. +description: Delivers messages and approval requests to the Telegram users an operator allows, turns their Approve and Deny taps into approval.answer events, and links their Telegram account to an Archie account through a /start code. The user_ids setting lists who may answer; the bot credential slot holds the bot token. version: 0.1.0 contributes: extensions: diff --git a/connectors/telegram/telegram.go b/connectors/telegram/telegram.go index 4dab6b9..9c78e45 100644 --- a/connectors/telegram/telegram.go +++ b/connectors/telegram/telegram.go @@ -14,6 +14,7 @@ import ( "slices" "strconv" "strings" + "sync" "time" "github.com/samcharles93/archipelago/sdk/connector" @@ -26,6 +27,7 @@ const ( pollSeconds = 25 answerPrefix = "answer:" answerType = "approval.answer" + linkType = "account.link" ) type telegram struct { @@ -33,6 +35,9 @@ type telegram struct { users []int64 api string client *http.Client + + mu sync.Mutex + username string } func newTelegram(cfg connector.Config) (*telegram, error) { @@ -68,7 +73,12 @@ var ( `"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"}}}`) + `"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 { @@ -80,6 +90,8 @@ func (t *telegram) Describe() connector.Description { }}, 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, }}, } } @@ -178,8 +190,30 @@ func (t *telegram) sendText(ctx context.Context, chat int64, text, approvalReque 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"` @@ -189,23 +223,18 @@ type update 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"` + From sender `json:"from"` } `json:"callback_query"` } -// Listen long-polls for taps. The cursor is Telegram's next update offset, so +// 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"}, + "offset": offset, "timeout": pollSeconds, "allowed_updates": []string{"callback_query", "message"}, }, &updates) if err != nil { return err @@ -217,7 +246,7 @@ func (t *telegram) Listen(ctx context.Context, cursor string, emit func([]connec var replies []func() for _, u := range updates { offset = max(offset, u.UpdateID+1) - e, reply := t.answer(ctx, u) + e, reply := t.handle(ctx, u) if e != nil { events = append(events, *e) } @@ -236,6 +265,85 @@ func (t *telegram) Listen(ctx context.Context, cursor string, emit func([]connec 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()) { @@ -261,6 +369,7 @@ func (t *telegram) answer(ctx context.Context, u update) (*connector.Event, func } 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.") diff --git a/connectors/telegram/telegram_test.go b/connectors/telegram/telegram_test.go index 28ff5e6..bdcbd88 100644 --- a/connectors/telegram/telegram_test.go +++ b/connectors/telegram/telegram_test.go @@ -3,6 +3,7 @@ package main import ( "context" json "encoding/json/v2" + "maps" "net/http" "net/http/httptest" "slices" @@ -238,3 +239,76 @@ func TestAChatMessageReachesOnlyAnAllowedUser(t *testing.T) { }) } } + +func startMessage(updateID, userID, text string) string { + return `{"update_id":` + updateID + `,"message":{"text":"` + text + `","chat":{"id":` + userID + + `},"from":{"id":` + userID + `,"first_name":"Sam","username":"sam"}}}` +} + +// TestOnlyAnAllowedUsersStartCodeIsALink guards account linking: the event +// names the sender as "telegram:", which core requires of this +// connector, and carries the code unchanged. A user who isn't allowed, and a +// /start with no code, emit nothing. +func TestOnlyAnAllowedUsersStartCodeIsALink(t *testing.T) { + tests := []struct { + name string + update string + want string + wantReply bool + }{ + { + name: "an allowed user's code is a link", update: startMessage("7", "42", "/start c0de_-X"), + want: `{"by":"telegram:42","code":"c0de_-X","name":"@sam","chat_id":"42"}`, + }, + { + name: "a code addressed to the bot by name is a link", update: startMessage("7", "42", "/start@archie_bot c0de"), + want: `{"by":"telegram:42","code":"c0de","name":"@sam","chat_id":"42"}`, + }, + {name: "a bare start is ignored", update: startMessage("7", "42", "/start")}, + {name: "other text is ignored", update: startMessage("7", "42", "hello there")}, + {name: "a user who isn't allowed is refused", update: startMessage("7", "99", "/start c0de"), wantReply: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + bot := &fakeBot{updates: "[" + tt.update + "]"} + 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 + ctx, cancel := context.WithCancel(t.Context()) + bot.idle = cancel + var got []connector.Event + _ = tg.Listen(ctx, "", func(events []connector.Event, _ string) error { + got = events + return nil + }) + if tt.want == "" { + if len(got) != 0 { + t.Fatalf("got events %v, want none", got) + } + if tt.wantReply != (len(bot.sent) == 1) { + t.Fatalf("sent %v, want a refusal: %v", bot.sent, tt.wantReply) + } + return + } + if len(got) != 1 || got[0].Type != linkType { + t.Fatalf("got events %v, want one %s", got, linkType) + } + var gotFields, wantFields map[string]string + if err := json.Unmarshal(got[0].Fields, &gotFields); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal([]byte(tt.want), &wantFields); err != nil { + t.Fatal(err) + } + if !maps.Equal(gotFields, wantFields) { + t.Fatalf("fields = %v, want %v", gotFields, wantFields) + } + }) + } +}