Spaces:
Sleeping
Sleeping
from flask import Flask, request | |
from twilio.twiml.messaging_response import MessagingResponse | |
from twilio.rest import Client | |
import os | |
# Initialize the Flask app | |
app = Flask(__name__) | |
account_sid = os.environ.get('TWILIO_ACCOUNT_SID') | |
auth_token = os.environ.get('TWILIO_AUTH_TOKEN') | |
client = Client(account_sid, auth_token) | |
# OpenAI API Key | |
# WhatsApp number to send messages from (your Twilio number) | |
from_whatsapp_number = 'whatsapp:+14155238886' | |
# Route to handle incoming WhatsApp messages | |
def whatsapp_webhook(): | |
incoming_msg = request.values.get('Body', '').lower() | |
sender = request.values.get('From') | |
if 'bookkeeping' in incoming_msg: | |
response_text = "Please provide the details you'd like to record." | |
else: | |
response_text = get_agricultural_insights(incoming_msg) | |
send_message(sender, response_text) | |
return '', 204 # Return an empty response to Twilio | |
def get_agricultural_insights(query): | |
return "I'm sorry, I couldn't process that request. Please try again later." | |
def send_message(to, body): | |
try: | |
message = client.messages.create( | |
from_=from_whatsapp_number, | |
body=body, | |
to=to | |
) | |
print(f"Message sent with SID: {message.sid}") | |
except Exception as e: | |
print(f"Error sending message: {e}") | |
# Function to send an initial message | |
def send_initial_message(to_number): | |
send_message( | |
f'whatsapp:{to_number}', | |
'Welcome to the Agri AI Chatbot! How can I assist you today?' | |
) | |
if __name__ == '__main__': | |
# Send an initial message when the script starts | |
send_initial_message('916382792828') # Replace with the recipient's number | |
# Start the Flask server | |
app.run(host='0.0.0.0', port=7860) |