Here's a step-by-step guide to create a Telegram bot that converts text to audio and audio to text using Python:
1. Prerequisites
- Python 3.7+
- Telegram account
- Free API keys for speech services
2. Required Libraries
pip install python-telegram-bot gtts SpeechRecognition pydub requests
3. Create Telegram Bot
- Start
@BotFather in Telegram
- Use
/newbot command
- Save your API token
4. Implementation Code (bot.py)
import os
import logging
from telegram import Update
from telegram.ext import Application, MessageHandler, filters, ContextTypes
from gtts import gTTS
import speech_recognition as sr
from pydub import AudioSegment
# Configuration
TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"
TEMP_DIR = "temp"
os.makedirs(TEMP_DIR, exist_ok=True)
# Enable logging
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
logger = logging.getLogger(__name__)
async def text_to_audio(update: Update, context: ContextTypes.DEFAULT_TYPE):
text = update.message.text
user_id = update.message.from_user.id
output_file = os.path.join(TEMP_DIR, f"{user_id}_output.mp3")
try:
# Convert text to speech
tts = gTTS(text=text, lang='en')
tts.save(output_file)
# Send audio back
await update.message.reply_audio(audio=open(output_file, 'rb'))
os.remove(output_file)
except Exception as e:
logger.error(f"Text-to-audio error: {e}")
await update.message.reply_text("⚠️ Error converting text to audio")
async def audio_to_text(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.message.from_user.id
input_file = os.path.join(TEMP_DIR, f"{user_id}_input.ogg")
wav_file = os.path.join(TEMP_DIR, f"{user_id}_input.wav")
try:
# Download voice message
voice_file = await update.message.voice.get_file()
await voice_file.download_to_drive(input_file)
# Convert to WAV format
AudioSegment.from_ogg(input_file).export(wav_file, format="wav")
# Recognize speech
recognizer = sr.Recognizer()
with sr.AudioFile(wav_file) as source:
audio_data = recognizer.record(source)
text = recognizer.recognize_google(audio_data)
# Send recognized text
await update.message.reply_text(f"🔊 Recognized text:\n\n{text}")
# Cleanup
os.remove(input_file)
os.remove(wav_file)
except Exception as e:
logger.error(f"Audio-to-text error: {e}")
await update.message.reply_text("⚠️ Error processing audio. Try clearer speech or English language")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.message.text:
await text_to_audio(update, context)
elif update.message.voice:
await audio_to_text(update, context)
def main():
application = Application.builder().token(TOKEN).build()
# Message handlers
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
application.add_handler(MessageHandler(filters.VOICE, handle_message))
# Start bot
application.run_polling()
logger.info("Bot started")
if __name__ == "__main__":
main()
5. How to Use
- Text to Audio: Send any text message to the bot
- Audio to Text: Send a voice message (English recommended)
6. Deployment Options
- Local: Run
python bot.py
- Cloud: Deploy to services like:
- Heroku (free tier available)
- PythonAnywhere
- Google Cloud Run
- AWS Lambda
7. Limitations & Improvements
-
Limitations:
- gTTS has 200 character limit per request
- Google Speech-to-text requires internet
- Accuracy depends on audio quality
-
Improvements:
- Add language selection
- Implement async processing
- Add file size checks
- Use paid APIs for better quality (Azure Cognitive Services, AWS Polly)
- Add rate limiting
- Implement error handling for long audio
8. Notes
- Free services have usage limits
- For production, consider:
- Caching frequent requests
- Using paid speech services
- Adding authorization
- Implementing queue system
Would you like me to elaborate on any specific part (cloud deployment, handling larger files, or alternative speech APIs)?