telegram-sync-cli · Installs the tg command
A Telegram CLI
for you and your agents.
Search your Telegram messages offline, query them with SQL, read a chat’s history, send messages and files, download attachments or call any Telegram API method from your shell. tg logs in to your own account and saves your messages to a local SQLite cache. Commands answer in JSON by default.
brew install neoromantic/ tap/ tgmacOS and Linux. You also need your own Telegram API ID and hash. Setup
Free · Open source · What’s new in 0.16.0
zsh
$ tg messages search --query "lisbon" \
| jq -r '.data.results[]
| "\(.chat.title) · \(.text)"'
Ana Ribeiro · Flights to Lisbon are cheaper on the 14thTomás Klein · I left the climbing shoes in Lisbon, can you grab them?Maya Chen · Lisbon or Porto for the offsite?$ - Search and SQL, offline
A read-only daemon saves your messages to a local cache. Search them or query them with SQL, with no API calls.
- Any Telegram API method
tg sendfor text and files,tg media downloadfor attachments,tg api <method>for everything else. - Made for agents
Commands print JSON, and errors carry a code. Any agent that can run a shell command can use tg.
Local cache
Search your messages
and query them with SQL.
Each account’s messages go into its own SQLite database in ~/.telegram-sync-cli. Search and SQL read from it, so they work offline and make no API calls.
zsh
$ tg sql --output csv --query "
SELECT c.title AS chat,
COUNT(*) AS messages
FROM messages_cache m
JOIN chats_cache c
ON c.chat_id = m.chat_id
WHERE c.type = 'private'
GROUP BY chat
ORDER BY messages DESC"
chat,messages
Ana Ribeiro,3
Maya Chen,2
Tomás Klein,1- Full-text search
- Find words, phrases and prefixes in every cached message, newest first or by relevance, and filter by date.
- Read-only SQL
tg sqlruns SELECT queries over one account’s cache and returns JSON or CSV. Queries run on a read-only connection, so they can’t change the cache.tg sql print-schemadescribes every table, and--tabledescribes its columns.- Cached reads, or
--fresh tg messages list --chatpages through a chat’s history, newest first. History, contacts, chats and users come from the cache when it has them, and--freshasks Telegram instead. Each message shows its attachment, if it has one. On service messages,actiontells you what happened, such as a missed call or a pinned message.
Sync daemon
The daemon saves your messages
and never sends anything.
Run tg daemon start and leave it running in tmux or as a service. It syncs every account you’re logged in to, reads from Telegram and writes only to your local cache.
- On start
- It loads your chat list, then catches up your private chats and small groups: the newest 100 messages the first time, or everything that arrived while the daemon was stopped. It catches up again after a reconnect.
- While it runs
- Every new message is saved as it arrives, in every chat, including large groups and channels. Edits update the saved copy. A deletion only sets a flag, so
--includeDeletedstill finds the message. Your contact list stays current too. - Older history
- Fetched in the background, page by page, back to each chat’s first message. Large groups and channels get it once you turn them on with
tg chats sync <chat>. - Cache size
- Messages stay. The daemon prunes old API activity, expired rate-limit windows and old sync jobs on a schedule.
tg statusshows each account’s cache size, andtg db vacuumgives free space back to the disk.
tg send · tg media · tg api
Send text and files,
or call any API method.
Built-in commands cover search, contacts, chats, sending messages and files, and downloading attachments. For everything else, tg api calls a Telegram API method by name and prints the result as JSON.
zsh
$ tg api account.checkUsername \
--username=myuser
{
"success": true,
"data": {
"method": "account.checkUsername",
"result": false
}
}- tg send
- Text to an @username, a user ID, a phone number or
mefor Saved Messages, with--reply-toand--silent.--filesends one file with an optional--caption: a JPEG, PNG or WebP image up to 10 MB as a photo, anything else as a document. The sent message goes into the cache right away. - tg media download
- Saves a message’s file to the account’s media cache and prints its path;
--outcopies it where you want. A cached file needs no network, and a partial download resumes. Media from chats with content protection is refused.tg media clean --allempties the cache. - tg api <method>
- Arguments are the method’s raw fields: flags such as
--username=myuser, or a--jsonobject for nested ones.
For AI agents
Agents get JSON
and an exit code.
Results go to stdout as JSON. Errors go to stderr as JSON with an error code and whether a retry can work. Paged reads suggest the next command with the same account and filters. Any agent that can run shell commands can use tg, with no MCP server or plugin.
zsh
$ tg me
{
"success": false,
"error": {
"code": "AUTH_REQUIRED",
"message": "No account found. Please log in first with \"tg auth login\"", "suggestion": "Log in with tg auth login", "retryable": false
}
}
$ echo $?
2- Learn tg before you log in
tg --help,tg --versionandtg sql print-schemaneed no account and no API credentials, so an agent can learn the commands and the cache schema first.- Flood waits
- A command waits out Telegram flood waits of up to 60 seconds. A longer one returns
RATE_LIMITEDwithwait_seconds, on that call and on later calls until it ends. - Read a chat page by page
- Each
tg messages listpage carriesnextBeforeandnextAfter, so an agent can walk a chat.tg messages get --context 5opens a search hit with the messages around it. - Wait for a reply
tg messages waitreturns new messages as soon as the daemon stores them.tg messages unreadprints unread ones, andtg messages readmarks a chat read.
Get started
Set it up
in four steps.
Install tg
brew install neoromantic/tap/ tg Copy to clipboardOr with Bun 1.4 or newer:
bun i -g @goodit/telegram-sync-cli Copy to clipboardAdd your API credentials
export TELEGRAM_API_ID=123456export TELEGRAM_API_HASH=your_api_hashCopy to clipboardCreate them at my.telegram.org/apps. Put the exports in your shell profile so the daemon sees them too.
If Telegram is blocked, set
TELEGRAM_PROXYto a SOCKS5, HTTP or MTProxy URL for the CLI and daemon. Proxy setup ↗Log in
tg auth login-qrCopy to clipboardScan the code in Telegram on your phone: Settings → Devices → Link Desktop Device. Or log in by phone with
tg auth login --phone +15550000000.Start the daemon, then search
tg daemon startCopy to clipboardLeave it running. In another terminal:
tg messages search --query "lisbon"Copy to clipboardSearch covers what the daemon has saved so far.
tg statusshows its progress, any failed sync jobs and the cache size.
Privacy & data
Your session and cache
stay on your machine.
Usage stats. Since 0.7.0 tg sends its author usage stats: how often it runs, which commands run, which errors come up, the version and the OS, with a random install ID. Never messages, names, phone numbers, IDs or queries. Nothing is sent before tg has shown a one-line notice, and tg telemetry off turns it off. Everything it sends ↗
Local files. Sessions, caches and settings live in ~/.telegram-sync-cli, or wherever TELEGRAM_SYNC_CLI_DATA_DIR points. tg reads your API ID and hash from the environment and connects to Telegram directly or through your configured proxy.
Deleted messages stay. A message already in your cache stays there after it is deleted in Telegram. Delete the data directory to remove everything.
This website uses cookieless PostHog analytics for page visits, link clicks and the steps a browser’s AI agent takes on its controls: the kind of control, the action and whether it was allowed, and whether the browser offers the page to its agent at all. Session recording is off. Website analytics are separate from tg and never see your Telegram data.
Questions
Before you log in.
No. It’s an independent open-source client built on mtcute. It logs in as you, with an API ID and hash you create at my.telegram.org/apps.
Yes, if it can run tg send or tg api, unless read-only mode is on: TELEGRAM_SYNC_CLI_READ_ONLY=1 or readOnly in config.json refuses every command that changes Telegram. allowedChats keeps it to the chats you list. Both guard against mistakes; they are not a sandbox. The daemon and tg sql never send, edit or delete anything.
Run tg messages list --chat @username. It returns the newest messages first, and --before and --after page through the rest. tg messages get with --id and --context 5 shows one message with up to five on each side. Both read the cache first and ask Telegram for what it doesn’t hold.
Yes. tg send --file sends one file, an image as a photo and anything else as a document. tg media download saves a message’s file to a local media cache and resumes a partial download. Message lists show each attachment’s kind, name, MIME type and size.
telegram-mcp is an MCP server with a fixed set of tools that call Telegram live. tg keeps a local cache you can search and query with SQL, and tg api calls any API method. tg is behind on sending albums and voice messages. The README has the full comparison.
Yes. Log in to each, then pick one with tg accounts switch or --account. Each account has its own cache, so search and SQL see one account at a time. The daemon syncs every account you’re logged in to, each on its own, so a flood wait in one account doesn’t hold the others.