telegram-exec-notifier 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,186 @@
1
+ Metadata-Version: 2.4
2
+ Name: telegram-exec-notifier
3
+ Version: 0.2.0
4
+ Summary: Run Claude, Codex and Kiro from Telegram and get execution notifications
5
+ Project-URL: Homepage, https://github.com/Sette/telegram-exec-notifier
6
+ Project-URL: Repository, https://github.com/Sette/telegram-exec-notifier
7
+ Project-URL: Issues, https://github.com/Sette/telegram-exec-notifier/issues
8
+ Keywords: telegram,notifications,claude,codex,kiro,cli
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: POSIX :: Linux
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Communications :: Chat
19
+ Classifier: Topic :: Utilities
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+
23
+ # Telegram Execution Notifier
24
+
25
+ [![CI](https://github.com/Sette/telegram-exec-notifier/actions/workflows/ci.yml/badge.svg)](https://github.com/Sette/telegram-exec-notifier/actions/workflows/ci.yml)
26
+ [![PyPI](https://img.shields.io/pypi/v/telegram-exec-notifier)](https://pypi.org/project/telegram-exec-notifier/)
27
+
28
+ Run command-line AI agents from Telegram and get their results back on your phone. Telegram Execution Notifier connects a Telegram bot to Claude Code, Codex CLI, and Kiro CLI running on your computer, so you can delegate coding, troubleshooting, documentation, and other tasks without staying at your terminal.
29
+
30
+ Send a prompt to your bot and choose which agent should handle it. The request is forwarded to the selected CLI on your computer, and the bot sends the final output to your authorized Telegram chat. This is especially useful when your agents can access local project files and skills: you can trigger workflows remotely and let an agent use the context and capabilities already configured in your CLI environment.
31
+
32
+ The project also provides a `notify-telegram` command for shell scripts, pipelines, and other tools to report when work finishes or fails. A small `systemd --user` service keeps the Telegram integration running in the background. Built-in prompt routing supports Claude Code, Codex CLI, and Kiro CLI; the notification command can also be used by other command-line tools, including AI CLIs that support skills.
33
+
34
+ ## Features
35
+
36
+ - Send prompts from Telegram to Claude Code, Codex CLI, or Kiro CLI on your computer.
37
+ - Receive an acknowledgment when a task starts and the agent's final output when it finishes.
38
+ - Run agents with access to local files and configured skills, making remote task delegation practical.
39
+ - Send success or failure notifications from the shell, scripts, pipelines, or Python code.
40
+ - Process messages only from the configured Telegram chat.
41
+ - Keep the integration running as a `systemd --user` service, with its local endpoint bound to `127.0.0.1`.
42
+
43
+ ## 1. Create and configure the Telegram bot
44
+
45
+ 1. In Telegram, message [@BotFather](https://t.me/BotFather), run `/newbot`, and save the token it gives you.
46
+ 2. Open your new bot and send it `/start`.
47
+ 3. Find your numeric chat ID and configure it as the authorized recipient. Only messages from this chat are processed.
48
+ 4. Create the plain file `~/.config/telegram-exec-notifier/environment` with the variables below ([`.env.example`](.env.example) lists every supported one). You encrypt it in step 3, so it does not stay on disk in plain text:
49
+
50
+ ```sh
51
+ TELEGRAM_BOT_TOKEN=your-bot-token
52
+ TELEGRAM_CHAT_ID=your-chat-id
53
+ ```
54
+
55
+ ## 2. Install
56
+
57
+ From this project directory:
58
+
59
+ ```sh
60
+ python -m venv .venv
61
+ . .venv/bin/activate
62
+ pip install -e .
63
+ ```
64
+
65
+ ### Install from PyPI
66
+
67
+ ```sh
68
+ pip install telegram-exec-notifier
69
+ ```
70
+
71
+ This provides the `notify-telegram` command and `telegram-exec-notifier` (the bot service). The systemd unit and the scripts below are in this repository.
72
+
73
+ ## 3. Start the user service
74
+
75
+ Encrypt the environment file, then start the service. Both commands run from the project directory:
76
+
77
+ ```sh
78
+ ./encrypt-credentials.sh
79
+ ./start-service.sh
80
+ ```
81
+
82
+ `encrypt-credentials.sh` uses `systemd-creds` (user scope, host key plus TPM2) to write `environment.cred`, checks that it decrypts to the same content, and then securely deletes the plain file. The service loads the credential with `LoadCredentialEncrypted=`, so the token is no longer stored in plain text on disk and is decrypted only on this computer. It needs a TPM2 (`systemd-analyze has-tpm2`) and systemd 256 or newer. To change a value, recreate the plain file and run `./encrypt-credentials.sh` again, then restart the service.
83
+
84
+ The script installs the user service unit (filling in this project's path), sets the environment file permissions to `600`, enables the service at startup, and restarts it.
85
+
86
+ The service expects to find `claude`, `codex`, and `kiro-cli` in `$HOME/.local/bin` or `/usr/local/bin`. Adjust `PATH` in the service unit if your CLI binaries are elsewhere. Claude and Codex receive the home directory as an additional working directory; Kiro runs with the home directory as its workspace and has read and write tools enabled. This lets the agents work with files across your home directory while the service unit keeps the rest of the system protected from writes. On startup, the service also copies personal skills from `~/.codex/skills` and `~/.claude/skills` to `~/.kiro/skills`, preserving any skills already present in Kiro.
87
+
88
+ ## Send prompts from Telegram
89
+
90
+ Send a direct message to the bot from the authorized chat. Messages without a leading `/` go to Claude Code. Prefix with `/codex` or `/kiro` to use another agent:
91
+
92
+ ```text
93
+ explique o estado deste projeto
94
+ /codex encontre e corrija o bug no parser
95
+ /kiro revise a documentação
96
+ ```
97
+
98
+ ### Continue an existing Claude session
99
+
100
+ By default each message starts a new Claude conversation that knows where other session transcripts live (`~/.claude/projects`). To continue a real session, for example the one running your experiment:
101
+
102
+ ```text
103
+ /sessions list the 10 most recent interactive sessions
104
+ /use 2 make session 2 active; later messages resume it with full context
105
+ /use new go back to a fresh conversation (also: /new)
106
+ ```
107
+
108
+ The active session is saved in `~/.config/telegram-exec-notifier/state.json` and survives service restarts. Sessions started by the bot itself are not listed. If the same session is open in a terminal, the bot's replies continue it separately from what you type there.
109
+
110
+ Claude replies are streamed: each message arrives as soon as it is written, a "still working" note appears every `TELEGRAM_HEARTBEAT` seconds while it runs, and a final message reports completion and elapsed time. Your next message is accepted as soon as the final answer is out, even if background tasks are still running.
111
+
112
+ The bot confirms when the task starts and sends the final output when it finishes. Each run has a time limit (30 minutes by default), and long responses are truncated to fit Telegram. Send `/help` to see the available commands. Messages from other chats are ignored.
113
+
114
+ ### Approve Claude permissions from Telegram
115
+
116
+ When Claude wants to run a command or edit a file that needs permission, the bot sends a message with the tool and its command or path, plus **Permitir** / **Negar** buttons. Claude continues or adapts according to your answer. If you do not answer within `TELEGRAM_PERMISSION_TIMEOUT` seconds (default 300), the request is denied. Only the authorized chat can answer. `/codex` and `/kiro` do not use this flow.
117
+
118
+ Optional settings in `~/.config/telegram-exec-notifier/environment`:
119
+
120
+ ```sh
121
+ # Claude runs without asking when its working directory is inside this folder.
122
+ # New conversations also start in this folder. Everything else still asks.
123
+ TELEGRAM_CLAUDE_AUTO_DIR=/home/you/sandbox
124
+ TELEGRAM_PERMISSION_TIMEOUT=300 # seconds to wait for a Telegram answer
125
+ TELEGRAM_COMMAND_TIMEOUT=1800 # seconds before a run is stopped
126
+ TELEGRAM_HEARTBEAT=120 # seconds between "still working" messages
127
+ TELEGRAM_BACKGROUND_TIMEOUT=86400 # seconds a run may continue after its final answer
128
+ ```
129
+
130
+ The folder check uses the session's working directory, so a shell command inside that folder can still reach outside it (for example `cd ..`). Use a dedicated folder.
131
+
132
+ ## Run with Docker
133
+
134
+ As an alternative to systemd, run the bot as a container. The image only contains the service; the agent CLIs (`claude`, `codex`, `kiro-cli`) stay on your computer, so the compose file mounts your home directory at the same path and runs as your user.
135
+
136
+ ```sh
137
+ cp .env.example .env # set TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID
138
+ HOST_UID=$(id -u) HOST_GID=$(id -g) docker compose up -d
139
+ ```
140
+
141
+ The image is published at `ghcr.io/sette/telegram-exec-notifier`. The port is published on `127.0.0.1` only; do not expose it to the network. Credentials come from `.env` through the environment, so the systemd encrypted-credential flow does not apply; the bot token is still hidden from the agents it starts. The CLI binaries must run inside the image (a glibc Linux image); if yours do not, build a custom image from this one.
142
+
143
+ ## 4. Send a notification
144
+
145
+ ```sh
146
+ notify-telegram "Codex finished running."
147
+ notify-telegram --tool Codex "Training completed successfully."
148
+ notify-telegram --tool Claude --failed "The run failed."
149
+ some-command 2>&1 | notify-telegram --tool Codex
150
+ ```
151
+
152
+ ## Call from Python
153
+
154
+ ```python
155
+ import asyncio
156
+ from telegram_exec_notifier import TelegramNotifier
157
+
158
+ asyncio.run(
159
+ TelegramNotifier().execution_finished("Codex", "Training completed")
160
+ )
161
+ ```
162
+
163
+ The same call works in an existing async function with `await`.
164
+
165
+ ## Development and releases
166
+
167
+ ```sh
168
+ uv run --group dev ruff check .
169
+ uv run --group dev pytest
170
+ ```
171
+
172
+ CI runs lint, tests on Python 3.10 to 3.13, a package build check and a Docker build on every pull request. Commits follow `type(scope): emoji description`. [release-please](https://github.com/googleapis/release-please) reads them on `main` and keeps a release pull request up to date; merging it creates the tag and the GitHub release, which publishes the package to PyPI and the image to GHCR.
173
+
174
+ One-time repository setup:
175
+
176
+ 1. Add the `RELEASE_PLEASE_TOKEN` secret (a personal access token with contents and pull request write access) so the release it creates can trigger the publish workflows.
177
+ 2. On PyPI, add a [trusted publisher](https://docs.pypi.org/trusted-publishers/) for `telegram-exec-notifier`: owner `Sette`, repository `telegram-exec-notifier`, workflow `python-publish.yml`, environment `pypi`. Create the `pypi` environment in the repository settings.
178
+ 3. Do not edit `.release-please-manifest.json`, the version in `pyproject.toml` or the changelog by hand; the release PR does it.
179
+
180
+ ## Security notes
181
+
182
+ - The service processes commands only from the configured Telegram chat ID.
183
+ - Its local endpoint listens on `127.0.0.1`; do not expose the port to the network.
184
+ - The bot token is stored encrypted (`environment.cred`), and the agent CLIs started by the bot do not inherit it in their environment.
185
+ - While the service runs, systemd keeps the decrypted credential in `/run/user/<uid>/credentials/`, readable by your user. An agent running as your user that knows this path could still read it, so encryption protects the token at rest (disk theft, backups, other users), not from a process running as you. Revoke the token with BotFather `/revoke` if you suspect a leak.
186
+ - Never commit your bot token.
@@ -0,0 +1,164 @@
1
+ # Telegram Execution Notifier
2
+
3
+ [![CI](https://github.com/Sette/telegram-exec-notifier/actions/workflows/ci.yml/badge.svg)](https://github.com/Sette/telegram-exec-notifier/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/telegram-exec-notifier)](https://pypi.org/project/telegram-exec-notifier/)
5
+
6
+ Run command-line AI agents from Telegram and get their results back on your phone. Telegram Execution Notifier connects a Telegram bot to Claude Code, Codex CLI, and Kiro CLI running on your computer, so you can delegate coding, troubleshooting, documentation, and other tasks without staying at your terminal.
7
+
8
+ Send a prompt to your bot and choose which agent should handle it. The request is forwarded to the selected CLI on your computer, and the bot sends the final output to your authorized Telegram chat. This is especially useful when your agents can access local project files and skills: you can trigger workflows remotely and let an agent use the context and capabilities already configured in your CLI environment.
9
+
10
+ The project also provides a `notify-telegram` command for shell scripts, pipelines, and other tools to report when work finishes or fails. A small `systemd --user` service keeps the Telegram integration running in the background. Built-in prompt routing supports Claude Code, Codex CLI, and Kiro CLI; the notification command can also be used by other command-line tools, including AI CLIs that support skills.
11
+
12
+ ## Features
13
+
14
+ - Send prompts from Telegram to Claude Code, Codex CLI, or Kiro CLI on your computer.
15
+ - Receive an acknowledgment when a task starts and the agent's final output when it finishes.
16
+ - Run agents with access to local files and configured skills, making remote task delegation practical.
17
+ - Send success or failure notifications from the shell, scripts, pipelines, or Python code.
18
+ - Process messages only from the configured Telegram chat.
19
+ - Keep the integration running as a `systemd --user` service, with its local endpoint bound to `127.0.0.1`.
20
+
21
+ ## 1. Create and configure the Telegram bot
22
+
23
+ 1. In Telegram, message [@BotFather](https://t.me/BotFather), run `/newbot`, and save the token it gives you.
24
+ 2. Open your new bot and send it `/start`.
25
+ 3. Find your numeric chat ID and configure it as the authorized recipient. Only messages from this chat are processed.
26
+ 4. Create the plain file `~/.config/telegram-exec-notifier/environment` with the variables below ([`.env.example`](.env.example) lists every supported one). You encrypt it in step 3, so it does not stay on disk in plain text:
27
+
28
+ ```sh
29
+ TELEGRAM_BOT_TOKEN=your-bot-token
30
+ TELEGRAM_CHAT_ID=your-chat-id
31
+ ```
32
+
33
+ ## 2. Install
34
+
35
+ From this project directory:
36
+
37
+ ```sh
38
+ python -m venv .venv
39
+ . .venv/bin/activate
40
+ pip install -e .
41
+ ```
42
+
43
+ ### Install from PyPI
44
+
45
+ ```sh
46
+ pip install telegram-exec-notifier
47
+ ```
48
+
49
+ This provides the `notify-telegram` command and `telegram-exec-notifier` (the bot service). The systemd unit and the scripts below are in this repository.
50
+
51
+ ## 3. Start the user service
52
+
53
+ Encrypt the environment file, then start the service. Both commands run from the project directory:
54
+
55
+ ```sh
56
+ ./encrypt-credentials.sh
57
+ ./start-service.sh
58
+ ```
59
+
60
+ `encrypt-credentials.sh` uses `systemd-creds` (user scope, host key plus TPM2) to write `environment.cred`, checks that it decrypts to the same content, and then securely deletes the plain file. The service loads the credential with `LoadCredentialEncrypted=`, so the token is no longer stored in plain text on disk and is decrypted only on this computer. It needs a TPM2 (`systemd-analyze has-tpm2`) and systemd 256 or newer. To change a value, recreate the plain file and run `./encrypt-credentials.sh` again, then restart the service.
61
+
62
+ The script installs the user service unit (filling in this project's path), sets the environment file permissions to `600`, enables the service at startup, and restarts it.
63
+
64
+ The service expects to find `claude`, `codex`, and `kiro-cli` in `$HOME/.local/bin` or `/usr/local/bin`. Adjust `PATH` in the service unit if your CLI binaries are elsewhere. Claude and Codex receive the home directory as an additional working directory; Kiro runs with the home directory as its workspace and has read and write tools enabled. This lets the agents work with files across your home directory while the service unit keeps the rest of the system protected from writes. On startup, the service also copies personal skills from `~/.codex/skills` and `~/.claude/skills` to `~/.kiro/skills`, preserving any skills already present in Kiro.
65
+
66
+ ## Send prompts from Telegram
67
+
68
+ Send a direct message to the bot from the authorized chat. Messages without a leading `/` go to Claude Code. Prefix with `/codex` or `/kiro` to use another agent:
69
+
70
+ ```text
71
+ explique o estado deste projeto
72
+ /codex encontre e corrija o bug no parser
73
+ /kiro revise a documentação
74
+ ```
75
+
76
+ ### Continue an existing Claude session
77
+
78
+ By default each message starts a new Claude conversation that knows where other session transcripts live (`~/.claude/projects`). To continue a real session, for example the one running your experiment:
79
+
80
+ ```text
81
+ /sessions list the 10 most recent interactive sessions
82
+ /use 2 make session 2 active; later messages resume it with full context
83
+ /use new go back to a fresh conversation (also: /new)
84
+ ```
85
+
86
+ The active session is saved in `~/.config/telegram-exec-notifier/state.json` and survives service restarts. Sessions started by the bot itself are not listed. If the same session is open in a terminal, the bot's replies continue it separately from what you type there.
87
+
88
+ Claude replies are streamed: each message arrives as soon as it is written, a "still working" note appears every `TELEGRAM_HEARTBEAT` seconds while it runs, and a final message reports completion and elapsed time. Your next message is accepted as soon as the final answer is out, even if background tasks are still running.
89
+
90
+ The bot confirms when the task starts and sends the final output when it finishes. Each run has a time limit (30 minutes by default), and long responses are truncated to fit Telegram. Send `/help` to see the available commands. Messages from other chats are ignored.
91
+
92
+ ### Approve Claude permissions from Telegram
93
+
94
+ When Claude wants to run a command or edit a file that needs permission, the bot sends a message with the tool and its command or path, plus **Permitir** / **Negar** buttons. Claude continues or adapts according to your answer. If you do not answer within `TELEGRAM_PERMISSION_TIMEOUT` seconds (default 300), the request is denied. Only the authorized chat can answer. `/codex` and `/kiro` do not use this flow.
95
+
96
+ Optional settings in `~/.config/telegram-exec-notifier/environment`:
97
+
98
+ ```sh
99
+ # Claude runs without asking when its working directory is inside this folder.
100
+ # New conversations also start in this folder. Everything else still asks.
101
+ TELEGRAM_CLAUDE_AUTO_DIR=/home/you/sandbox
102
+ TELEGRAM_PERMISSION_TIMEOUT=300 # seconds to wait for a Telegram answer
103
+ TELEGRAM_COMMAND_TIMEOUT=1800 # seconds before a run is stopped
104
+ TELEGRAM_HEARTBEAT=120 # seconds between "still working" messages
105
+ TELEGRAM_BACKGROUND_TIMEOUT=86400 # seconds a run may continue after its final answer
106
+ ```
107
+
108
+ The folder check uses the session's working directory, so a shell command inside that folder can still reach outside it (for example `cd ..`). Use a dedicated folder.
109
+
110
+ ## Run with Docker
111
+
112
+ As an alternative to systemd, run the bot as a container. The image only contains the service; the agent CLIs (`claude`, `codex`, `kiro-cli`) stay on your computer, so the compose file mounts your home directory at the same path and runs as your user.
113
+
114
+ ```sh
115
+ cp .env.example .env # set TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID
116
+ HOST_UID=$(id -u) HOST_GID=$(id -g) docker compose up -d
117
+ ```
118
+
119
+ The image is published at `ghcr.io/sette/telegram-exec-notifier`. The port is published on `127.0.0.1` only; do not expose it to the network. Credentials come from `.env` through the environment, so the systemd encrypted-credential flow does not apply; the bot token is still hidden from the agents it starts. The CLI binaries must run inside the image (a glibc Linux image); if yours do not, build a custom image from this one.
120
+
121
+ ## 4. Send a notification
122
+
123
+ ```sh
124
+ notify-telegram "Codex finished running."
125
+ notify-telegram --tool Codex "Training completed successfully."
126
+ notify-telegram --tool Claude --failed "The run failed."
127
+ some-command 2>&1 | notify-telegram --tool Codex
128
+ ```
129
+
130
+ ## Call from Python
131
+
132
+ ```python
133
+ import asyncio
134
+ from telegram_exec_notifier import TelegramNotifier
135
+
136
+ asyncio.run(
137
+ TelegramNotifier().execution_finished("Codex", "Training completed")
138
+ )
139
+ ```
140
+
141
+ The same call works in an existing async function with `await`.
142
+
143
+ ## Development and releases
144
+
145
+ ```sh
146
+ uv run --group dev ruff check .
147
+ uv run --group dev pytest
148
+ ```
149
+
150
+ CI runs lint, tests on Python 3.10 to 3.13, a package build check and a Docker build on every pull request. Commits follow `type(scope): emoji description`. [release-please](https://github.com/googleapis/release-please) reads them on `main` and keeps a release pull request up to date; merging it creates the tag and the GitHub release, which publishes the package to PyPI and the image to GHCR.
151
+
152
+ One-time repository setup:
153
+
154
+ 1. Add the `RELEASE_PLEASE_TOKEN` secret (a personal access token with contents and pull request write access) so the release it creates can trigger the publish workflows.
155
+ 2. On PyPI, add a [trusted publisher](https://docs.pypi.org/trusted-publishers/) for `telegram-exec-notifier`: owner `Sette`, repository `telegram-exec-notifier`, workflow `python-publish.yml`, environment `pypi`. Create the `pypi` environment in the repository settings.
156
+ 3. Do not edit `.release-please-manifest.json`, the version in `pyproject.toml` or the changelog by hand; the release PR does it.
157
+
158
+ ## Security notes
159
+
160
+ - The service processes commands only from the configured Telegram chat ID.
161
+ - Its local endpoint listens on `127.0.0.1`; do not expose the port to the network.
162
+ - The bot token is stored encrypted (`environment.cred`), and the agent CLIs started by the bot do not inherit it in their environment.
163
+ - While the service runs, systemd keeps the decrypted credential in `/run/user/<uid>/credentials/`, readable by your user. An agent running as your user that knows this path could still read it, so encryption protects the token at rest (disk theft, backups, other users), not from a process running as you. Revoke the token with BotFather `/revoke` if you suspect a leak.
164
+ - Never commit your bot token.
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "telegram-exec-notifier"
7
+ version = "0.2.0"
8
+ description = "Run Claude, Codex and Kiro from Telegram and get execution notifications"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ dependencies = []
12
+ keywords = ["telegram", "notifications", "claude", "codex", "kiro", "cli"]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Environment :: Console",
16
+ "Intended Audience :: Developers",
17
+ "Operating System :: POSIX :: Linux",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: Communications :: Chat",
24
+ "Topic :: Utilities",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/Sette/telegram-exec-notifier"
29
+ Repository = "https://github.com/Sette/telegram-exec-notifier"
30
+ Issues = "https://github.com/Sette/telegram-exec-notifier/issues"
31
+
32
+ [project.scripts]
33
+ notify-telegram = "telegram_exec_notifier.cli:main"
34
+ telegram-exec-notifier = "telegram_exec_notifier.server:main"
35
+
36
+ [dependency-groups]
37
+ dev = ["pytest>=8", "ruff>=0.6"]
38
+
39
+ [tool.setuptools.packages.find]
40
+ where = ["src"]
41
+
42
+ [tool.pytest.ini_options]
43
+ testpaths = ["tests"]
44
+ pythonpath = ["src"]
45
+
46
+ [tool.ruff]
47
+ line-length = 120
48
+ target-version = "py310"
49
+
50
+ [tool.ruff.lint]
51
+ select = ["E", "F", "I", "B", "UP"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,5 @@
1
+ """Telegram notifications for Claude and Codex executions."""
2
+
3
+ from .notifier import TelegramNotifier
4
+
5
+ __all__ = ["TelegramNotifier"]
@@ -0,0 +1,28 @@
1
+ """Command line entry point for sending notifications."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import sys
8
+
9
+ from .notifier import TelegramNotifier
10
+
11
+
12
+ def main() -> None:
13
+ parser = argparse.ArgumentParser(description="Send a message to your Telegram chat")
14
+ parser.add_argument("message", nargs="?", help="Message text; reads stdin if omitted")
15
+ parser.add_argument("--tool", help="Label the message as an execution result")
16
+ parser.add_argument("--failed", action="store_true", help="Mark execution as failed")
17
+ args = parser.parse_args()
18
+ message = args.message if args.message is not None else sys.stdin.read().strip()
19
+ if not message:
20
+ parser.error("provide a message or pipe text through stdin")
21
+
22
+ notifier = TelegramNotifier()
23
+ if args.tool:
24
+ asyncio.run(
25
+ notifier.execution_finished(args.tool, message, success=not args.failed)
26
+ )
27
+ else:
28
+ asyncio.run(notifier.send(message))
@@ -0,0 +1,46 @@
1
+ """Load settings from a systemd encrypted credential instead of a plain env file."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+ CREDENTIAL_NAME = "environment"
9
+ # Variables the spawned agent CLIs must never inherit.
10
+ SECRET_VARS = ("TELEGRAM_BOT_TOKEN", "CREDENTIALS_DIRECTORY")
11
+
12
+
13
+ def _parse(text: str) -> dict[str, str]:
14
+ values = {}
15
+ for line in text.splitlines():
16
+ line = line.strip()
17
+ if not line or line.startswith("#") or "=" not in line:
18
+ continue
19
+ key, _, value = line.partition("=")
20
+ value = value.strip()
21
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
22
+ value = value[1:-1]
23
+ values[key.strip()] = value
24
+ return values
25
+
26
+
27
+ def load_credentials() -> None:
28
+ """Export KEY=VALUE pairs from the credential into os.environ.
29
+
30
+ Does nothing when the service was not started with a credential (for example
31
+ when variables come from a plain EnvironmentFile or the shell).
32
+ """
33
+ directory = os.environ.get("CREDENTIALS_DIRECTORY")
34
+ if not directory:
35
+ return
36
+ path = Path(directory) / CREDENTIAL_NAME
37
+ try:
38
+ values = _parse(path.read_text())
39
+ except OSError:
40
+ return
41
+ os.environ.update(values)
42
+
43
+
44
+ def child_env() -> dict[str, str]:
45
+ """Environment for agent subprocesses, without the bot token."""
46
+ return {k: v for k, v in os.environ.items() if k not in SECRET_VARS}
@@ -0,0 +1,69 @@
1
+ """Convert the Markdown emitted by agent CLIs into Telegram-safe HTML."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ import re
7
+
8
+ _FENCE = re.compile(r"^```[^\n]*\n(.*?)(?:^```[ \t]*$|\Z)", re.S | re.M)
9
+ _CODE = re.compile(r"`([^`\n]+)`")
10
+ _BOLD = re.compile(r"\*\*(?=\S)(.+?)(?<=\S)\*\*|__(?=\S)(.+?)(?<=\S)__")
11
+ _ITALIC = re.compile(r"(?<![\w*])\*(?=[^\s*])([^*\n]+?)(?<=[^\s*])\*(?![\w*])")
12
+ _LINK = re.compile(r"\[([^\]\n]+)\]\((https?://[^)\s]+)\)")
13
+ _HEADER = re.compile(r"^#{1,6}\s+(.*)$")
14
+ _BULLET = re.compile(r"^(\s*)[-*+]\s+")
15
+ _RULE = re.compile(r"^\s*([-*_])\1{2,}\s*$")
16
+
17
+
18
+ def _inline(text: str) -> str:
19
+ """Format one already-escaped line of Markdown."""
20
+ spans: list[str] = []
21
+
22
+ def stash(match: re.Match) -> str:
23
+ spans.append(f"<code>{match.group(1)}</code>")
24
+ return f"\0{len(spans) - 1}\0"
25
+
26
+ text = _CODE.sub(stash, text)
27
+ text = _LINK.sub(lambda m: f'<a href="{m.group(2)}">{m.group(1)}</a>', text)
28
+ text = _BOLD.sub(lambda m: f"<b>{m.group(1) or m.group(2)}</b>", text)
29
+ text = _ITALIC.sub(r"<i>\1</i>", text)
30
+ return re.sub(r"\0(\d+)\0", lambda m: spans[int(m.group(1))], text)
31
+
32
+
33
+ def _prose(text: str) -> str:
34
+ lines = html.escape(text, quote=False).split("\n")
35
+ out: list[str] = []
36
+ table: list[str] = []
37
+
38
+ def flush_table() -> None:
39
+ if table:
40
+ out.append("<pre>" + "\n".join(table) + "</pre>")
41
+ table.clear()
42
+
43
+ for line in lines:
44
+ if line.lstrip().startswith("|"):
45
+ table.append(line)
46
+ continue
47
+ flush_table()
48
+ if _RULE.match(line):
49
+ continue
50
+ header = _HEADER.match(line)
51
+ if header:
52
+ out.append(f"<b>{_inline(header.group(1))}</b>")
53
+ continue
54
+ out.append(_inline(_BULLET.sub(lambda m: f"{m.group(1)}• ", line)))
55
+ flush_table()
56
+ return "\n".join(out)
57
+
58
+
59
+ def markdown_to_telegram_html(text: str) -> str:
60
+ """Return Telegram HTML for Markdown text; unclosed code fences are closed."""
61
+ parts: list[str] = []
62
+ position = 0
63
+ for match in _FENCE.finditer(text):
64
+ parts.append(_prose(text[position : match.start()]))
65
+ code = html.escape(match.group(1).rstrip("\n"), quote=False)
66
+ parts.append(f"<pre>{code}</pre>")
67
+ position = match.end()
68
+ parts.append(_prose(text[position:]))
69
+ return "".join(parts)
@@ -0,0 +1,44 @@
1
+ """Client for the local Telegram notification service."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import os
8
+ from urllib.error import HTTPError, URLError
9
+ from urllib.request import Request, urlopen
10
+
11
+
12
+ class TelegramNotifier:
13
+ """Send messages to the local notifier service."""
14
+
15
+ def __init__(self, service_url: str | None = None) -> None:
16
+ self.service_url = (
17
+ service_url or os.getenv("TELEGRAM_NOTIFIER_URL", "http://127.0.0.1:8765")
18
+ ).rstrip("/")
19
+
20
+ async def send(self, message: str) -> None:
21
+ """Send a plain text notification via the local service."""
22
+ await asyncio.to_thread(self._send, message)
23
+
24
+ def _send(self, message: str) -> None:
25
+ payload = json.dumps({"text": message}).encode()
26
+ request = Request(
27
+ f"{self.service_url}/notify",
28
+ data=payload,
29
+ headers={"Content-Type": "application/json"},
30
+ method="POST",
31
+ )
32
+ try:
33
+ with urlopen(request, timeout=15) as response:
34
+ if response.status != 200:
35
+ raise RuntimeError(f"Notifier service returned HTTP {response.status}")
36
+ except (HTTPError, URLError) as exc:
37
+ raise RuntimeError(f"Could not send notification: {exc}") from exc
38
+
39
+ async def execution_finished(
40
+ self, tool: str, summary: str, *, success: bool = True
41
+ ) -> None:
42
+ """Send a consistently formatted execution result."""
43
+ status = "✅ concluída" if success else "❌ falhou"
44
+ await self.send(f"{tool}: execução {status}\n\n{summary}")