transcript / app.py
CORVO-AI's picture
Update app.py
678d88b verified
raw
history blame
3.2 kB
import requests
from flask import Flask, request, jsonify
from datetime import datetime
import json
app = Flask(__name__)
# Your PythonAnywhere API endpoint
PYTHONANYWHERE_URL = "https://omarnuwara.pythonanywhere.com/get-response"
# URL of the GitHub-hosted JSON database
USER_DB_URL = "https://raw.githubusercontent.com/omarnuwrar/api/refs/heads/main/user.json"
def get_users_from_db():
"""Fetch user data from the GitHub JSON file."""
try:
response = requests.get(USER_DB_URL)
if response.status_code == 200:
return response.json()
else:
raise Exception("Failed to fetch the user database.")
except Exception as e:
raise Exception(f"Error fetching user database: {str(e)}")
def validate_token(token):
"""Validate the token from the GitHub-hosted database."""
try:
users = get_users_from_db()
# Look for the token in the database
for user in users:
if user["token"] == token:
# Check if the token is expired
expiration_time = datetime.fromisoformat(user["token_expiration_time"])
if datetime.now() < expiration_time:
return True, None # Token is valid
else:
return False, "Token is expired."
return False, "Token not found." # Token not found in the database
except Exception as e:
return False, f"Error validating token: {str(e)}"
@app.route('/chat', methods=['POST'])
def chat():
try:
# Ensure the request contains JSON and a "message" and "token" key
if not request.is_json:
return jsonify({"error": "Request must be in JSON format."}), 400
user_input = request.json.get("message", "")
token = request.json.get("token", "")
if not user_input:
return jsonify({"error": "No message provided in the request."}), 400
if not token:
return jsonify({"error": "No token provided in the request."}), 400
# Validate the token
token_valid, token_message = validate_token(token)
if not token_valid:
return jsonify({"error": "Invalid token.", "details": token_message}), 401
# Create the payload to send to PythonAnywhere
data = {"message": user_input}
# Forward the request to PythonAnywhere
response = requests.post(PYTHONANYWHERE_URL, json=data)
if response.status_code == 200:
response_json = response.json()
ai_response = response_json.get("response", "No 'response' key found in the JSON.")
ai_response = ai_response.encode('latin1').decode('utf-8', 'ignore')
return jsonify({"response": ai_response})
else:
# Handle errors from PythonAnywhere
return jsonify({
"error": "Error from PythonAnywhere",
"details": response.text
}), response.status_code
except Exception as e:
# Catch any unexpected errors
return jsonify({"error": "An error occurred", "details": str(e)}), 500
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860)