Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,16 @@ Run `tg` with no arguments.
| `↑` `↓` `j` `k` | Move in the chat list |
| `enter` | Open the chat, or send the message |
| `/` | Filter chats by name |
| `tab` `esc` | Switch between chat list and composer |
| `tab` | Switch between chat list and composer, `esc` goes back to the list |
| `pgup` `pgdn` | Scroll the conversation, older messages load as you go |
| `ctrl+↑` `ctrl+↓` | Pick the message to reply to (`alt` works too) |
| `ctrl+↑` `ctrl+↓` | Pick the message to reply to (`alt` works too, use it on a Mac) |
| `↑` | In an empty composer, edit your last message |
| `esc` | Cancel the reply or the edit |
| `ctrl+v` | Attach the image in the clipboard, the message becomes its caption |
| `ctrl+v` (`cmd+v` on a Mac) | Attach the image in the clipboard, the message becomes its caption |
| `backspace` | Remove the attachment, when the message is empty |
| `q` `ctrl+c` | Quit |
| `ctrl+c` | Clear the composer or cancel the edit, quit when it is empty |
| `esc` | In the chat list, open the settings: theme, spacing, how shortcuts are written |
| `q` | Quit, from the chat list |

The mouse works too: click a chat, scroll either pane, right click a message to reply, edit, copy its text or copy its ID. Copying uses OSC 52, so it also works over SSH; inside tmux it needs `set -g set-clipboard on`. Edits are sent as plain text, so bold and links made in another app are lost, and messages the composer cannot hold as they are (several lines, special characters) are edited elsewhere. New messages arrive live. What you type and leave unsent stays with its chat, shown in the list as a `[draft]`.

Expand All @@ -144,6 +146,10 @@ To send a picture, copy it and paste it into the composer, or press `ctrl+v`, or

`tg config spacing on` sets messages apart in the conversation: a blank line before a new sender, a pause of more than five minutes, or a new day. Off, the default, packs them together. It is stored as `"spaced_messages"` in `config.json`.

Both can also be changed in the settings, with `esc` from the chat list. There "Shortcuts" picks how keys are written: `⌘V` and `⌥↑↓` on a Mac, `ctrl+v` and `ctrl+↑↓` elsewhere. It follows the system tg runs on, so over SSH from a Mac set it once. It is stored as `"keys"` in `config.json`.

Bots' inline buttons are drawn under their messages. Click one to press it, the bot's answer shows at the bottom. A link button copies its link. Buttons that need Telegram's own apps, like games and payments, say so.

### Pictures

Profile pictures, photos, stickers and video previews are drawn in terminals that implement the Kitty graphics protocol with Unicode placeholders: [Kitty](https://sw.kovidgoyal.net/kitty/) and [Ghostty](https://ghostty.org). Animated stickers play in a loop, and with [ffmpeg](https://ffmpeg.org) installed so do video stickers, GIFs and videos up to 6 seconds, muted. Round video messages show their first frame. The terminal animates them on the GPU, and ffmpeg decodes videos on the GPU when it can. A chat without a photo gets a square badge with its initials. Elsewhere the badge is drawn with text, and media shows as `[photo]`, `[sticker 😄]` and so on. Inside tmux, pictures need `set -g allow-passthrough on`. Force them on or off with `TG_IMAGES=1` or `TG_IMAGES=0`.
Expand Down
15 changes: 14 additions & 1 deletion internal/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,20 @@ func (a *app) dispatch(ctx context.Context, args []string) error {
if len(cfg.Accounts) > 1 {
label = name
}
return tui.Run(ctx, be, a.version, label, tui.Look{Theme: cfg.Theme, Spaced: cfg.SpacedMessages})
look := func(f *config.File) tui.Look {
return tui.Look{Theme: f.Theme, Spaced: f.SpacedMessages, Keys: f.Keys}
}
// The settings menu saves one change at a time, over config.json
// as it is then.
save := func(change func(*tui.Look)) error {
return config.Update(func(f *config.File) error {
l := look(f)
change(&l)
f.Theme, f.SpacedMessages, f.Keys = l.Theme, l.Spaced, l.Keys
return nil
})
}
return tui.Run(ctx, be, a.version, label, look(cfg), save)
})
}

