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):

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]

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:

Platformkeys dir
Android/Termux/sdcard/keys/tganswer
WindowsW:\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)

  1. 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"}
    
  2. Create the config: copy config.example.json to <keys dir>/config.json and edit the rules (see Configuration).

  3. Log in once:

    python -m tganswer login
    

    Enter 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.

  4. 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 nothing
    
  5. Run: 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.

keymeaning
backendtelethon (default) or telegram_cli
telethon.sessionsession file (default telethon.session in the keys dir)
telethon.credentialsJSON file with api_id/api_hash (default telegram_api.json)
telethon.timeoutseconds to wait for one request, uploads included (default 120)
download_dir, data_dirdefault downloads and data in the keys dir
log_levelDEBUG, INFO, WARNING...
ttsdefault voice for say: {"voice", "rate", "pitch", "volume"}

Bot options:

keymeaning
dry_runlog what would be sent, send nothing (state file is not written)
keep_incomingdownload incoming audio to download_dir as <peer>_<msg id>.<ext>
max_ageignore messages older than this many seconds (default 300, 0 = off)
whitelistif not empty, only these peers get answers
blacklistthese peers never get answers
ruleslist 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:

keydefaultmeaning
namerule<N>used in logs and the state file
enabledtrue
match"*""*", a peer, or a list of peers
triggerany_audiovoice, audio, any_audio or text
patternregex, required for text
ignore_casetruefor pattern
replyaudio file path or list of paths
sayphrase or list of phrases spoken with TTS and sent as voice
voice, rate, pitch, volumefrom ttsTTS settings for this rule's say
pickrandomrandom or round_robin over all reply files and say phrases
send_asvoicefor reply files: voice (converted to OGG/Opus if needed) or audio
texttext sent after the audio (or alone)
reply_totruequote the incoming message
cooldown0seconds; 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").

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

keymeaning
modespawn (start telegram-cli) or attach (connect to one already running with -P)
binaryexecutable, or a command list such as ["wsl", "telegram-cli"]
public_key-k key file (default server.pub in the keys dir)
host, portTCP port telegram-cli listens on (-P), default 127.0.0.1:2391
profile_dirHOME for the spawned telegram-cli (holds the session)
extra_argsadditional telegram-cli flags
start_timeout, command_timeoutseconds

Limits of telegram-cli

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