Skip to content
Proyectos

Acerca de

Cliente de Telegram para terminal: TUI, CLI y una skill de agente

Herramientas de desarrollo

Cómo se miden estas cifras

What you can do

  • hooks: scripts that add notes under msgs, e.g. transcribe voice msgs locally or describe photos and stickers with a model
  • command palette: ; lists every command of the pane in fzf, so you don't need to remember keys
  • background player for voice msgs and music: starts while still downloading, next/prev, seek, speed (voice speed is remembered, 1.5× by default)
  • record and send voice msgs from your default mic

Crecimiento de estrellas medido

in 24h
0
in 7 days
+2
in 15 days
+5
in 1 month
+5

Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.

README.md

Original

tg

Join telegram chat

Telegram terminal client: TUI, CLI and an agent skill

tg                   # the TUI
tg unread [--json]   # unread messages as plain text, for scripts and agents
tg skill install     # teach Claude Code to use it

More in Command line and agents.

tg screenshot

Features

  • hooks: scripts that add notes under msgs, e.g. transcribe voice msgs locally or describe photos and stickers with a model
  • command palette: ; lists every command of the pane in fzf, so you don't need to remember keys
  • background player for voice msgs and music: starts while still downloading, next/prev, seek, speed (voice speed is remembered, 1.5× by default)
  • record and send voice msgs from your default mic
  • attach files with yazi, ranger or nnn: pictures, documents, audio, video, several at once
  • secret chats and new groups
  • reactions: shown under msgs, react with +, notified when someone reacts to yours
  • bot buttons: press them with x
  • reply, edit, forward, delete, send messages, write long ones in vim
  • view media: photos, videos, voice/video notes, documents, stickers, polls, link previews
  • mouse: click a chat to open it, scroll with the wheel
  • Nerd Font or emoji icons for message kinds and chat flags, chat names colored by type (group, channel, secret, bot)
  • notifications, unread count in the terminal title
  • pin/unpin, mark as read/unread, mute/unmute chats, find a chat by name with fzf
  • contacts, user status and info
  • command line and agent skill: unread, history, search, download, send (close the TUI first)
  • vim keys that also work in the Russian layout (Ukrainian with KEY_ALIASES)
  • QR code login

Requirements

To use tg, you'll need to have the following installed:

Optional dependencies

  • terminal-notifier - for Mac (used by default). You can change it to dunst for Linux or any other notifications program (see NOTIFY_CMD in configuration)
  • ffmpeg - to record voice msgs and upload videos.
  • tdlib - only if the TDLib bundled with python-telegram doesn't work on your platform. Build it and set TDLIB_PATH in config (or PYTHON_TELEGRAM_TDLIB_PATH env var). Homebrew's tdlib is too old.
  • urlview to choose urls when there is multiple in message, use URL_VIEW in config file to use another app (it should accept urls in stdin)
  • to open stickers and animated ones (thumbnail preview) you need to set in mailcap appropriate handler and have app which will open webp file:
    image/webp; mpv %s
    
  • yazi, ranger, nnn - choose files to send (the first one installed is used, otherwise you type a path), customizable with FILE_PICKER_CMD
  • fzf - to create groups and secret chats (used for single and multiple user selection)
  • arabic-reshaper, python-bidi - to render Arabic/Persian text in terminals without native BiDi support: pip install "tg[rtl]" and set RTL_RESHAPE = True in config. Leave it off if your terminal already handles BiDi, otherwise text gets reversed twice.

Installation

From PyPI

This option is recommended for production:

pip3 install tg
tg

Or install it as an isolated tool with pipx or uv:

pipx install tg
uv tool install tg

From sources

This option is recommended for development:

git clone https://github.com/paul-nameless/tg.git
cd tg
pip install .
tg

Using Docker

Note that voice recordings and notifications won't work when using Docker.

docker run -it --rm ghcr.io/paul-nameless/tg

