Guide · Bots & assistants

A Telegram voice assistant: speech recognition, replies, and text to speech

Build a Telegram voice assistant in Python: transcribe voice messages, reply using chat history, and return each answer as both voice and text.

30 min time
Python 3.11, ffmpeg stack
~120 lines of code
Intermediate level

A Telegram voice bot is useful when your hands are busy or typing is inconvenient: while traveling, cooking, working or studying. The user records a voice message, and the assistant responds by voice like a conversation partner. In this guide we build an AI voice assistant using three models: the bot transcribes speech, a text model replies using the conversation history, and the bot sends the answer as both a voice message and text. All three models work with one llmbox key.

This guide builds on An AI Telegram bot in 15 minutes: Python and one API key, which covers the aiogram bot foundation, the token from @BotFather and the .env file. Here we add voice message handling.

How the voice assistant works

Every voice message goes through four steps:

  1. The bot receives the voice message and downloads the file through the Bot API. Telegram stores voice messages in OGG with the Opus codec.
  2. The speech recognition model Scribe v2 turns the recording into text.
  3. A text model answers the transcribed question using the latest messages in the chat.
  4. The speech model Eleven v4 Turbo turns the answer into speech. The bot converts the audio to OGG/Opus and sends a voice message, followed by the same answer as text.

The text version is easy to reread, copy or forward. The user also receives it if speech generation fails. The bot responds to regular text messages with both voice and text as well.

What you need

  • Python 3.11 or newer and the aiogram, openai and python-dotenv packages: pip install aiogram openai python-dotenv.
  • ffmpeg to convert audio to OGG/Opus. On macOS install it with brew install ffmpeg, on Debian and Ubuntu with apt install ffmpeg.
  • A bot token from @BotFather and an llmbox key from the Keys section of your account. Both are stored in .env, as in the basic guide:
.env
BOT_TOKEN=123456:ABC
LLMBOX_API_KEY=sk-your-key

All requests go through the official openai SDK with the address https://llmbox.cc/v1. Transcription and speech are available on the OpenAI-compatible paths /v1/audio/transcriptions and /v1/audio/speech, so you do not need a separate audio SDK.

Which models to choose

For speech recognition, the catalog has Scribe v2. The guide Transcribing audio and video through the API: calls, interviews and voice messages covers the model, speaker labeling and timestamps. A voice bot needs only the basic call: a file in, text out.

For speech generation, ElevenLabs recommends Eleven v4 Turbo when you want expressive delivery in a live conversation. If minimal delay matters more, compare it with Eleven Flash v2.5, but it has fewer languages: 32 versus more than 90. Other audio models are collected in the audio model collection.

A voice assistant does not need long answers from the text model, so a fast, inexpensive Flash-class model is enough:

The bot code

The whole bot fits in one bot.py file. The full code is below, followed by a walkthrough of each part.

bot.py
import asyncio, os
from collections import defaultdict, deque
from aiogram import Bot, Dispatcher, F
from aiogram.filters import Command
from aiogram.types import BufferedInputFile, Message
from dotenv import load_dotenv
from openai import APIConnectionError, APIStatusError, AsyncOpenAI

load_dotenv()
client = AsyncOpenAI(base_url="https://llmbox.cc/v1", api_key=os.environ["LLMBOX_API_KEY"])
bot = Bot(os.environ["BOT_TOKEN"])
dp = Dispatcher()
history = defaultdict(lambda: deque(maxlen=10))

SYSTEM = ("You are a voice assistant. Answer briefly, in two or three sentences, "
          "without lists, tables or markup: the answer will be spoken aloud.")
MAX_VOICE_SECONDS = 120  # longer voice messages are not transcribed
MAX_SPEECH_CHARS = 1000  # only the beginning of a long answer is spoken
ERRORS = {
    402: "The API balance has run out of funds.",
    403: "The key's spend limit has been reached.",
    429: "Too many requests, please try again in a minute.",
}


async def transcribe(msg: Message) -> str:
    data = await bot.download(msg.voice)  # getFile and downloading the file
    r = await client.audio.transcriptions.create(
        model="scribe_v2", file=("voice.ogg", data.read(), "audio/ogg"),
    )
    return r.text.strip()


async def think(chat_id: int, text: str) -> str:
    h = history[chat_id]
    r = await client.chat.completions.create(
        model="deepseek/deepseek-v4.1-flash",
        messages=[{"role": "system", "content": SYSTEM}, *h, {"role": "user", "content": text}],
    )
    answer = (r.choices[0].message.content or "").strip()
    if answer:
        h.extend([{"role": "user", "content": text}, {"role": "assistant", "content": answer}])
    return answer


