WhatsappAgent / api.py
AamirMalik's picture
Create api.py
f9b9446 verified
# api.py (FastAPI Backend)
from fastapi import FastAPI, Request
import requests
import os
import json
from dotenv import load_dotenv
import sqlite3
import datetime
# Load environment variables
load_dotenv()
# Initialize FastAPI app
app = FastAPI()
# Database setup
DB_FILE = "messages.db"
conn = sqlite3.connect(DB_FILE, check_same_thread=False)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY, sender TEXT, message TEXT, response TEXT, category TEXT, timestamp TEXT)''')
conn.commit()
# Open-source LLM API
HF_API_URL = "https://api-inference.huggingface.co/models/facebook/blenderbot-400M-distill"
HF_API_KEY = os.getenv("HF_API_KEY")
# Twilio API config
TWILIO_ACCOUNT_SID = os.getenv("TWILIO_ACCOUNT_SID")
TWILIO_AUTH_TOKEN = os.getenv("TWILIO_AUTH_TOKEN")
TWILIO_PHONE_NUMBER = os.getenv("TWILIO_PHONE_NUMBER")
# Message categories
CATEGORIES = {"business": ["invoice", "meeting", "contract"], "personal": ["hello", "birthday", "dinner"], "spam": ["win", "free", "click"]}
# Helper functions
def categorize_message(message):
for category, keywords in CATEGORIES.items():
if any(keyword in message.lower() for keyword in keywords):
return category
return "general"
def generate_response(message, tone):
headers = {"Authorization": f"Bearer {HF_API_KEY}", "Content-Type": "application/json"}
payload = {"inputs": f"Respond in a {tone} tone: {message}"}
response = requests.post(HF_API_URL, headers=headers, json=payload)
return response.json().get("generated_text", "")
def send_message(to, message):
url = f"https://api.twilio.com/2010-04-01/Accounts/{TWILIO_ACCOUNT_SID}/Messages.json"
data = {"From": TWILIO_PHONE_NUMBER, "To": to, "Body": message}
response = requests.post(url, auth=(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN), data=data)
return response.status_code == 201
# Webhook for incoming messages
@app.post("/webhook")
async def receive_message(request: Request):
data = await request.json()
sender = data.get("From")
message = data.get("Body")
timestamp = datetime.datetime.now().isoformat()
# Categorize and generate response
category = categorize_message(message)
response_text = generate_response(message, tone="casual")
# Log message
c.execute("INSERT INTO messages (sender, message, response, category, timestamp) VALUES (?, ?, ?, ?, ?)",
(sender, message, response_text, category, timestamp))
conn.commit()
return {"status": "received"}