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