import telebot
import httpx
import json
import base64
# Replace with your Telegram Bot Token
TELEGRAM_BOT_TOKEN = "YOUR_BOT_TOKEN"
# Create bot instance
bot = telebot.TeleBot(TELEGRAM_BOT_TOKEN)
# Google TTS Configuration
GOOGLE_API_KEY = "AIzaSyBrHRq1560psTF4pnWChWGV4G1mgymWb8g"
TTS_API_URL = "https://texttospeech.googleapis.com/v1/text:synthesize"
TTS_HEADERS = {
"User-Agent": "okhttp/4.11.0",
"Accept-Encoding": "gzip",
"x-goog-api-key": GOOGLE_API_KEY,
"Content-Type": "application/json; charset=utf-8"
}
TTS_PAYLOAD_TEMPLATE = {
"audioConfig": {
"audioEncoding": "MP3",
"effectsProfileId": [],
"pitch": 0.0,
"sampleRateHertz": 0,
"speakingRate": 1.0,
"volumeGainDb": 0
},
"voice": {
"languageCode": "en-US", # English (US)
"name": "en-US-Wavenet-F", # Female voice
"ssmlGender": "FEMALE" # Set to FEMALE
}
}
# Function to synthesize text to audio
def synth_text(text):
payload = TTS_PAYLOAD_TEMPLATE.copy()
payload["input"] = {"text": text}
response = httpx.post(TTS_API_URL, json=payload, headers=TTS_HEADERS)
if response.status_code == 200:
return base64.b64decode(response.json()["audioContent"])
else:
error_message = response.json().get("error", {}).get("message", "Unknown error")
raise Exception(f"Google TTS API Error: {error_message}")
# Handle the /start command
@bot.message_handler(commands=["start"])
def send_welcome(message):
bot.reply_to(message, "Welcome! Use /text followed by your message to convert it to speech.\n\nExample: /text Hello Baby")
# Handle the /text command
@bot.message_handler(commands=["text"])
def handle_text_command(message):
try:
# Extract text after the command
user_text = message.text.partition(' ')[2].strip()
if not user_text:
bot.reply_to(message, "Please provide text to synthesize. Example: /text Hello Baby")
return
# Check for long text and truncate if necessary
if len(user_text) > 5000:
bot.reply_to(message, "Text too long! Please provide text under 5000 characters.")
return
bot.send_message(message.chat.id, "Synthesizing your message...")
# Get synthesized audio
audio_content = synth_text(user_text)
# Send the audio file as a voice message
bot.send_voice(message.chat.id, audio_content)
except Exception as e:
bot.reply_to(message, f"Failed to synthesize text. Error: {str(e)}")
# Handle other unrecognized messages
@bot.message_handler(func=lambda message: True)
def handle_other_messages(message):
bot.reply_to(message, "I didn't understand that. Use /text followed by your message to convert it to speech.")
# Start the bot
bot.polling()
๏ปฟ