Metadata-Version: 2.4
Name: kabi-tg-cli
Version: 0.5.1
Summary: Telethon-powered Telegram CLI for local sync, search, and agent-friendly retrieval
Project-URL: Homepage, https://github.com/jackwener/tg-cli
Project-URL: Repository, https://github.com/jackwener/tg-cli
Project-URL: Issues, https://github.com/jackwener/tg-cli/issues
Author-email: jackwener <jakevingoo@gmail.com>
License: Apache License
        Version 2.0, January 2004
        http://www.apache.org/licenses/
        
        TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
        1. Definitions.
        
        "License" shall mean the terms and conditions for use, reproduction, and
        distribution as defined by Sections 1 through 9 of this document.
        
        "Licensor" shall mean the copyright owner or entity authorized by the copyright
        owner that is granting the License.
        
        "Legal Entity" shall mean the union of the acting entity and all other entities
        that control, are controlled by, or are under common control with that entity.
        For the purposes of this definition, "control" means (i) the power, direct or
        indirect, to cause the direction or management of such entity, whether by
        contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
        outstanding shares, or (iii) beneficial ownership of such entity.
        
        "You" (or "Your") shall mean an individual or Legal Entity exercising
        permissions granted by this License.
        
        "Source" form shall mean the preferred form for making modifications, including
        but not limited to software source code, documentation source, and configuration
        files.
        
        "Object" form shall mean any form resulting from mechanical transformation or
        translation of a Source form, including but not limited to compiled object code,
        generated documentation, and conversions to other media types.
        
        "Work" shall mean the work of authorship, whether in Source or Object form,
        made available under the License, as indicated by a copyright notice that is
        included in or attached to the work (an example is provided in the Appendix
        below).
        
        "Derivative Works" shall mean any work, whether in Source or Object form, that
        is based on (or derived from) the Work and for which the editorial revisions,
        annotations, elaborations, or other modifications represent, as a whole, an
        original work of authorship. For the purposes of this License, Derivative Works
        shall not include works that remain separable from, or merely link (or bind by
        name) to the interfaces of, the Work and Derivative Works thereof.
        
        "Contribution" shall mean any work of authorship, including the original version
        of the Work and any modifications or additions to that Work or Derivative Works
        thereof, that is intentionally submitted to Licensor for inclusion in the Work
        by the copyright owner or by an individual or Legal Entity authorized to submit
        on behalf of the copyright owner. For the purposes of this definition,
        "submitted" means any form of electronic, verbal, or written communication sent
        to the Licensor or its representatives, including but not limited to
        communication on electronic mailing lists, source code control systems, and
        issue tracking systems that are managed by, or on behalf of, the Licensor for
        the purpose of discussing and improving the Work, but excluding communication
        that is conspicuously marked or otherwise designated in writing by the copyright
        owner as "Not a Contribution."
        
        "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
        of whom a Contribution has been received by Licensor and subsequently
        incorporated within the Work.
        
        2. Grant of Copyright License. Subject to the terms and conditions of this
        License, each Contributor hereby grants to You a perpetual, worldwide,
        non-exclusive, no-charge, royalty-free, irrevocable copyright license to
        reproduce, prepare Derivative Works of, publicly display, publicly perform,
        sublicense, and distribute the Work and such Derivative Works in Source or
        Object form.
        
        3. Grant of Patent License. Subject to the terms and conditions of this License,
        each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
        no-charge, royalty-free, irrevocable (except as stated in this section) patent
        license to make, have made, use, offer to sell, sell, import, and otherwise
        transfer the Work, where such license applies only to those patent claims
        licensable by such Contributor that are necessarily infringed by their
        Contribution(s) alone or by combination of their Contribution(s) with the Work
        to which such Contribution(s) was submitted. If You institute patent litigation
        against any entity (including a cross-claim or counterclaim in a lawsuit)
        alleging that the Work or a Contribution incorporated within the Work constitutes
        direct or contributory patent infringement, then any patent licenses granted to
        You under this License for that Work shall terminate as of the date such
        litigation is filed.
        
        4. Redistribution. You may reproduce and distribute copies of the Work or
        Derivative Works thereof in any medium, with or without modifications, and in
        Source or Object form, provided that You meet the following conditions:
        
        (a) You must give any other recipients of the Work or Derivative Works a copy of
        this License; and
        
        (b) You must cause any modified files to carry prominent notices stating that
        You changed the files; and
        
        (c) You must retain, in the Source form of any Derivative Works that You
        distribute, all copyright, patent, trademark, and attribution notices from the
        Source form of the Work, excluding those notices that do not pertain to any part
        of the Derivative Works; and
        
        (d) If the Work includes a "NOTICE" text file as part of its distribution, then
        any Derivative Works that You distribute must include a readable copy of the
        attribution notices contained within such NOTICE file, excluding those notices
        that do not pertain to any part of the Derivative Works, in at least one of the
        following places: within a NOTICE text file distributed as part of the
        Derivative Works; within the Source form or documentation, if provided along
        with the Derivative Works; or, within a display generated by the Derivative
        Works, if and wherever such third-party notices normally appear. The contents of
        the NOTICE file are for informational purposes only and do not modify the
        License. You may add Your own attribution notices within Derivative Works that
        You distribute, alongside or as an addendum to the NOTICE text from the Work,
        provided that such additional attribution notices cannot be construed as
        modifying the License.
        
        You may add Your own copyright statement to Your modifications and may provide
        additional or different license terms and conditions for use, reproduction, or
        distribution of Your modifications, or for any such Derivative Works as a whole,
        provided Your use, reproduction, and distribution of the Work otherwise complies
        with the conditions stated in this License.
        
        5. Submission of Contributions. Unless You explicitly state otherwise, any
        Contribution intentionally submitted for inclusion in the Work by You to the
        Licensor shall be under the terms and conditions of this License, without any
        additional terms or conditions. Notwithstanding the above, nothing herein shall
        supersede or modify the terms of any separate license agreement you may have
        executed with Licensor regarding such Contributions.
        
        6. Trademarks. This License does not grant permission to use the trade names,
        trademarks, service marks, or product names of the Licensor, except as required
        for reasonable and customary use in describing the origin of the Work and
        reproducing the content of the NOTICE file.
        
        7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
        writing, Licensor provides the Work (and each Contributor provides its
        Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
        KIND, either express or implied, including, without limitation, any warranties
        or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        PARTICULAR PURPOSE. You are solely responsible for determining the
        appropriateness of using or redistributing the Work and assume any risks
        associated with Your exercise of permissions under this License.
        
        8. Limitation of Liability. In no event and under no legal theory, whether in
        tort (including negligence), contract, or otherwise, unless required by
        applicable law (such as deliberate and grossly negligent acts) or agreed to in
        writing, shall any Contributor be liable to You for damages, including any
        direct, indirect, special, incidental, or consequential damages of any character
        arising as a result of this License or out of the use or inability to use the
        Work (including but not limited to damages for loss of goodwill, work stoppage,
        computer failure or malfunction, or any and all other commercial damages or
        losses), even if such Contributor has been advised of the possibility of such
        damages.
        
        9. Accepting Warranty or Additional Liability. While redistributing the Work or
        Derivative Works thereof, You may choose to offer, and charge a fee for,
        acceptance of support, warranty, indemnity, or other liability obligations
        and/or rights consistent with this License. However, in accepting such
        obligations, You may act only on Your own behalf and on Your sole responsibility,
        not on behalf of any other Contributor, and only if You agree to indemnify,
        defend, and hold each Contributor harmless for any liability incurred by, or
        claims asserted against, such Contributor by reason of your accepting any such
        warranty or additional liability.
        
        END OF TERMS AND CONDITIONS
License-File: LICENSE
Keywords: agent,cli,search,telegram,telethon,tg
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Communications :: Chat
Classifier: Topic :: Utilities
Requires-Python: >=3.10
Requires-Dist: click>=8.0
Requires-Dist: python-dotenv>=1.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: rich>=13.0
Requires-Dist: telethon>=1.36
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.11; extra == 'dev'
Requires-Dist: twine>=6.1; extra == 'dev'
Description-Content-Type: text/markdown

# tg-cli

[![CI](https://github.com/jackwener/tg-cli/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/jackwener/tg-cli/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/kabi_tg_cli)](https://pypi.org/project/kabi-tg-cli/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)

Telethon-powered Telegram CLI for local-first sync, search, export, and agent-friendly retrieval.

## More Projects

- [xiaohongshu-cli](https://github.com/jackwener/xiaohongshu-cli) — Xiaohongshu (小红书) CLI for notes and account workflows
- [twitter-cli](https://github.com/jackwener/twitter-cli) — Twitter/X CLI for timelines, search, and posting
- [bilibili-cli](https://github.com/jackwener/bilibili-cli) — Bilibili CLI for videos, users, search, and feeds
- [discord-cli](https://github.com/jackwener/discord-cli) — Discord CLI for local-first sync, search, and export

[English](#english) | [中文](#中文)

## English

tg-cli uses your own Telegram account over MTProto, not the Bot API. It syncs messages into local
SQLite so humans and AI agents can query the same cache quickly with `--json` or `--yaml`.

## Features

- Sync Telegram dialogs into a local SQLite cache
- Search by keyword or regex, with chat, sender, and time filters
- Browse recent messages, today's messages, top senders, and timelines
- Export messages as text, JSON, or YAML
- Keep a near-real-time cache with `tg listen --persist`
- Prefer YAML for AI agents when a strict JSON parser is not required
- Default to YAML automatically on non-TTY stdout; override with `OUTPUT=yaml|json|rich|auto`
- Structured output contract: [SCHEMA.md](./SCHEMA.md)

## Installation

```bash
# Recommended: uv tool
uv tool install kabi-tg-cli

# Or: pipx / pip
pipx install kabi-tg-cli
pip install kabi-tg-cli
```

Upgrade to the latest version:

```bash
uv tool upgrade kabi-tg-cli
# Or: pipx upgrade kabi-tg-cli
```

> **Tip:** Upgrade regularly to avoid unexpected errors from outdated API handling.

Install from GitHub:

```bash
uv tool install git+https://github.com/jackwener/tg-cli.git
```

Install from source:

```bash
git clone git@github.com:jackwener/tg-cli.git
cd tg-cli
uv sync --extra dev
```

## Quick Start

```bash
# First login (uses Telegram Desktop built-in credentials by default)
tg chats

# Check the current account
tg status
tg whoami

# Refresh the local cache
tg refresh

# Read and search
tg today
tg recent --hours 24 --limit 20 --yaml
tg search "Rust" --hours 48
tg filter "Rust,Golang,remote" --hours 48 --sync-first --yaml

# Keep a near-real-time cache
tg listen --persist
```

## Refresh Model

tg-cli is intentionally local-first:

- `tg refresh` is the recommended daily entrypoint
- `tg sync-all` is the lower-level primitive for scripts and schedulers
- `--sync-first` refreshes before a single query
- `tg listen --persist` reconnects automatically for a near-live cache

Most query commands read from local SQLite, not directly from Telegram.

## Usage

```bash
# Sync
tg status --yaml
tg refresh
tg sync-all --yaml
tg sync "GroupName"

# Search / browse
tg search "Rust"
tg search "Rust|Golang" --regex --hours 72
tg recent --hours 24 --limit 20 --yaml
tg today --sync-first
tg top --hours 24 --sync-first
tg timeline --by hour --sync-first

# Export
tg export "GroupName" -f yaml -o messages.yaml

# Send
tg send "GroupName" "Hello!"
```

## Scheduling

If you do not want to run `tg refresh` manually, use a scheduler.

### cron

See [examples/tg-refresh.cron](https://github.com/jackwener/tg-cli/blob/main/examples/tg-refresh.cron).

### systemd user timer

See:

- [tg-refresh.service](https://github.com/jackwener/tg-cli/blob/main/examples/systemd/tg-refresh.service)
- [tg-refresh.timer](https://github.com/jackwener/tg-cli/blob/main/examples/systemd/tg-refresh.timer)

Typical flow:

```bash
mkdir -p ~/.config/systemd/user
cp examples/systemd/tg-refresh.service ~/.config/systemd/user/
cp examples/systemd/tg-refresh.timer ~/.config/systemd/user/
systemctl --user daemon-reload
systemctl --user enable --now tg-refresh.timer
```

## Use as AI Agent Skill

tg-cli ships with a [`SKILL.md`](./SKILL.md) for AI agent integration.

### Agent Output Recommendation

If an AI agent needs machine-readable output, prefer `--yaml` first:

- `--yaml` is usually more token-efficient than pretty-printed JSON
- It is still easy to parse for agents and scripts
- Keep `--json` for `jq`, strict JSON-only tooling, or exact downstream schemas
- Non-TTY stdout defaults to YAML automatically
- Use `OUTPUT=yaml|json|rich|auto` to override the default mode

Recommended agent workflow:

```bash
tg refresh --yaml
tg chats --yaml
tg recent --hours 24 --sync-first --yaml
tg search "keyword" --chat "GroupName" --sync-first --yaml
```

### Claude Code / Antigravity

```bash
mkdir -p .agents/skills
git clone git@github.com:jackwener/tg-cli.git .agents/skills/tg-cli
```

### OpenClaw / ClawHub

```bash
clawhub install tg-cli
```

## ⚠️ Account Safety

tg-cli uses your personal Telegram account via MTProto. To reduce the risk of account restrictions:

1. **Get your own API credentials** — Go to [my.telegram.org](https://my.telegram.org), create an app, and set:
   ```bash
   export TG_API_ID=12345678
   export TG_API_HASH="your_api_hash_here"
   ```
   The default `api_id=2040` (Telegram Desktop) is shared by many third-party tools and may attract stricter scrutiny.

2. **Limit sync frequency** — Avoid running `tg refresh` more than 1–2 times per day.

3. **Use `--delay` and `--max-chats`** — Both `refresh` and `sync-all` support:
   - `--delay 3.0` — seconds between each chat sync (default: 2.0, with ±20% jitter)
   - `--max-chats 30` — only sync the first N chats per run

4. **Prefer established accounts** — New or rarely-used accounts are more likely to be flagged.

5. **Prefer read-only operations** — `tg send` carries higher risk than read commands.

## Troubleshooting

- `No messages today`
  - Run `tg refresh` first, or use `tg today --sync-first`.
- `Chat '...' not found in database`
  - Run `tg refresh` first, or use the numeric `chat_id` from `tg chats --yaml`.
- Repeatedly running `sync-all`
  - Prefer `tg refresh` for daily use, `--sync-first` for single queries, or `tg listen --persist`.

## 中文

`tg-cli` 是一个基于 Telethon 的 Telegram CLI。它不是 Bot API 工具，而是使用你自己的
Telegram 账号走 MTProto，把消息同步到本地 SQLite，方便你在终端里做搜索、筛选、导出，
也方便 AI agent 直接把它当作本地 retrieval tool 调用。

## 功能特性

- 同步 Telegram dialogs 到本地 SQLite
- 支持关键词搜索和 regex 搜索，可按 chat、sender、时间窗口过滤
- 支持 `recent`、`today`、`top`、`timeline` 等本地分析命令
- 支持导出为 text、JSON、YAML
- 支持 `tg listen --persist`，维持近实时本地缓存
- 支持 `--json` / `--yaml`，其中 AI agent 更推荐 `--yaml`
- stdout 不是 TTY 时默认自动输出 YAML，也可以用 `OUTPUT=yaml|json|rich|auto` 覆盖

## 安装

```bash
# 推荐：uv tool
uv tool install kabi-tg-cli

# 或者：pipx / pip
pipx install kabi-tg-cli
pip install kabi-tg-cli
```

升级到最新版本：

```bash
uv tool upgrade kabi-tg-cli
# 或：pipx upgrade kabi-tg-cli
```

> **提示：** 建议定期升级，避免因版本过旧导致的 API 调用异常。

从 GitHub 安装：

```bash
uv tool install git+https://github.com/jackwener/tg-cli.git
```

从源码安装：

```bash
git clone git@github.com:jackwener/tg-cli.git
cd tg-cli
uv sync --extra dev
```

## 快速开始

```bash
# 首次登录（默认使用 Telegram Desktop 内置的 API 凭证）
tg chats

# 检查当前账号
tg status
tg whoami

# 刷新本地缓存
tg refresh

# 浏览和搜索
tg today
tg recent --hours 24 --limit 20 --yaml
tg search "Rust" --hours 48
tg filter "招聘,remote,Web3" --hours 48 --sync-first --yaml

# 保持近实时缓存
tg listen --persist
```

## 刷新模型

`tg-cli` 是 local-first 设计：

- `tg refresh`
  - 推荐的日常入口，刷新所有当前 dialogs
- `tg sync-all`
  - 更底层的同步原语，适合脚本和调度器
- `--sync-first`
  - 单次查询前先刷新，适合 `today`、`search`、`recent`
- `tg listen --persist`
  - 常驻监听并自动重连，适合做近实时本地缓存

大多数查询命令默认读本地 SQLite，而不是每次都直接请求 Telegram。

## 使用示例

```bash
# 同步
tg status --yaml
tg refresh
tg sync-all --yaml
tg sync "群名"

# 搜索 / 浏览
tg search "Rust"
tg search "Rust|Golang" --regex --hours 72
tg recent --hours 24 --limit 20 --yaml
tg today --sync-first
tg top --hours 24 --sync-first
tg timeline --by hour --sync-first

# 导出
tg export "群名" -f yaml -o messages.yaml

# 发送消息
tg send "群名" "Hello!"
```

## 定时刷新

如果你不想每次手动执行 `tg refresh`，可以配合调度器。

### cron

参考 [examples/tg-refresh.cron](https://github.com/jackwener/tg-cli/blob/main/examples/tg-refresh.cron)。

### systemd user timer

参考：

- [tg-refresh.service](https://github.com/jackwener/tg-cli/blob/main/examples/systemd/tg-refresh.service)
- [tg-refresh.timer](https://github.com/jackwener/tg-cli/blob/main/examples/systemd/tg-refresh.timer)

典型流程：

```bash
mkdir -p ~/.config/systemd/user
cp examples/systemd/tg-refresh.service ~/.config/systemd/user/
cp examples/systemd/tg-refresh.timer ~/.config/systemd/user/
systemctl --user daemon-reload
systemctl --user enable --now tg-refresh.timer
```

## 作为 AI Agent Skill 使用

`tg-cli` 自带 [`SKILL.md`](./SKILL.md)，方便 AI agent 自动学习并调用。

### Agent 输出建议

如果下游不是严格要求 JSON，优先使用 `--yaml`：

- `--yaml` 通常比 pretty-printed JSON 更省 token
- 对 agent 和脚本来说依然容易解析
- 只有在 `jq` 或严格 JSON-only tooling 场景下再优先用 `--json`
- stdout 不是 TTY 时会默认自动输出 YAML
- 也可以用 `OUTPUT=yaml|json|rich|auto` 强制覆盖默认输出模式

推荐的 agent 调用顺序：

```bash
tg refresh --yaml
tg chats --yaml
tg recent --hours 24 --sync-first --yaml
tg search "keyword" --chat "GroupName" --sync-first --yaml
```

### Claude Code / Antigravity

```bash
mkdir -p .agents/skills
git clone git@github.com:jackwener/tg-cli.git .agents/skills/tg-cli
```

### OpenClaw / ClawHub

```bash
clawhub install tg-cli
```

## ⚠️ 账号安全

`tg-cli` 使用你的个人 Telegram 账号走 MTProto。为了降低账号被风控的风险：

1. **申请自己的 API 凭证** — 前往 [my.telegram.org](https://my.telegram.org)，创建应用后设置：
   ```bash
   export TG_API_ID=12345678
   export TG_API_HASH="your_api_hash_here"
   ```
   默认的 `api_id=2040`（Telegram Desktop）被大量第三方工具共用，风控更严格。

2. **控制同步频率** — 避免每天执行 `tg refresh` 超过 1-2 次。

3. **使用 `--delay` 和 `--max-chats`** — `refresh` 和 `sync-all` 支持：
   - `--delay 3.0` — 每个 chat 同步间隔秒数（默认 2.0，±20% 随机抖动）
   - `--max-chats 30` — 每次最多同步前 N 个 chat

4. **优先使用老号** — 新注册或长期未活跃的账号更容易被标记。

5. **优先只读操作** — `tg send` 比读取类命令风险更高。

## 常见问题

- `No messages today`
  - 先执行 `tg refresh`，或直接使用 `tg today --sync-first`
- `Chat '...' not found in database`
  - 先执行 `tg refresh`，或用 `tg chats --yaml` 找到准确的 `chat_id`
- 为什么总要先同步
  - 因为 `tg-cli` 是 local-first 设计，大多数查询命令默认读本地 SQLite，不直接查 Telegram

## 推荐项目

- [twitter-cli](https://github.com/jackwener/twitter-cli) — Twitter/X 时间线、搜索与发帖 CLI
- [bilibili-cli](https://github.com/jackwener/bilibili-cli) — Bilibili 视频、用户、搜索与动态 CLI
- [discord-cli](https://github.com/jackwener/discord-cli) — Discord 本地优先同步、检索与导出 CLI

## License

Apache-2.0