def clip(text: str, limit: int) -> str:
    if len(text) <= limit:
        return text
    cut = text[:limit]
    end = max(cut.rfind(". "), cut.rfind("! "), cut.rfind("? "))
    return cut[:end + 1] if end > 0 else cut


async def to_ogg(mp3: bytes) -> bytes:
    p = await asyncio.create_subprocess_exec(
        "ffmpeg", "-loglevel", "error", "-i", "pipe:0", "-ac", "1", "-ar", "48000",
        "-c:a", "libopus", "-b:a", "32k", "-f", "ogg", "pipe:1",
        stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
    )
    out, err = await p.communicate(mp3)
    if p.returncode != 0:
        raise RuntimeError(err.decode())
    return out


async def speak(text: str) -> bytes:
    r = await client.audio.speech.create(
        model="eleven_v4_turbo", voice="nova",
        input=clip(text, MAX_SPEECH_CHARS), response_format="mp3",
    )
    return await to_ogg(r.content)


async def reply(msg: Message, text: str):
    answer = await think(msg.chat.id, text)
    if not answer:
        await msg.answer("I couldn't answer that, please rephrase your question.")
        return
    try:
        ogg = await speak(answer)
        await msg.answer_voice(BufferedInputFile(ogg, filename="answer.ogg"))
    except Exception as e:  # without a voice the answer still goes out as text
        print("Speech generation failed:", e)
    for i in range(0, len(answer), 4096):
        await msg.answer(answer[i:i + 4096])


async def answer_voice(msg: Message):
    text = await transcribe(msg)
    if not text:
        await msg.answer("I couldn't make out the speech, please try again.")
        return
    await reply(msg, text)


async def safely(msg: Message, job):
    try:
        await job
    except APIStatusError as e:
        await msg.answer(ERRORS.get(e.status_code, f"API error {e.status_code}, please try again."))
    except APIConnectionError:
        await msg.answer("No connection to the API, please try again.")


@dp.message(Command("reset"))
async def on_reset(msg: Message):
    history.pop(msg.chat.id, None)
    await msg.answer("Conversation history cleared.")


@dp.message(F.voice)
async def on_voice(msg: Message):
    if msg.voice.duration > MAX_VOICE_SECONDS:
        await msg.answer(f"Please record a voice message shorter than {MAX_VOICE_SECONDS} seconds.")
        return
    await bot.send_chat_action(msg.chat.id, "record_voice")
    await safely(msg, answer_voice(msg))


@dp.message(F.text)
async def on_text(msg: Message):
    await safely(msg, reply(msg, msg.text))


asyncio.run(dp.start_polling(bot))

Start the bot with python bot.py, send it a voice message and wait for the reply: the voice message arrives first, followed by the text.

How the bot transcribes voice messages

In the basic guide, the bot ignored non-text messages. Here, the F.voice filter sends voice messages to a separate handler. Handlers are checked in order, so the /reset command is declared before the text handler; otherwise, F.text would intercept it.

To transcribe Telegram voice messages, the bot first downloads the file. The bot.download method handles two Bot API steps: it requests getFile by file_id and downloads the file from the resulting path. The Bot API gives bots files up to 20 MB, and voice messages of a couple of minutes are well below that limit.

The bot sends the file to client.audio.transcriptions.create without conversion, using the name voice.ogg. The model is specified as scribe_v2, and the response arrives in the default json format with a text field. Scribe v2 detects the language automatically. If all participants speak the same language, add the language="en" parameter to set it explicitly. If the API returns 400 invalid_content for a file, convert the recording to MP3 with ffmpeg and send it again.

While the bot works, send_chat_action with the record_voice action displays a recording indicator in the chat header. This lets the user know that the message was received.

How the assistant remembers the conversation

The think function keeps the last ten messages from each chat and passes them to the model with the system message. This lets the assistant interpret a question such as "and if it's next week?" in the context of the previous message. The transcribed text is added to the history in the same way as a regular text message, so voice and text can alternate in one conversation.

The question and the answer are added to the history only after the model replies successfully. If a request fails, the history does not keep a question without an answer. The /reset command clears the chat history when the user wants to start a new topic.

The system message is especially important for a voice assistant. Lists, tables and Markdown are awkward when read aloud, and a long monologue is tiring to listen to. The model is therefore asked to answer briefly and without markup. Short answers also reduce the cost because speech is billed for every character.

How the answer becomes a voice message

The speak function sends the answer to client.audio.speech.create with the eleven_v4_turbo model and receives MP3 audio. The voice is set with the voice parameter: OpenAI voice names (alloy, nova, onyx, shimmer and others) are mapped to ElevenLabs voices, and any other value is taken as an ElevenLabs voice_id. The guide Text to speech API: voices for video, podcasts and bots explains how to choose a voice from samples.

