v0.11.1 ab30a57

adapter.go RawHistoryFolder

1package telegram
2
3import (
4	"context"
5	"fmt"
6	"strconv"
7	"strings"
8	"time"
9
10	"github.com/bnema/zut/packages/agent/modes/bot"
11	"github.com/bnema/zut/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 `zut 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	command, isCommand := bot.ParseCommand(text)
119	if a.Cfg.AllowedUserID == 0 {
120		if isCommand && command == bot.CmdStart {
121			a.Cfg.AllowedUserID = msg.From.ID
122			_ = a.Save(*a.Cfg)
123			_ = a.Client.SendMessage(ctx, msg.Chat.ID,
124				fmt.Sprintf("paired with @%s. send any message and i'll forward it to zut.", msg.From.Username),
125				msg.MessageID)
126			return
127		}
128		_ = a.Client.SendMessage(ctx, msg.Chat.ID,
129			"this bot isn't paired yet. send /start to claim it.",
130			msg.MessageID)
131		return
132	}
133
134	// Enforce allowed user.
135	if msg.From.ID != a.Cfg.AllowedUserID {
136		_ = a.Client.SendMessage(ctx, msg.Chat.ID,
137			"this bot is paired with a different user.",
138			msg.MessageID)
139		return
140	}
141
142	inbound := bot.InboundMessage{
143		ChannelID: chanID,
144		MessageID: msgID,
145	}
146
147	// Built-in commands that bypass the agent.
148	if isCommand {
149		commandHandler(command, inbound)
150		return
151	}
152	if bot.IsStopCommand(text) {
153		commandHandler(bot.CmdStop, inbound)
154		return
155	}
156
157	// Build the prompt: combine text + caption; download image attachments.
158	prompt := strings.TrimSpace(msg.Text)
159	if msg.Caption != "" {
160		if prompt != "" {
161			prompt += "\n"
162		}
163		prompt += msg.Caption
164	}
165
166	var images []provider.ImageBlock
167	if len(msg.Photo) > 0 {
168		largest := msg.Photo[len(msg.Photo)-1]
169		if data, mime, err := a.download(ctx, largest.FileID, ""); err == nil {
170			images = append(images, provider.ImageBlock{MimeType: mime, Data: data})
171		} else {
172			fmt.Fprintln(stderr(), "telegram: download photo:", err)
173		}
174	}
175	if msg.Document != nil && bot.IsImageMIME(msg.Document.MimeType) {
176		if data, mime, err := a.download(ctx, msg.Document.FileID, msg.Document.MimeType); err == nil {
177			images = append(images, provider.ImageBlock{MimeType: mime, Data: data})
178		}
179	}
180
181	inbound.Text = prompt
182	inbound.Images = images
183	handler(inbound)
184}
185
186// Send delivers a reply to a Telegram chat.  channelID is parsed back
187// to int64.  Messages are chunked to 4000 runes (Telegram limit 4096).
188func (a *Adapter) Send(ctx context.Context, channelID, text string, opts bot.SendOptions) error {
189	chatID, err := strconv.ParseInt(channelID, 10, 64)
190	if err != nil {
191		return fmt.Errorf("invalid channelID %q: %w", channelID, err)
192	}
193	replyTo := 0
194	if opts.ReplyToMessageID != "" {
195		if n, err := strconv.Atoi(opts.ReplyToMessageID); err == nil {
196			replyTo = n
197		}
198	}
199	for _, chunk := range bot.ChunkMessage(text, 4000) {
200		if err := a.Client.SendMessage(ctx, chatID, chunk, replyTo); err != nil {
201			return err
202		}
203		// Only the first chunk should be threaded under the original message.
204		replyTo = 0
205	}
206	return nil
207}
208
209// IndicateWorking keeps Telegram's "typing..." indicator alive until
210// the returned stop function is called.
211func (a *Adapter) IndicateWorking(ctx context.Context, channelID string) (stop func()) {
212	chatID, err := strconv.ParseInt(channelID, 10, 64)
213	if err != nil {
214		return func() {}
215	}
216	tctx, cancel := context.WithCancel(ctx)
217	go func() {
218		for {
219			_ = a.Client.SendChatAction(tctx, chatID, "typing")
220			select {
221			case <-tctx.Done():
222				return
223			case <-time.After(4 * time.Second):
224			}
225		}
226	}()
227	return cancel
228}
229
230// StatusText returns the bot's @username for inclusion in /status.
231func (a *Adapter) StatusText() string {
232	if a.Cfg.BotUsername != "" {
233		return "@" + a.Cfg.BotUsername
234	}
235	return ""
236}
237
238// download fetches a file from Telegram and returns bytes + mime.
239func (a *Adapter) download(ctx context.Context, fileID, mime string) ([]byte, string, error) {
240	f, err := a.Client.GetFile(ctx, fileID)
241	if err != nil {
242		return nil, "", err
243	}
244	data, err := a.Client.DownloadFile(ctx, f.FilePath)
245	if err != nil {
246		return nil, "", err
247	}
248	if mime == "" {
249		mime = bot.GuessImageMIME(f.FilePath)
250	}
251	return data, mime, nil
252}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 476

↑↓ moveenter openesc close