Spaces:
Sleeping
Sleeping
Update main.py
Browse files4 unmodified lines56789103 unmodified lines141516171819202122232410 unmodified lines3536373839404114 unmodified lines5657585960616263646566673 unmodified lines7172737475767713 unmodified lines919293949596976 unmodified lines1041051061071081091106 unmodified lines1171181191201211221239 unmodified lines13313413513613713813967 unmodified lines2072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422434 unmodified lines2482492502512522532542555 unmodified lines2612622632644 unmodified linesimport asyncioimport jsonfrom datetime import datetime# Add these constants at the topAPI_URL = "https://api-inference.huggingface.co/models/openai/whisper-large-v3-turbo"3 unmodified lines"Accept": "application/json"}# Initialize message history in memory onlymessage_history = []# Create a new Client instance with a custom session name and no local storageapp = Client("my_bot",api_id=API_ID,api_hash=API_HASH,10 unmodified linesprint("Message History Update:", json.dumps(message_data, indent=2))# Add command to print history@app.on_message(filters.command("history"))async def history_command(client, message):if not message_history:await message.reply_text("No message history available.")14 unmodified linesawait message.reply_text(f"Error retrieving history: {str(e)}")# Command handler for /start@app.on_message(filters.command("start"))async def start_command(client, message):await message.reply_text("Hello! I'm your Telegram bot. Nice to meet you!")# Command handler for /help@app.on_message(filters.command("help"))async def help_command(client, message):help_text = """Available commands:3 unmodified linesawait message.reply_text(help_text)# Message handler for regular text messages@app.on_message(filters.text & filters.private & ~filters.command(["start", "help", "info"]))async def echo(client, message):try:thinking_msg = await message.reply_text("🤔 Thinking about your message...")13 unmodified linesawait message.reply_text(f"Sorry, I couldn't process your message: {str(e)}")# Handle photo messages@app.on_message(filters.photo)async def handle_photo(client, message):response = "Nice photo!"await message.reply_text(response)6 unmodified lines)# Handle sticker messages@app.on_message(filters.sticker)async def handle_sticker(client, message):response = "Cool sticker!"await message.reply_text(response)6 unmodified lines)# Custom command example@app.on_message(filters.command("info"))async def info_command(client, message):user = message.from_userinfo_text = f"""9 unmodified linestry:with open(file_path, "rb") as f:data = f.read()response = requests.post(API_URL, data=data)return response.json().get('text', 'Could not transcribe audio')except Exception as e:print(f"Error in transcription: {e}")67 unmodified linesprint(f"Error getting AI response: {str(e)}\nFull error: {repr(e)}")return "Sorry, I couldn't process your message."# Update the voice message handler with retry logic@app.on_message(filters.voice | filters.audio)async def handle_voice(client, message):try:# Send a processing messageprocessing_msg = await message.reply_text("🎵 Processing your voice message...")# Download the voice message with retry logicmax_retries = 3for attempt in range(max_retries):try:message = await app.get_messages(message.chat.id,message.id)voice_file = await message.download()breakexcept Exception as e:if attempt == max_retries - 1:raise eawait asyncio.sleep(1)transcription = await transcribe_audio(voice_file)await message.reply_text(f"🗣️ Transcription:\n\n{transcription}")thinking_msg = await message.reply_text("🤔 Thinking about your message...")ai_response = await get_ai_response(transcription)await thinking_msg.delete()await message.reply_text(ai_response)# Save voice message to historysave_message_to_history(message.from_user.id,message.from_user.username,4 unmodified lines# Clean uptry:os.remove(voice_file)await processing_msg.delete()except:pass5 unmodified lines# Run the botif __name__ == "__main__":print("Bot is running...")app.run()4 unmodified lines567891011123 unmodified lines16171819202122232425262728293031323334353637383940414243444510 unmodified lines5657585960616214 unmodified lines7778798081828384858687883 unmodified lines9293949596979813 unmodified lines1121131141151161171186 unmodified lines1251261271281291301316 unmodified lines1381391401411421431449 unmodified lines15415515615715815916067 unmodified lines2282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652664 unmodified lines2712722732742752762772782795 unmodified lines2852862872884 unmodified linesimport asyncioimport jsonfrom datetime import datetimeimport edge_ttsimport io# Add these constants at the topAPI_URL = "https://api-inference.huggingface.co/models/openai/whisper-large-v3-turbo"3 unmodified lines"Accept": "application/json"}# TTS settingsDEFAULT_VOICE = "en-IN-NeerjaNeural"DEFAULT_RATE = "+25%"# Initialize message history in memory onlymessage_history = []async def text_to_speech(text, voice=DEFAULT_VOICE, rate=DEFAULT_RATE):"""Convert text to speech and return the audio data"""try:communicate = edge_tts.Communicate(text, voice, rate=rate)audio_data = bytes()async for chunk in communicate.stream():if chunk["type"] == "audio":audio_data += chunk["data"]return audio_dataexcept Exception as e:print(f"Error in text-to-speech conversion: {str(e)}")return None# Create a new Client instance with a custom session name and no local storagemyaibot = Client("my_bot",api_id=API_ID,api_hash=API_HASH,10 unmodified linesprint("Message History Update:", json.dumps(message_data, indent=2))# Add command to print history@myaibot.on_message(filters.command("history"))async def history_command(client, message):if not message_history:await message.reply_text("No message history available.")14 unmodified linesawait message.reply_text(f"Error retrieving history: {str(e)}")# Command handler for /start@myaibot.on_message(filters.command("start"))async def start_command(client, message):await message.reply_text("Hello! I'm your Telegram bot. Nice to meet you!")# Command handler for /help@myaibot.on_message(filters.command("help"))async def help_command(client, message):help_text = """Available commands:3 unmodified linesawait message.reply_text(help_text)# Message handler for regular text messages@myaibot.on_message(filters.text & filters.private & ~filters.command(["start", "help", "info"]))async def echo(client, message):try:thinking_msg = await message.reply_text("🤔 Thinking about your message...")13 unmodified linesawait message.reply_text(f"Sorry, I couldn't process your message: {str(e)}")# Handle photo messages@myaibot.on_message(filters.photo)async def handle_photo(client, message):response = "Nice photo!"await message.reply_text(response)6 unmodified lines)# Handle sticker messages@myaibot.on_message(filters.sticker)async def handle_sticker(client, message):response = "Cool sticker!"await message.reply_text(response)6 unmodified lines)# Custom command example@myaibot.on_message(filters.command("info"))async def info_command(client, message):user = message.from_userinfo_text = f"""9 unmodified linestry:with open(file_path, "rb") as f:data = f.read()response = requests.post(API_URL,data=data)return response.json().get('text', 'Could not transcribe audio')except Exception as e:print(f"Error in transcription: {e}")67 unmodified linesprint(f"Error getting AI response: {str(e)}\nFull error: {repr(e)}")return "Sorry, I couldn't process your message."# Update the voice message handler with TTS response@myaibot.on_message(filters.voice | filters.audio)async def handle_voice(client, message):try:processing_msg = await message.reply_text("🎵 Processing your voice message...")# Download and process voice messagevoice_file = await message.download()transcription = await transcribe_audio(voice_file)await message.reply_text(f"🗣️ Transcription:\n\n{transcription}")# Get AI responsethinking_msg = await message.reply_text("🤔 Thinking about your message...")ai_response = await get_ai_response(transcription)await thinking_msg.delete()await message.reply_text(ai_response)# Convert AI response to speechprocessing_tts = await message.reply_text("🔊 Converting response to speech...")audio_data = await text_to_speech(ai_response)if audio_data:# Create an in-memory file-like objectaudio_file = io.BytesIO(audio_data)audio_file.name = "response.mp3"# Send audio directly from memoryawait message.reply_voice(audio_file,caption="🎵 Voice response")# Save to historysave_message_to_history(message.from_user.id,message.from_user.username,4 unmodified lines# Clean uptry:os.remove(voice_file) # Still need to remove the downloaded voice fileawait processing_msg.delete()await processing_tts.delete()except:pass5 unmodified lines# Run the botif __name__ == "__main__":print("Bot is running...")myaibot.run()
main.py+54-30