Voice notes have become one of the most dominant communication channels on Telegram. However, processing long audio messages on the go or querying artificial intelligence while driving, walking, or multitasking often requires hands-free interaction. While cloud-based voice assistants charge recurring monthly API fees and route your private audio recordings through third-party servers, 2026 has ushered in a powerful open-source alternative: fully local, self-hosted AI voice bots on Telegram.
By combining OpenAI's Faster-Whisper model for ultra-fast local speech recognition with Ollama for open-weights LLM reasoning (such as Llama 3.1 or DeepSeek-R1), you can build a private, highly responsive AI voice assistant that runs entirely on your own server or workstation. This step-by-step guide walks you through building, configuring, and deploying a self-hosted Telegram AI voice assistant bot in Python.
A self-hosted Telegram AI voice assistant uses python-telegram-bot to receive voice notes (.ogg format), Faster-Whisper to transcribe speech locally, and Ollama to generate intelligent answers via open LLMs. This architecture guarantees 100% data privacy and zero API costs. To discover pre-built developer tools and Telegram AI bots, explore Telekit's Tech, Coding & AI Catalog.
Why Self-Host a Telegram Voice AI Assistant in 2026?
As privacy concerns grow and subscription costs for proprietary voice platforms stack up, self-hosting your AI stack provides unmatched advantages:
- 100% Privacy & Security: Audio recordings and transcribed text never leave your local infrastructure. Your personal voice messages remain private.
- Zero Subscription Fees: Run state-of-the-art open models like Llama 3.1, Mistral, or DeepSeek without paying per-token or per-minute speech API fees.
- Seamless Telegram Integration: Chat directly from your iOS, Android, Desktop, or Web Telegram app without installing additional native applications.
- Offline Capability & Customization: Customize system prompts, context windows, and voice models to suit your specific workflow or coding requirements.
System Architecture & Prerequisites
Before beginning the installation, ensure your host server or workstation meets the minimum hardware and software prerequisites:
System Prerequisites Checklist:
- Operating System: Ubuntu 22.04 LTS / 24.04 LTS, Debian 12, or macOS / WSL2
- Python Version: Python 3.10 or higher
- System Tools: FFmpeg (required for Telegram OPUS/OGG audio conversion)
- GPU / CPU: NVIDIA GPU (4GB+ VRAM recommended for fast Whisper + Ollama execution) or modern multi-core CPU (16GB+ RAM)
- Telegram Bot Token: Obtained via official Telegram @BotFather
Step 1: Install System Dependencies, FFmpeg & Ollama
First, update your package repository and install ffmpeg, Python development headers, and git. Open your terminal and run:
# Update system repositories and install FFmpeg & build tools sudo apt update && sudo apt install -y ffmpeg python3-pip python3-venv git curl # Install Ollama locally curl -fsSL https://ollama.com/install.sh | sh # Start Ollama service and pull your preferred LLM (e.g., Llama 3.1 8B) ollama pull llama3.1
To verify that Ollama is running correctly, execute ollama list in your terminal. You should see llama3.1:latest listed in the available local models.
Step 2: Set Up Python Environment & Install Dependencies
Create a dedicated directory for your project, set up an isolated Python virtual environment, and install the required Python packages:
# Create project directory mkdir -p ~/telegram-voice-ai && cd ~/telegram-voice-ai # Create virtual environment python3 -m venv venv source venv/bin/activate # Install python-telegram-bot, faster-whisper, and ollama SDK pip install --upgrade pip pip install python-telegram-bot faster-whisper ollama pydub
Step 3: Register Your Bot with Telegram @BotFather
To communicate with the Telegram API, you need a unique Telegram Bot API token:
- Open Telegram and search for @BotFather.
- Send the command
/newbot. - Provide a display name (e.g., My Local AI Voice Assistant) and a unique username ending in
bot(e.g., MyLocalVoiceAiBot). - Copy the HTTP API access token provided by BotFather (e.g.,
7123456789:AAFx...). Save this securely.
Step 4: Writing the AI Voice Assistant Code (bot.py)
Create a new file named bot.py inside your project directory. This script downloads voice notes, transcribes them with faster-whisper, queries ollama, and streams the answer back to your Telegram chat.
import os
import logging
import asyncio
from pathlib import Path
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
from faster_whisper import WhisperModel
import ollama
# Setup logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
# Configuration
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "YOUR_BOT_TOKEN_HERE")
ALLOWED_USER_ID = os.getenv("ALLOWED_USER_ID", "") # Optional: Security whitelist
OLLAMA_MODEL = "llama3.1"
WHISPER_MODEL_SIZE = "small" # Options: tiny, base, small, medium, large-v3
# Initialize Whisper model (CPU or CUDA)
device = "cuda" if os.system("nvidia-smi > /dev/null 2>&1") == 0 else "cpu"
logger.info(f"Loading Faster-Whisper ('{WHISPER_MODEL_SIZE}') on device: {device}")
whisper_model = WhisperModel(WHISPER_MODEL_SIZE, device=device, compute_type="float16" if device == "cuda" else "int8")
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_name = update.effective_user.first_name
welcome_text = (
f"👋 Hello {user_name}! I am your private, self-hosted AI Voice Assistant.
"
"🎤 Send me a voice note or text message, and I will transcribe and answer you locally!"
)
await update.message.reply_text(welcome_text)
async def handle_voice_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = str(update.effective_user.id)
if ALLOWED_USER_ID and user_id != ALLOWED_USER_ID:
await update.message.reply_text("⛔ Access denied. Unauthorized user.")
return
status_msg = await update.message.reply_text("📥 Receiving voice note...")
try:
# Download voice note file (.ogg format)
voice_file = await update.message.voice.get_file()
file_path = Path(f"temp_{update.message.message_id}.ogg")
await voice_file.download_to_drive(file_path)
await status_msg.edit_text("🎙️ Transcribing audio with Faster-Whisper...")
# Transcribe audio file using Faster-Whisper
segments, info = whisper_model.transcribe(str(file_path), beam_size=5)
transcription = " ".join([segment.text for segment in segments]).strip()
# Clean up temporary audio file
if file_path.exists():
file_path.unlink()
if not transcription:
await status_msg.edit_text("⚠️ Could not transcribe audio. Please try speaking clearer.")
return
await status_msg.edit_text(f"📝 *Transcribed:* "{transcription}"
🤖 *Thinking with {OLLAMA_MODEL}...*", parse_mode="Markdown")
# Query local Ollama model
response = ollama.chat(
model=OLLAMA_MODEL,
messages=[
{"role": "system", "content": "You are a helpful, concise AI assistant receiving voice query transcriptions on Telegram. Provide clear, direct answers."},
{"role": "user", "content": transcription}
]
)
ai_reply = response['message']['content']
# Send response back to user
final_message = f"🗣️ *You asked:* {transcription}
🤖 *Answer:*
{ai_reply}"
await status_msg.edit_text(final_message, parse_mode="Markdown")
except Exception as e:
logger.error(f"Error processing voice message: {e}")
await status_msg.edit_text(f"❌ Error processing audio: {str(e)}")
if file_path.exists():
file_path.unlink()
async def handle_text_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_text = update.message.text
status_msg = await update.message.reply_text("🤖 Thinking...")
try:
response = ollama.chat(
model=OLLAMA_MODEL,
messages=[{"role": "user", "content": user_text}]
)
ai_reply = response['message']['content']
await status_msg.edit_text(ai_reply)
except Exception as e:
await status_msg.edit_text(f"❌ Error: {str(e)}")
def main():
app = ApplicationBuilder().token(BOT_TOKEN).build()
app.add_handler(CommandHandler("start", start_command))
app.add_handler(MessageHandler(filters.VOICE, handle_voice_message))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_text_message))
logger.info("Bot is running in polling mode...")
app.run_polling()
if __name__ == "__main__":
main()
Step 5: Whisper Model Performance & Hardware Matrix
Selecting the optimal Whisper model size depends on your available system RAM and VRAM. Use this comparative matrix to optimize speed versus transcription accuracy:
Step 6: Deploying as a 24/7 Background Systemd Service
To ensure your Telegram AI Voice Assistant remains running continuously across server reboots, create a systemd service file on your Linux host:
# Create systemd service configuration sudo nano /etc/systemd/system/telegram-voice-bot.service
Paste the following service configuration (replace youruser and YOUR_BOT_TOKEN_HERE with your actual system username and Telegram bot token):
[Unit] Description=Telegram AI Voice Assistant Bot After=network.target ollama.service [Service] Type=simple User=youruser WorkingDirectory=/home/youruser/telegram-voice-ai ExecStart=/home/youruser/telegram-voice-ai/venv/bin/python bot.py Environment="TELEGRAM_BOT_TOKEN=YOUR_BOT_TOKEN_HERE" Restart=always RestartSec=5 [Install] WantedBy=multi-user.target
Enable and start the service with systemctl:
# Reload systemd daemon sudo systemctl daemon-reload # Enable service on system boot and start it now sudo systemctl enable --now telegram-voice-bot # Check service live status sudo systemctl status telegram-voice-bot
Security & Best Practices
- User Whitelisting: Always configure the
ALLOWED_USER_IDvariable inbot.py. This prevents unauthorized Telegram users from sending massive audio files and overwhelming your hardware resources. - Temporary File Cleanups: Ensure your code explicitly deletes downloaded
.oggaudio files immediately after transcription to avoid filling up server storage. - Log Monitoring: Use
journalctl -u telegram-voice-bot -fto view live logs and monitor incoming audio transcriptions.
Frequently Asked Questions (FAQ)
How much VRAM is required to run Whisper and Ollama concurrently?
Using the small Whisper model (~2GB VRAM) alongside Ollama's llama3.1:8b quantized model (~5.5GB VRAM), you can comfortably host both models on a single GPU with 8GB of VRAM (such as an NVIDIA RTX 3060 or RTX 4060).
Can this bot convert AI responses back into voice messages (TTS)?
Yes! You can integrate open-source text-to-speech (TTS) engines like Coqui TTS, Piper TTS, or gTTS in Python to synthesize the AI text answer into an .ogg audio file and send it back using await update.message.reply_voice(...).
What is the maximum voice note duration supported by Telegram?
The standard Telegram Bot API supports downloading voice files up to 20 MB in size. For voice notes (which use high-compression OPUS audio), 20 MB corresponds to over 30 minutes of continuous speech.
Why use Faster-Whisper instead of OpenAI's original Whisper library?
Faster-Whisper is a reimplementation of OpenAI's Whisper model using CTranslate2. It is up to 4 times faster than the original PyTorch implementation while utilizing significantly less GPU memory for the exact same level of accuracy.
Conclusion
Self-hosting a Telegram AI voice assistant gives you the power of modern conversational artificial intelligence right inside your favorite messaging application with zero recurring costs and absolute privacy. By pairing Faster-Whisper with Ollama in Python, you can process audio notes in seconds and interact with your personal AI assistant hands-free. Explore our curated bot guides and developer resources on Telekit to enhance your Telegram setup!