Command line and agents

Besides the TUI, tg has commands that print compact text (or JSON with --json) and exit, so scripts and AI agents can read your Telegram.

tg skill install copies a skill file that teaches agents these commands to ~/.claude/skills/tg/SKILL.md (Claude Code) and ~/.agents/skills/tg/SKILL.md (Codex, opencode). Pick one with --agent claude|codex|opencode.

tg unread                        # unread chats with their newest unread messages
tg chats --unread                # list chats
tg history @alice --limit 50     # messages of a chat
tg search "invoice" --chat me    # search messages
tg download @alice 12345 --out ~/Downloads
tg mark-read @alice
tg send @alice "on my way"       # disabled unless CLI_SEND = True
tg watch --count 1 --timeout 600  # wait for the next new message
tg whoami
tg help                          # all commands; tg <command> -h for flags
  • Commands use the same session as the TUI, so close the TUI first (they exit with code 6 while it runs). Log in once with tg login or by starting the TUI.
  • Reading never marks messages as read. Sending is off by default; enable it in conf.py with CLI_SEND = True, and optionally limit it with CLI_SEND_ALLOWLIST = ["@alice", 12345].
  • TG_API_ID and TG_API_HASH env vars override API_ID/API_HASH.

Configuration

Config file should be stored at ~/.config/tg/conf.py. This is simple python file.

Simple config:

# should start with + (plus) and contain country code
PHONE = "[phone number in international format]"

Advanced configuration:

All configurable variables can be found here

import os


# You can write anything you want here, file will be executed at start time
# You can keep you sensitive information in password managers or gpg
# encrypted files for example
def get_pass(key):
    # retrieves key from password store
    return os.popen("pass show {} | head -n 1".format(key)).read().strip()


PHONE = get_pass("i/telegram-phone")
# encrypt you local tdlib database with the key
ENC_KEY = get_pass("i/telegram-enc-key")

# log level for debugging, info by default
LOG_LEVEL = "DEBUG"
# path where logs will be stored (all.log and error.log)
LOG_PATH = os.path.expanduser("~/.local/share/tg/")

# If you have problems with tdlib shipped with the client, you can install and
# use your own, for example:
TDLIB_PATH = "/path/to/libtdjson.dylib"

# you can use any other notification cmd, it is simple python string which
# can format title, msg, subtitle and icon_path paramters
# In these exapmle, kitty terminal is used and when notification is pressed
# it will focus on the tab of running tg
NOTIFY_CMD = "terminal-notifier -title {title} -subtitle {subtitle} -message {msg} -appIcon {icon_path} -sound default -execute '/Applications/kitty.app/Contents/MacOS/kitty @ --to unix:/tmp/kitty focus-tab --no-response -m title:tg'"

# You can use your own voice recording cmd but it's better to use default one.
# The voice note must be encoded with the Opus codec, and stored inside an OGG
# container. Voice notes can have only a single audio channel.
VOICE_RECORD_CMD = (
    "ffmpeg -f avfoundation -i ':default' -c:a libopus -b:a 32k {file_path}"
)

# Chat and message flags and the icon left of media messages default to plain
# Unicode and emoji (all listed in tg/icons.py). Override any of them, e.g.
# one letter like mutt ("pinned": "P") or an empty string to hide one.
# Nerd Font icons look sharper: Ghostty, kitty and WezTerm draw them out of
# the box, other terminals need a Nerd Font installed
from tg.icons import NERD_CHAT_FLAGS, NERD_MSG_FLAGS, NERD_MSG_KIND_GLYPHS

CHAT_FLAGS = NERD_CHAT_FLAGS
MSG_FLAGS = NERD_MSG_FLAGS
MSG_KIND_GLYPHS = NERD_MSG_KIND_GLYPHS
# MSG_FLAGS = {**NERD_MSG_FLAGS, "seen": ""}  # Nerd icons, but hide "seen"