Expand Down
8 changes: 6 additions & 2 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,12 @@ type File struct {
Theme string `json:"theme,omitempty"`
// SpacedMessages sets messages apart in the TUI's conversation, see
// `tg config spacing`. Off packs them together.
SpacedMessages bool `json:"spaced_messages,omitempty"`
Accounts map[string]*Account `json:"accounts,omitempty"`
SpacedMessages bool `json:"spaced_messages,omitempty"`
// Keys is how the TUI writes shortcuts: "mac" with ⌥ and ⌘, "pc" with
// alt+ and ctrl+. Empty follows the system tg runs on. The TUI's
// settings menu (esc) sets it.
Keys string `json:"keys,omitempty"`
Accounts map[string]*Account `json:"accounts,omitempty"`
}

// Account is one logged in Telegram account and its guardrails. Both
Expand Down
33 changes: 33 additions & 0 deletions internal/core/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,37 @@ type Message struct {
// PictureSize is the media's size in pixels, zero when unknown. The TUI
// sets room aside for the picture with it, so nothing moves when it loads.
PictureSize image.Point `json:"-"`
// Buttons are a bot's inline keyboard, row by row.
Buttons [][]Button `json:"-"`
}

// ButtonKind tells what pressing a button of a bot's keyboard does.
type ButtonKind uint8

const (
// ButtonOther only works in Telegram's own apps, like a game or a payment.
ButtonOther ButtonKind = iota
// ButtonCallback sends its Value to the bot, see Backend.Press.
ButtonCallback
// ButtonURL opens the link in its Value.
ButtonURL
// ButtonCopy copies its Value.
ButtonCopy
)

// Button is one button of a bot's inline keyboard.
type Button struct {
Text string
Kind ButtonKind
Value string
}

// BotAnswer is what a bot replies to a pressed button: a notice to show and
// a link to open. Either can be empty, a bot often answers by editing its
// message instead.
type BotAnswer struct {
Text string
URL string
}

