1package telegram
2
3import (
4 "context"
5 "fmt"
6 "strconv"
7 "strings"
8 "time"
9
10 "github.com/patriceckhart/zot/packages/agent/modes/bot"
11 "github.com/patriceckhart/zot/packages/provider"
12)
13
14// Adapter implements bot.BotAdapter for Telegram.
15type Adapter struct {
16 Client *Client
17 Cfg *Config // pointer so Run can mutate and persist
18 Save func(Config) error
19}
20
21// NewAdapter creates a Telegram adapter.
22func NewAdapter(client *Client, cfg *Config, save func(Config) error) *Adapter {
23 return &Adapter{Client: client, Cfg: cfg, Save: save}
24}
25
26// Run drives the Telegram long-polling loop. It performs initial
27// GetMe, handles pairing, and dispatches inbound messages to the
28// generic handler / commandHandler callbacks.
29func (a *Adapter) Run(ctx context.Context,
30 handler func(bot.InboundMessage),
31 commandHandler func(bot.Command, bot.InboundMessage),
32) error {
33 if a.Cfg.BotToken == "" {
34 return fmt.Errorf("no bot token configured; run `zot bot setup` first")
35 }
36 me, err := a.Client.GetMe(ctx)
37 if err != nil {
38 return fmt.Errorf("getMe: %w", err)
39 }
40 // Keep the stored username/id in sync with the actual bot.
41 if a.Cfg.BotID != me.ID || a.Cfg.BotUsername != me.Username {
42 a.Cfg.BotID = me.ID
43 a.Cfg.BotUsername = me.Username
44 _ = a.Save(*a.Cfg)
45 }
46
47 fmt.Printf("telegram bridge online as @%s (id=%d)\n", me.Username, me.ID)
48 if a.Cfg.AllowedUserID == 0 {
49 fmt.Println("no user paired yet — send /start to the bot from Telegram to claim it")
50 } else {
51 fmt.Printf("paired with telegram user id %d\n", a.Cfg.AllowedUserID)
52 }
53
54 return a.pollLoop(ctx, handler, commandHandler)
55}
56
57// pollLoop long-polls Telegram for updates and dispatches them.
58func (a *Adapter) pollLoop(ctx context.Context,
59 handler func(bot.InboundMessage),
60 commandHandler func(bot.Command, bot.InboundMessage),
61) error {
62 backoff := time.Second
63 for {
64 if err := ctx.Err(); err != nil {
65 return err
66 }
67 updates, err := a.Client.GetUpdates(ctx, a.Cfg.LastUpdateID+1, 30)
68 if err != nil {
69 if ctx.Err() != nil {
70 return ctx.Err()
71 }
72 fmt.Fprintln(stderr(), "telegram: getUpdates error:", err)
73 select {
74 case <-ctx.Done():
75 return ctx.Err()
76 case <-time.After(backoff):
77 }
78 if backoff < 30*time.Second {
79 backoff *= 2
80 }
81 continue
82 }
83 backoff = time.Second
84 for _, u := range updates {
85 a.handleUpdate(ctx, u, handler, commandHandler)
86 a.Cfg.LastUpdateID = u.UpdateID
87 _ = a.Save(*a.Cfg)
88 }
89 }
90}
91
92// handleUpdate processes a single Telegram update. Telegram-specific
93// concerns (pairing, user filtering, image download) live here; the
94// generic callbacks are called for normal messages and commands.
95func (a *Adapter) handleUpdate(ctx context.Context, u Update,
96 handler func(bot.InboundMessage),
97 commandHandler func(bot.Command, bot.InboundMessage),
98) {
99 msg := u.Message
100 if msg == nil {
101 msg = u.Edited
102 }
103 if msg == nil || msg.From == nil || msg.From.IsBot {
104 return
105 }
106 if msg.Chat.Type != "private" {
107 return
108 }
109
110 chanID := fmt.Sprintf("%d", msg.Chat.ID)
111 msgID := fmt.Sprintf("%d", msg.MessageID)
112
113 // Pairing: first user who sends /start claims the bridge.
114 text := strings.TrimSpace(msg.Text)
115 if a.Cfg.AllowedUserID == 0 {
116 if strings.HasPrefix(text, "/start") {
117 a.Cfg.AllowedUserID = msg.From.ID
118 _ = a.Save(*a.Cfg)
119 _ = a.Client.SendMessage(ctx, msg.Chat.ID,
120 fmt.Sprintf("paired with @%s. send any message and i'll forward it to zot.", msg.From.Username),
121 msg.MessageID)
122 return
123 }
124 _ = a.Client.SendMessage(ctx, msg.Chat.ID,
125 "this bot isn't paired yet. send /start to claim it.",
126 msg.MessageID)
127 return
128 }
129
130 // Enforce allowed user.
131 if msg.From.ID != a.Cfg.AllowedUserID {
132 _ = a.Client.SendMessage(ctx, msg.Chat.ID,
133 "this bot is paired with a different user.",
134 msg.MessageID)
135 return
136 }
137
138 inbound := bot.InboundMessage{
139 ChannelID: chanID,
140 MessageID: msgID,
141 }
142
143 // Built-in commands that bypass the agent.
144 switch text {
145 case "/start":
146 commandHandler(bot.CmdStart, inbound)
147 return
148 case "/help":
149 commandHandler(bot.CmdHelp, inbound)
150 return
151 case "/status":
152 commandHandler(bot.CmdStatus, inbound)
153 return
154 case "/stop":
155 commandHandler(bot.CmdStop, inbound)
156 return
157 }
158 if bot.IsStopCommand(text) {
159 commandHandler(bot.CmdStop, inbound)
160 return
161 }
162
163 // Build the prompt: combine text + caption; download image attachments.
164 prompt := strings.TrimSpace(msg.Text)
165 if msg.Caption != "" {
166 if prompt != "" {
167 prompt += "\n"
168 }
169 prompt += msg.Caption
170 }
171
172 var images []provider.ImageBlock
173 if len(msg.Photo) > 0 {
174 largest := msg.Photo[len(msg.Photo)-1]
175 if data, mime, err := a.download(ctx, largest.FileID, ""); err == nil {
176 images = append(images, provider.ImageBlock{MimeType: mime, Data: data})
177 } else {
178 fmt.Fprintln(stderr(), "telegram: download photo:", err)
179 }
180 }
181 if msg.Document != nil && isImageMIME(msg.Document.MimeType) {
182 if data, mime, err := a.download(ctx, msg.Document.FileID, msg.Document.MimeType); err == nil {
183 images = append(images, provider.ImageBlock{MimeType: mime, Data: data})
184 }
185 }
186
187 inbound.Text = prompt
188 inbound.Images = images
189 handler(inbound)
190}
191
192// Send delivers a reply to a Telegram chat. channelID is parsed back
193// to int64. Messages are chunked to 4000 runes (Telegram limit 4096).
194func (a *Adapter) Send(ctx context.Context, channelID, text string, opts bot.SendOptions) error {
195 chatID, err := strconv.ParseInt(channelID, 10, 64)
196 if err != nil {
197 return fmt.Errorf("invalid channelID %q: %w", channelID, err)
198 }
199 replyTo := 0
200 if opts.ReplyToMessageID != "" {
201 if n, err := strconv.Atoi(opts.ReplyToMessageID); err == nil {
202 replyTo = n
203 }
204 }
205 for _, chunk := range chunkMessage(text, 4000) {
206 if err := a.Client.SendMessage(ctx, chatID, chunk, replyTo); err != nil {
207 return err
208 }
209 // Only the first chunk should be threaded under the original message.
210 replyTo = 0
211 }
212 return nil
213}
214
215// IndicateWorking keeps Telegram's "typing..." indicator alive until
216// the returned stop function is called.
217func (a *Adapter) IndicateWorking(ctx context.Context, channelID string) (stop func()) {
218 chatID, err := strconv.ParseInt(channelID, 10, 64)
219 if err != nil {
220 return func() {}
221 }
222 tctx, cancel := context.WithCancel(ctx)
223 go func() {
224 for {
225 _ = a.Client.SendChatAction(tctx, chatID, "typing")
226 select {
227 case <-tctx.Done():
228 return
229 case <-time.After(4 * time.Second):
230 }
231 }
232 }()
233 return cancel
234}
235
236// StatusText returns the bot's @username for inclusion in /status.
237func (a *Adapter) StatusText() string {
238 if a.Cfg.BotUsername != "" {
239 return "@" + a.Cfg.BotUsername
240 }
241 return ""
242}
243
244// download fetches a file from Telegram and returns bytes + mime.
245func (a *Adapter) download(ctx context.Context, fileID, mime string) ([]byte, string, error) {
246 f, err := a.Client.GetFile(ctx, fileID)
247 if err != nil {
248 return nil, "", err
249 }
250 data, err := a.Client.DownloadFile(ctx, f.FilePath)
251 if err != nil {
252 return nil, "", err
253 }
254 if mime == "" {
255 mime = guessImageMIME(f.FilePath)
256 }
257 return data, mime, nil
258}