tganswer
Auto-answer bot for your own Telegram account (a userbot). It watches private chats only and replies to incoming voice/audio messages (optionally also to text matching a regex) with voice messages, audio files and/or text. Groups, channels and your own outgoing messages are always ignored.
Replies can be prepared audio files, or Russian (or any other language)
speech generated from text with Microsoft's neural voices, by default
Dmitry (ru-RU-DmitryNeural), sent as real voice messages (OGG/Opus).
Two ways to talk to Telegram (the backend):
- Telethon (default, recommended): a maintained pure-Python client. Works natively on Windows and on Android in Termux.
- telegram-cli (legacy): the old C client, driven over its TCP port. See telegram-cli backend (legacy).
Python 3.10+.
Install
python -m pip install telethon edge-tts imageio-ffmpeg
# or, from the repository folder:
python -m pip install -e .[telethon,tts]
telethon: the Telegram client.edge-tts: text to speech (needs internet).imageio-ffmpeg: a bundled ffmpeg for the conversion to.ogg. A systemffmpegonPATHis used first if there is one.
On Termux, install Python first: pkg install python.
Where things live
Secrets and session data never go into this repository. Everything sits in the keys dir:
| Platform | keys dir |
|---|---|
| Android/Termux | /sdcard/keys/tganswer |
| Windows | W:\Desktop\keys\tganswer |
| other | ~/.config/tganswer |
You can override it with the TGANSWER_KEYS_DIR environment variable or with keys_dir in the config.
<keys dir>/
config.json # your config (copy of config.example.json)
telegram_api.json # api_id and api_hash (Telethon)
telethon.session # your login (Telethon); keep it private
replies/ # your reply audio files (any location works)
downloads/ # incoming audio when keep_incoming is on
data/state.json # cooldowns, round-robin positions, handled message ids
data/tts-cache/ # generated speech for 'say' rules
The config file is found in this order: -c/--config PATH, then $TGANSWER_CONFIG, then
<keys dir>/config.json. Relative paths inside the config resolve against the keys dir.
Setup (Telethon)
Get an API id. Log in at https://my.telegram.org, open API development tools and create an app (any name). Save the values as
<keys dir>/telegram_api.json:{"api_id": 1234567, "api_hash": "0123456789abcdef0123456789abcdef"}Create the config: copy
config.example.jsonto<keys dir>/config.jsonand edit the rules (see Configuration).Log in once:
python -m tganswer loginEnter your phone number (international format, e.g.
+79991234567), the code Telegram sends you, and your 2FA password if you have one. The session is saved to<keys dir>/telethon.session. Anyone with this file can use your account, so keep it private.Check:
python -m tganswer config # validates the config, shows paths and rules python -m tganswer events # prints incoming private messages (Ctrl+C to stop) python -m tganswer run --dry-run # logs what it would answer, sends nothingRun:
python -m tganswer run(see Run).
Russian voice replies (TTS)
Generate an .ogg voice file from text. This needs no config:
python -m tganswer tts "Привет! Сейчас не могу ответить, перезвоню позже." -o replies/busy.ogg
python -m tganswer tts "Текст" --rate=-10% --pitch=-5Hz -o reply.ogg
python -m tganswer tts --list-voices ru # ru-RU-DmitryNeural (male), ru-RU-SvetlanaNeural (female)
The default voice is ru-RU-DmitryNeural. Values that start with - need the
= form (--rate=-10%), otherwise they are read as an option. The output is
OGG/Opus mono 48 kHz, which Telegram shows as a voice message.
The bot can also speak a reply by itself: give a rule a say phrase (or a
list of phrases) instead of, or in addition to, reply files:
{"name": "busy", "trigger": "any_audio", "say": "Перезвоню позже", "cooldown": 600}
Every phrase is generated once when the bot starts, cached in
<data_dir>/tts-cache, and sent as a voice message. The top-level tts
object sets the default voice, rate, pitch and volume; a rule can
override each of them. Speech comes from Microsoft's free Edge voice service,
so it needs internet. The service sometimes fails once ("No audio was
received"); generation is retried 3 times. If it still fails, the rule's
text (if any) is sent anyway.
Configuration
See config.example.json. Keys starting with _ are comments.
| key | meaning |
|---|---|
backend | telethon (default) or telegram_cli |
telethon.session | session file (default telethon.session in the keys dir) |
telethon.credentials | JSON file with api_id/api_hash (default telegram_api.json) |
telethon.timeout | seconds to wait for one request, uploads included (default 120) |
download_dir, data_dir | default downloads and data in the keys dir |
log_level | DEBUG, INFO, WARNING... |
tts | default voice for say: {"voice", "rate", "pitch", "volume"} |
Bot options:
| key | meaning |
|---|---|
dry_run | log what would be sent, send nothing (state file is not written) |
keep_incoming | download incoming audio to download_dir as <peer>_<msg id>.<ext> |
max_age | ignore messages older than this many seconds (default 300, 0 = off) |
whitelist | if not empty, only these peers get answers |
blacklist | these peers never get answers |
rules | list of rules; the first enabled matching rule wins |
A peer is written as a user id (12345), user#12345, @username or a print name
(John_Doe, i.e. first and last name; case-insensitive, spaces equal _).
Rule keys:
| key | default | meaning |
|---|---|---|
name | rule<N> | used in logs and the state file |
enabled | true | |
match | "*" | "*", a peer, or a list of peers |
trigger | any_audio | voice, audio, any_audio or text |
pattern | regex, required for text | |
ignore_case | true | for pattern |
reply | audio file path or list of paths | |
say | phrase or list of phrases spoken with TTS and sent as voice | |
voice, rate, pitch, volume | from tts | TTS settings for this rule's say |
pick | random | random or round_robin over all reply files and say phrases |
send_as | voice | for reply files: voice (converted to OGG/Opus if needed) or audio |
text | text sent after the audio (or alone) | |
reply_to | true | quote the incoming message |
cooldown | 0 | seconds; per rule and per peer |
At least one of reply, say or text is required. If the matching rule is
in cooldown for the peer, nothing is sent. A failed send does not start the
cooldown.
Run
python -m tganswer run # until Ctrl+C / SIGTERM
python -m tganswer run --dry-run # log replies instead of sending
python -m tganswer -v run # debug logging
python -m tganswer run --once # no reconnect; exit when the connection ends (tests)
-c/--config and -v work before or after the subcommand.
Every message is marked as handled before the reply is sent, so a crash or restart never answers the same message twice. If the connection drops, the bot reconnects with backoff (1 s up to 60 s). Setup errors (no credentials, not logged in) stop it with a message instead.
Voice replies from reply files that are not OGG (mp3, m4a, wav...) are
converted to OGG/Opus mono 48 kHz with ffmpeg and cached in
<data_dir>/voice-cache. Without ffmpeg the original file is sent and a
warning is logged.
On Android, keep the bot running in Termux with termux-wake-lock so it is not
stopped in the background.
telegram-cli backend (legacy)
Set "backend": "telegram_cli" to use telegram-cli
instead of Telethon. tganswer starts telegram-cli (or attaches to a running
one) with its TCP port enabled (-P). Commands go over one connection, and
incoming updates arrive as JSON on a second one. Replies are sent with
reply_audio / send_audio, falling back to send_file / send_document
if the build lacks a command. If telegram-cli dies, it is restarted.
Install telegram-cli
telegram-cli is old and unmaintained. Build it from source:
git clone --recursive https://github.com/vysheng/tg.git && cd tg
./configure --disable-liblua --disable-python # json support needs libjansson
make
Dependencies (Debian/Ubuntu): libreadline-dev libconfig-dev libssl-dev
libevent-dev libjansson-dev zlib1g-dev make gcc. Newer OpenSSL versions need
one of the community forks/patches of tg (search for "telegram-cli openssl 1.1").
- Termux (Android):
pkg install telegram-cliif your repo still ships it, otherwise build as above (pkg install clang make libevent openssl readline libconfig libjansson). - Windows: run it under WSL and set
"binary": ["wsl", "telegram-cli"](the port is reachable from Windows on 127.0.0.1). Paths inextra_argsmust then be WSL paths (/mnt/w/...).
Copy the server public key tg/server.pub (or tg-server.pub) into the keys
dir as server.pub. With this backend the keys dir also holds
profile/ (used as HOME for telegram-cli, session in profile/.telegram-cli).
Log in and check
python -m tganswer login # runs telegram-cli interactively; quit with safe_quit
python -m tganswer cmd get_self # prints your user as JSON (telegram-cli only)
python -m tganswer events # prints raw incoming updates (Ctrl+C to stop)
telegram_cli section
| key | meaning |
|---|---|
mode | spawn (start telegram-cli) or attach (connect to one already running with -P) |
binary | executable, or a command list such as ["wsl", "telegram-cli"] |
public_key | -k key file (default server.pub in the keys dir) |
host, port | TCP port telegram-cli listens on (-P), default 127.0.0.1:2391 |
profile_dir | HOME for the spawned telegram-cli (holds the session) |
extra_args | additional telegram-cli flags |
start_timeout, command_timeout | seconds |
Limits of telegram-cli
- It speaks an old MTProto layer. Telegram may refuse its login, or it may
not understand newer message types. The JSON output also differs between
forks, so media detection is lenient. Check with
python -m tganswer eventswhat your build prints. - Voice vs. audio detection depends on what the build reports (a voice flag,
MIME type or file name). A bare
audiomedia type is treated as voice. - Whether
send_audioproduces a voice bubble or a music file depends on the build.
Tests
python -m unittest discover -s tests -t .
No network is used. tests/test_telethon.py drives the Telethon backend with
a fake client. tests/test_integration.py runs the real CLI against
tests/fake_tgcli.py, a fake telegram-cli that serves scripted events from
tests/fixtures/.
Limits
- Telethon only receives messages while the bot runs. Messages that arrived while it was offline are not answered.
- A user can forbid voice messages in their privacy settings (Telegram
Premium). Then the voice reply fails and only the rule's
textis sent.