// MediaPhoto is the Media of a message that carries a photo.
Expand Down Expand Up @@ -172,6 +203,8 @@ type Backend interface {
// posts: front ends offer it only for messages the account sent.
Edit(ctx context.Context, chatID int64, msgID int, text string) error
MarkRead(ctx context.Context, chatID int64, maxID int) error
// Press presses a ButtonCallback of message msgID, data being its Value.
Press(ctx context.Context, chatID int64, msgID int, data string) (BotAnswer, error)
// CreateGroup makes a new group with only the account in it.
CreateGroup(ctx context.Context, title string) (Chat, error)
Search(ctx context.Context, q SearchQuery) ([]Message, error)
Expand Down
8 changes: 8 additions & 0 deletions internal/core/guard.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,14 @@ func (g *guarded) Edit(ctx context.Context, chatID int64, msgID int, text string
return g.Backend.Edit(ctx, chatID, msgID, text)
}

// Press is checked like sending: the bot acts on it as on a message.
func (g *guarded) Press(ctx context.Context, chatID int64, msgID int, data string) (BotAnswer, error) {
if err := g.check("pressing buttons", chatID); err != nil {
return BotAnswer{}, err
}
return g.Backend.Press(ctx, chatID, msgID, data)
}

func (g *guarded) MarkRead(ctx context.Context, chatID int64, maxID int) error {
if err := g.check("marking as read", chatID); err != nil {
return err
Expand Down
12 changes: 10 additions & 2 deletions internal/core/guard_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,18 @@ func (w *writes) Send(context.Context, int64, SendRequest) (Message, error) {
}
func (w *writes) Edit(context.Context, int64, int, string) error { w.n++; return nil }
func (w *writes) MarkRead(context.Context, int64, int) error { w.n++; return nil }
func (w *writes) Press(context.Context, int64, int, string) (BotAnswer, error) {
w.n++
return BotAnswer{}, nil
}
func (w *writes) CreateGroup(context.Context, string) (Chat, error) {
w.n++
return Chat{}, nil
}

// attempt tries every kind of write on chatID and reports which were refused.
// Editing follows the same rules as sending, so it is reported with it.
// Editing and pressing buttons follow the same rules as sending, so they are
// reported with it.
func attempt(t *testing.T, policy Policy, chatID int64) (send, read, group bool, reached int) {
t.Helper()
backend := &writes{}
Expand All @@ -43,6 +48,9 @@ func attempt(t *testing.T, policy Policy, chatID int64) (send, read, group bool,
if edit := refused(g.Edit(context.Background(), chatID, 1, "x")); edit != send {
t.Errorf("chat %d: editing refused=%v, sending refused=%v", chatID, edit, send)
}
if _, err := g.Press(context.Background(), chatID, 1, "x"); refused(err) != send {
t.Errorf("chat %d: pressing refused=%v, sending refused=%v", chatID, refused(err), send)
}
read = refused(g.MarkRead(context.Background(), chatID, 1))
_, err = g.CreateGroup(context.Background(), "g")
group = refused(err)
Expand All @@ -69,7 +77,7 @@ func TestGuard(t *testing.T) {
t.Errorf("%s: refused send=%v read=%v group=%v", c.name, send, read, group)
}
allowed := 0
for _, refused := range []bool{c.send, c.send, c.read, c.group} { // send twice: edit too
for _, refused := range []bool{c.send, c.send, c.send, c.read, c.group} { // edit and press follow send
if !refused {
allowed++
}
Expand Down
31 changes: 29 additions & 2 deletions internal/demo/demo.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,14 @@ type fixture struct {
lines []string // "<minutes ago>|<sender, empty for self>|<text>"
}

// keyboards are the inline keyboards of the last message of bot chats.
var keyboards = map[int64][][]core.Button{
104: {
{{Text: "@weather_demo_bot", Kind: core.ButtonCallback, Value: "edit:1"}, {Text: "@build_demo_bot", Kind: core.ButtonCallback, Value: "edit:2"}},
{{Text: "Bot API docs", Kind: core.ButtonURL, Value: "https://core.telegram.org/bots/api"}},
},
}

var fixtures = []fixture{
{core.Chat{ID: 101, Kind: core.KindUser, Title: "Alice Rossi", Username: "alice", Unread: 2, Pinned: true, PhotoID: 1}, []string{
"190|Alice Rossi|hey, are we still on for tomorrow?",
Expand Down Expand Up @@ -97,8 +105,8 @@ var fixtures = []fixture{
"340|Papà|[photo]",
}},
{core.Chat{ID: 104, Kind: core.KindBot, Title: "BotFather", Username: "BotFather", PhotoID: 6}, []string{
"8000||/newbot",
"7999|BotFather|Alright, a new bot. How are we going to call it?",
"8000||/mybots",
"7999|BotFather|Choose a bot from the list below:",
}},
{core.Chat{ID: 1000, Kind: core.KindUser, Title: "Saved Messages"}, []string{
"9000||wifi guest password: correct horse battery staple",
Expand Down Expand Up @@ -143,6 +151,7 @@ func New() *Backend {
}
chat := f.chat
msgs := b.messages[chat.ID]
msgs[len(msgs)-1].Buttons = keyboards[chat.ID]
chat.Last = &msgs[len(msgs)-1]
b.chats = append(b.chats, chat)
}
Expand Down Expand Up @@ -269,6 +278,24 @@ func (b *Backend) Edit(_ context.Context, chatID int64, msgID int, text string)
return nil
}

// Press answers with the label of the button, as a bot would with a notice.
func (b *Backend) Press(_ context.Context, chatID int64, msgID int, data string) (core.BotAnswer, error) {
b.mu.Lock()
defer b.mu.Unlock()
i := slices.IndexFunc(b.messages[chatID], func(m core.Message) bool { return m.ID == msgID })
if i < 0 {
return core.BotAnswer{}, fmt.Errorf("no message %d in chat %d", msgID, chatID)
}
for _, row := range b.messages[chatID][i].Buttons {
for _, button := range row {
if button.Kind == core.ButtonCallback && button.Value == data {
return core.BotAnswer{Text: "Editing " + button.Text}, nil
}
}
}
return core.BotAnswer{}, fmt.Errorf("message %d has no such button", msgID)
}

func (b *Backend) MarkRead(_ context.Context, chatID int64, _ int) error {
b.mu.Lock()
defer b.mu.Unlock()
Expand Down
18 changes: 18 additions & 0 deletions internal/mtp/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"github.com/gotd/td/telegram/updates"
"github.com/gotd/td/telegram/uploader"
"github.com/gotd/td/tg"
"github.com/gotd/td/tgerr"

"github.com/RealDoc06/tg-cli/internal/config"
"github.com/RealDoc06/tg-cli/internal/core"
Expand Down Expand Up @@ -296,6 +297,23 @@ func (b *backend) Edit(ctx context.Context, chatID int64, msgID int, text string
return err
}

func (b *backend) Press(ctx context.Context, chatID int64, msgID int, data string) (core.BotAnswer, error) {
peer, err := b.peers.input(chatID)
if err != nil {
return core.BotAnswer{}, err
}
res, err := b.api.MessagesGetBotCallbackAnswer(ctx, &tg.MessagesGetBotCallbackAnswerRequest{
Peer: peer, MsgID: msgID, Data: []byte(data),
})
if tgerr.Is(err, "BOT_RESPONSE_TIMEOUT") {
return core.BotAnswer{}, nil // the bot got it, and may answer by editing its message
}
if err != nil {
return core.BotAnswer{}, err
}
return core.BotAnswer{Text: res.Message, URL: res.URL}, nil
}

func (b *backend) MarkRead(ctx context.Context, chatID int64, maxID int) error {
peer, err := b.peers.input(chatID)
if err != nil {
Expand Down
26 changes: 26 additions & 0 deletions internal/mtp/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@ func (b *backend) message(raw tg.MessageClass, e tg.Entities) (core.Message, boo
Edited: m.EditDate != 0 && !m.EditHide,
}
out.Media, out.Picture, out.PictureSize = mediaSummary(m.Media)
if markup, ok := m.ReplyMarkup.(*tg.ReplyInlineMarkup); ok {
for _, row := range markup.Rows {
buttons := make([]core.Button, len(row.Buttons))
for i, button := range row.Buttons {
buttons[i] = buttonOf(button)
}
out.Buttons = append(out.Buttons, buttons)
}
}
if reply, ok := m.ReplyTo.(*tg.MessageReplyHeader); ok && !reply.ForumTopic {
out.ReplyTo = reply.ReplyToMsgID
}
Expand All @@ -38,6 +47,23 @@ func (b *backend) message(raw tg.MessageClass, e tg.Entities) (core.Message, boo
return core.Message{}, false
}

// buttonOf converts a button of an inline keyboard. A callback button that
// asks for the account's password is left to Telegram's own apps.
func buttonOf(button tg.KeyboardInlineButton) core.Button {
out := core.Button{Text: button.Text}
switch t := button.Type.(type) {
case *tg.InlineButtonTypeCallback:
if !t.RequiresPassword {
out.Kind, out.Value = core.ButtonCallback, string(t.Data)
}
case *tg.InlineButtonTypeURL:
out.Kind, out.Value = core.ButtonURL, t.URL
case *tg.InlineButtonTypeCopy:
out.Kind, out.Value = core.ButtonCopy, t.CopyText
}
return out
}

// author works out who wrote a message. Private chats and channel posts omit
// the sender, which is then implied by the chat and the direction.
func (b *backend) author(from, chat tg.PeerClass, out bool, e tg.Entities) (int64, string) {
Expand Down
Loading
Loading