# click a chat to switch to it, scroll messages and chats with the wheel;
# while it's on, hold Shift (Option in some terminals) to select text
MOUSE = True

# play voice messages and audio files in the background with ffplay (part of
# ffmpeg), starting while they download; PLAYER_KEY opens the player menu:
# <Space> pause, n/p or j/k next/prev, h/l seek 10s, -/+ speed by 0.1,
# g go to the message, s stop. Voice speed is remembered, music plays at 1x.
# False opens them via mailcap instead
BACKGROUND_AUDIO = True
VOICE_SPEED = 1.5
PLAYER_KEY = "."

# opens the command palette in fzf
PALETTE_KEY = ";"

# use this app to open url when there are multiple
URL_VIEW = "urlview"

# colors for people's names; None draws every name in one color (blue),
# a tuple picks a color per person by their name
USERS_COLORS = None

# rainbow names with the base 16 colors
# USERS_COLORS = tuple(range(2, 16))

# to use 256 colors, set range appropriately
# though 233 looks better, because last colors are black and gray
# USERS_COLORS = tuple(range(233))

# color for your own name and Saved Messages, None colors it like others
MY_COLOR = 10

# chat list title colors by chat type: "group", "channel", "secret", "bot",
# "private"; types left out use the name colors above
CHAT_TYPE_COLORS = {"group": 13, "channel": 11, "secret": 9, "bot": 14}

# cleanup cache
# Values: N days, None (never)
KEEP_MEDIA = 7

FILE_PICKER_CMD = "yazi --chooser-file={file_path}"
# FILE_PICKER_CMD = "ranger --choosefiles={file_path}"
# FILE_PICKER_CMD = "nnn -p {file_path}"

MAILCAP_FILE = os.path.expanduser("~/.config/mailcap")

DOWNLOAD_DIR = os.path.expanduser("~/Downloads/")  # copy file to this dir

# date shown between messages of different days, e.g. "%m/%d/%Y" or "%x" for your locale
DATE_FORMAT = "%d.%m.%Y"
TODAY_LABEL = "Today"  # e.g. "Hoy", "Сегодня"

# title of the chat with yourself
SAVED_MESSAGES = "Saved Messages"

# hooks run for the open chat: they get its last msgs as JSON on stdin and
# print {"type": "note", "msg_id": 123, "text": "..."} lines shown under msgs
HOOKS = [
    {
        "cmd": "~/.config/tg/hooks/tldr.py",
        "types": ["voice", "recording", "photo", "sticker"],
        "timeout": 600,
    },
]

# terminal title, None leaves it alone. TERMINAL_TITLE_UNREAD is used while
# something is unread: {unread} is the number of unread chats, {last_event} the
# newest unread message or reaction to yours ("Bob: hi", "Bob 👍 «msg»"), it goes
# away once read. An empty field drops with its separator, remove a field to hide it
TERMINAL_TITLE = "tg"
TERMINAL_TITLE_UNREAD = "tg • {unread} • {last_event:.40}"
# run a shell command with the title instead of setting the terminal's: the
# title is "$1", empty when tg quits
# TERMINAL_TITLE_CMD = 'tmux rename-window -t "$TMUX_PANE" "${1:-tg}"'

# show the chat list next to messages, toggle with z
CHAT_LIST_IN_MSGS = True

# chat list width next to messages, in percent of the screen (0-80, 0 hides it)
CHAT_LIST_WIDTH = 25

# lines per chat in the chat list: 2 puts the preview under the title, 1 is compact
CHAT_ROWS = 2

# highlight of the selected chat/message: reverse, bold, underline, dim, standout,
# bg:N for a background color (0-255, e.g. "bg:236" for dark grey), or combined like "bg:236+bold"
SELECTED_STYLE = "reverse"

# background color (0-255) of reactions under messages, None for no background
REACTION_BG = 238
# background of your own reactions
REACTION_MINE_BG = 24