Telegram voice messages are recorded in OGG with the Opus codec. The to_ogg function pipes the MP3 to ffmpeg through standard input and reads the result from standard output without creating temporary files. The -ac 1 and -ar 48000 flags set mono and a 48 kHz sample rate, -c:a libopus selects the Opus codec and -f ogg the container. A bitrate of 32 kbit/s is enough for speech.

The finished file is sent with the msg.answer_voice method, which calls sendVoice in the Bot API. The Bot API also accepts voice messages in MP3, so you can skip ffmpeg and pass r.content from speak directly. That variant is shown in the text-to-speech guide, while OGG/Opus produces a voice message in the same format Telegram users record themselves.

The bot sends the answer text as a separate message rather than a caption to the voice message. A caption is limited to 1024 characters and a regular message to 4096, and the bot splits a long answer into parts of 4096 characters, as in the basic guide.

Errors and limits

For every voice message the assistant makes three API requests (recognition, reply, speech), and any of them can fail. The safely function catches SDK errors and replies to the user in plain text instead of staying silent. The most common codes are:

CodeWhat happenedWhat to do
400 invalid_contentAn empty or unsuitable audio fileConvert the recording to MP3 and retry
402 insufficient_quotaThe balance is too lowTop up the balance in your account
403 spend_limit_exceededThe key's spend limit is reachedRaise the key's limit
429 rate_limit_exceededToo many requestsRetry after the pause from the Retry-After header
503, 504A temporary server-side errorRetry the request later

The full list of codes is on the Errors documentation page.

Speech generation is wrapped in a separate try: if it fails, the user still gets the answer as text, and the reason goes to the process output. Transcription and text-model errors stop processing because there is no question to answer.

There are two limits in the code, and both are set by constants:

  • MAX_VOICE_SECONDS is the maximum length of an incoming voice message. The bot takes the duration from msg.voice.duration before downloading the file, so a recording that is too long uses no download bandwidth and incurs no transcription cost.
  • MAX_SPEECH_CHARS is how many characters of the answer to speak. If the model still answers at length, the clip function cuts the text at the last complete sentence within the limit. The beginning is spoken, and the full answer arrives as text.

Conversation memory is kept in an in-memory dictionary and disappears on restart. For a bot with many users, move the history to Redis or a database. The bot sends API requests from your server, so the llmbox key never reaches users.

What the voice assistant costs

The cost of each voice message has three parts with different billing units:

  • Transcription is billed per second of recording. The rate and a per-minute calculator are on the Scribe v2 page.
  • The reply is billed per text model token. Input tokens include the system message and the conversation history, so the limit of ten messages keeps spending down.
  • Speech is billed per character of the reply. The rate is on the Eleven v4 Turbo page. Short answers and MAX_SPEECH_CHARS directly reduce this part.

The text part is easy to estimate with the calculator: enter the number of voice messages per day and the average request size with history.

Per month on DeepSeek V4.1 Flash ≈ $1.71 13.5M in · 1.35M out

You pay from your balance for actual usage, with no subscription. All three requests of each voice message are visible in the Logs section of your account with their status and cost. To keep the assistant's spending separate from other projects, create a separate key for it and set a spend limit.

What's next

Give the assistant a role in the system message: translator, English tutor, recipe helper. If the bot should answer from your documents, add a knowledge base search; the article Embeddings: POST /v1/embeddings explains the vectors used for such search. All transcription and speech parameters, formats and error codes are collected on the ElevenLabs-compatible API documentation page, and SDK setup is on the OpenAI and ElevenLabs SDKs page.

Questions

Can I use the bot without ffmpeg?

Yes. The Bot API also accepts voice messages in MP3, so you can send the speech output as it is, the way the text-to-speech guide does. ffmpeg converts the audio to OGG with the Opus codec, the format Telegram itself uses for voice recordings.

Which languages does the bot understand?

Scribe v2 detects the language of the recording on its own, and according to ElevenLabs documentation it recognizes more than 90 languages. If everyone speaks the same language, pass it explicitly with the language parameter, for example language="en".

Why does the bot refuse long voice messages?

The limit is set by the MAX_VOICE_SECONDS constant in the code. You can raise it, but keep in mind that transcription is billed per second of recording, and the Bot API gives a bot files up to 20 MB.

How do I change the assistant's voice?

Change the voice parameter in the speak function. OpenAI voice names such as nova or onyx are mapped to ElevenLabs voices, and any other value is taken as a voice_id from the GET /v2/voices list.

What does one voice message cost?

It has three parts: transcription is billed per second of recording, the reply per text model token, and speech per character of the reply. The rates are on the model pages, and the cost of each step is visible in the Logs section of your account.

Published November 15, 2026

One key — every model

GPT, Gemini, DeepSeek, Qwen, video and audio. Pay as you go.

Create a key