Now i have the code where should i paste it to give whatsapp automation run.
- User
Now i have the code where should i paste it to give whatsapp automation run.
Assistant
To integrate this car rental agent with WhatsApp, you'll need to use the WhatsApp Business API or a third-party service. Here's how to set it up using different approaches:
Option 1: Using Twilio (Recommended for Quick Setup)
First, modify the code to work as a webhook-based service:
from flask import Flask, request from twilio.twiml.messaging_response import MessagingResponse import pandas as pd from datetime import datetime, timedelta import json import os app = Flask(__name__) # Store conversation states (in production, use a database) conversations = {} class WhatsAppCarRentalAgent: def __init__(self, phone_number): self.phone_number = phone_number self.state = "welcome" self.customer_info = {} self.rental_info = {} self.available_cars = { "1": {"name": "Economy", "models": ["Toyota Yaris", "Honda Fit"], "rate": 35}, "2": {"name": "Compact", "models": ["Toyota Corolla", "Honda Civic"], "rate": 45}, "3": {"name": "Mid-size", "models": ["Toyota Camry", "Honda Accord"], "rate": 55}, "4": {"name": "SUV", "models": ["Toyota RAV4", "Honda CR-V"], "rate": 70}, "5": {"name": "Luxury", "models": ["BMW 3 Series", "Mercedes C-Class"], "rate": 95} } def process_message(self, incoming_msg): incoming_msg = incoming_msg.strip().lower() if self.state == "welcome": self.state = "get_name" return "Welcome to Car Rental Service! 🚗\n\nI'll help you rent a car today.\n\nPlease enter your full name:" elif self.state == "get_name": self.customer_info["name"] = incoming_msg.title() self.state = "get_email" return f"Thank you, {self.customer_info['name']}!\n\nPlease enter your email address:" elif self.state == "get_email": self.customer_info["email"] = incoming_msg self.state = "get_phone" return "Please enter your phone number:" elif self.state == "get_phone": self.customer_info["phone"] = incoming_msg self.state = "get_license" return "Please enter your driver's license number:" elif self.state == "get_license": self.customer_info["license"] = incoming_msg.upper() self.state = "show_cars" car_list = "🚗 Available Car Categories:\n\n" for key, car in self.available_cars.items(): car_list += f"{key}. {car['name']} - ${car['rate']}/day\n" car_list += "\nReply with a number (1-5) to select:" return car_list elif self.state == "show_cars": if incoming_msg in self.available_cars: self.rental_info["category"] = self.available_cars[incoming_msg]["name"] self.rental_info["rate"] = self.available_cars[incoming_msg]["rate"] self.state = "get_pickup_date" return "When would you like to pick up the car?\n\nPlease enter date (DD/MM/YYYY):" else: return "Please select a valid option (1-5):" elif self.state == "get_pickup_date": try: self.rental_info["pickup_date"] = datetime.strptime(incoming_msg, "%d/%m/%Y") self.state = "get_days" return "How many days would you like to rent the car?" except: return "Please enter a valid date format (DD/MM/YYYY):" elif self.state == "get_days": try: days = int(incoming_msg) if days > 0: self.rental_info["days"] = days self.rental_info["total_cost"] = days * self.rental_info["rate"] self.state = "get_location" return "Where would you like to pick up the car?\n\nEnter pickup location:" else: return "Please enter a positive number of days:" except: return "Please enter a valid number:" elif self.state == "get_location": self.rental_info["location"] = incoming_msg self.state = "confirm" summary = f"""📋 Booking Summary: Customer: {self.customer_info['name']} Car Type: {self.rental_info['category']} Pickup Date: {self.rental_info['pickup_date'].strftime('%d/%m/%Y')} Duration: {self.rental_info['days']} days Location: {self.rental_info['location']} Total Cost: ${self.rental_info['total_cost']} Reply 'YES' to confirm or 'NO' to cancel:""" return summary elif self.state == "confirm": if incoming_msg == "yes": # Save to Excel self.save_to_excel() booking_ref = f"CR{datetime.now().strftime('%Y%m%d%H%M%S')}" self.state = "complete" return f"✅ Booking Confirmed!\n\nYour booking reference: {booking_ref}\n\nThank you for choosing our service! 🚗" elif incoming_msg == "no": self.state = "complete" return "Booking cancelled. Thank you for your time!" else: return "Please reply with 'YES' to confirm or 'NO' to cancel:" else: return "Thank you for using our service! Send 'hi' to start a new booking." def save_to_excel(self): data = { "Booking Date": datetime.now().strftime("%Y-%m-%d %H:%M"), "Customer Name": self.customer_info["name"], "Email": self.customer_info["email"], "Phone": self.customer_info["phone"], "License": self.customer_info["license"], "Car Category": self.rental_info["category"], "Pickup Date": self.rental_info["pickup_date"].strftime("%Y-%m-%d"), "Days": self.rental_info["days"], "Location": self.rental_info["location"], "Total Cost": self.rental_info["total_cost"] } excel_file = "whatsapp_car_rentals.xlsx" if os.path.exists(excel_file): df = pd.read_excel(excel_file) df = pd.concat([df, pd.DataFrame([data])], ignore_index=True) else: df = pd.DataFrame([data]) df.to_excel(excel_file, index=False) @app.route("/webhook", methods=['POST']) def webhook(): incoming_msg = request.values.get('Body', '').strip() from_number = request.values.get('From', '') # Get or create conversation for this number if from_number not in conversations: conversations[from_number] = WhatsAppCarRentalAgent(from_number) agent = conversations[from_number] response_text = agent.process_message(incoming_msg) # Create response resp = MessagingResponse() resp.message(response_text) return str(resp) if __name__ == "__main__": app.run(debug=True, port=5000)Setup Instructions:
1. Install Required Packages:
pip install flask twilio pandas openpyxl2. Set up Twilio:
- Sign up for a Twilio account at twilio.com
- Get a WhatsApp-enabled phone number
- Configure the webhook URL in Twilio Console
3. Deploy Options:
Option A: Local Testing with ngrok
# Install ngrok # Run your Flask app python whatsapp_car_rental.py # In another terminal, expose your local server ngrok http 5000 # Copy the HTTPS URL and set it as webhook in Twilio # Format: https://your-ngrok-url.ngrok.io/webhookOption B: Deploy to Cloud (Recommended for Production)
For Heroku: Create these files:
requirements.txt:flask twilio pandas openpyxl gunicornProcfile:web: gunicorn app:appThen deploy:
heroku create your-car-rental-bot git add . git commit -m "Initial commit" git push heroku mainFor Railway.app (Easier alternative):
- Push your code to GitHub
- Connect Railway to your GitHub repo
- It will auto-deploy
4. Configure Twilio Webhook:
- Go to Twilio Console > Messaging > Settings > WhatsApp Sandbox
- Set webhook URL:
https://your-app-url.com/webhook
5. Test Your Bot:
- Send a WhatsApp message to your Twilio number
- The bot will guide you through the rental process
Would you like me to explain any specific part of the setup or provide alternative deployment options?