# fzf command of all pickers (f, +, x, ng, ns)
FZF = "fzf --layout=reverse"

# extra fzf options of the bot button picker (x)
BUTTON_FZF_OPTS = (
    "--layout=reverse --border=rounded --prompt='number or search, Enter › '"
)

# collapse longer messages unless selected, None shows them in full
MSG_MAX_LINES = 10

# reshape Arabic/Persian text for terminals without BiDi support (needs tg[rtl])
RTL_RESHAPE = False

# key aliases: pressing the key on the left acts as the key on the right
KEY_ALIASES = {"о": "j", "л": "k"}

Mailcap file

Mailcap file is used for deciding how to open telegram files (docs, pics, voice notes, etc.). Path to the file can be overriden with MAILCAP_FILE in config file.

Example: ~/.mailcap

# media
video/*; mpv "%s"
audio/ogg; mpv --speed=1.33 "%s"
audio/mpeg; mpv --no-video "%s"
image/*; qview "%s"

# text
text/html; w3m "%s"
text/html; open -a Firefox "%s"
text/plain; less "%s"

# fallback to vim
text/*; vim "%s"

Keybindings

vi like keybindings are used in the project. Can be used commands like 4j - 4 lines down.

For navigation arrow keys also can be used.

Press ? in the chats or msgs pane to see all keys, or ; to pick a command in fzf and run it (PALETTE_KEY in the config). To add key aliases, set KEY_ALIASES in the configuration.

Chats:

  • j,k: move up/down
  • J,K: move 10 chats up/down
  • g: go to top chat
  • l: open msgs of the chat
  • m: mute/unmute current chat
  • p: pin/unpin current chat
  • u: mark read/unread
  • r: read current chat and the reactions to your msgs in it (opening a chat reads its reactions too)
  • c: show list of contacts
  • dd: delete chat or remove history
  • Cg: create new group chat
  • Cs: create new secret chat
  • /: search in chats
  • f: find a loaded chat by name in fzf and go to it (also works in msgs)
  • ?: show help
  • ;: pick a command in fzf and run it

Msgs:

  • j,k: move up/down
  • J,K: move 10 msgs up/down
  • G: move to the last msg (at the bottom)
  • z: show/hide the chat list
  • D: download file
  • l: if video, pics or audio then open app specified in mailcap file, for example:
    # Images
    image/png; qView "%s"
    audio/*; mpv "%s"
    
    if text, open in less (to view multiline msgs)
  • e: edit current msg
  • <space>: select msg and jump one msg down (use for deletion or forwarding)
  • <ctrl+space>: same as space but jumps one msg up
  • y: yank (copy) selected msgs with to internal buffer (for forwarding) and copy current msg text or path to file to clipboard
  • p: forward (paste) yanked (copied) msgs to current chat
  • dd: delete msg for everybody (multiple messages will be deleted if selected)
  • i: type and send one message
  • a: type messages one after another (input stays open after each send, Esc or empty Enter to stop)
  • I or A: open vim to write long msg and send
  • v: record and send voice message
  • r,R: reply to a current msg
  • S: calls a file picker
  • sv: send video
  • sa: send audio
  • sp: send picture
  • sd: send document
  • o: open url present in message (if multiple urls, urlview will be opened)
  • x: press a bot button of the msg, choose it in fzf by its number or text, or with arrows, then Enter; bot buttons are drawn under the msg like reactions
  • +: react to msg, choose an emoji in fzf (choose your reaction again to remove it)
  • ]: next chat
  • [: prev chat
  • u: show user info (username, bio, phone, etc.)
  • c: show chat info (e.g. secret chat encryption key, chat id, state, etc.)
  • ?: show help
  • ;: pick a command in fzf and run it
  • !: open msg with custom cmd

Publish

Run task to automatically increase version and release (https://taskfile.dev):

task release

Explorar proyectos relacionados

Cargando…