Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,74 +1,92 @@
|
|
1 |
from flask import Flask, request
|
2 |
import requests
|
3 |
-
import json
|
4 |
|
5 |
app = Flask(__name__)
|
6 |
|
7 |
-
#
|
8 |
-
|
|
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
14 |
|
15 |
payload = {
|
16 |
-
"
|
17 |
-
"
|
|
|
|
|
|
|
|
|
18 |
}
|
19 |
|
20 |
try:
|
21 |
-
response = requests.post(url, headers=headers,
|
22 |
response.raise_for_status()
|
23 |
-
response_data = response.json()
|
24 |
-
assistant_response = response_data.get("assistant_response", "No response received.")
|
25 |
-
return assistant_response
|
26 |
-
except Exception as err:
|
27 |
-
return f"An error occurred: {err}"
|
28 |
|
29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
@app.route("/webhook", methods=["GET"])
|
31 |
def verify_webhook():
|
32 |
-
# Facebook verification challenge
|
33 |
mode = request.args.get("hub.mode")
|
34 |
token = request.args.get("hub.verify_token")
|
35 |
challenge = request.args.get("hub.challenge")
|
36 |
|
37 |
-
if mode == "subscribe" and token == "123400":
|
38 |
return challenge
|
39 |
else:
|
40 |
return "Verification failed", 403
|
41 |
|
42 |
@app.route("/webhook", methods=["POST"])
|
43 |
def handle_message():
|
44 |
-
# Parse incoming message from Facebook
|
45 |
body = request.get_json()
|
46 |
-
print(body)
|
47 |
|
48 |
for entry in body["entry"]:
|
49 |
for messaging_event in entry["messaging"]:
|
50 |
-
if "message" in messaging_event:
|
51 |
sender_id = messaging_event["sender"]["id"]
|
52 |
-
message_text = messaging_event["message"]
|
53 |
|
54 |
-
#
|
55 |
-
|
56 |
-
ai_response = gpt4o_ai(message_text, chat_history)
|
57 |
|
58 |
-
# Send
|
59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
|
61 |
return "OK", 200
|
62 |
|
63 |
-
# Function to send a message back to Facebook Messenger
|
64 |
-
def send_message(recipient_id, message_text):
|
65 |
-
url = f"https://graph.facebook.com/v16.0/me/messages?access_token={PAGE_ACCESS_TOKEN}"
|
66 |
-
payload = {
|
67 |
-
"recipient": {"id": recipient_id},
|
68 |
-
"message": {"text": message_text}
|
69 |
-
}
|
70 |
-
response = requests.post(url, json=payload)
|
71 |
-
print(response.json())
|
72 |
-
|
73 |
if __name__ == "__main__":
|
74 |
app.run(host="0.0.0.0", port=7860, debug=True)
|
|
|
1 |
from flask import Flask, request
|
2 |
import requests
|
|
|
3 |
|
4 |
app = Flask(__name__)
|
5 |
|
6 |
+
# Configuration
|
7 |
+
AI_SERVICE_URL = "http://localhost:5001/send-message" # URL of the second service
|
8 |
+
AI_SERVICE_TOKEN = "123400" # Token for authentication between services
|
9 |
|
10 |
+
def duckduckgo_chat(user_input):
|
11 |
+
url = "https://duckduckgo.com/duckchat/v1/chat"
|
12 |
+
headers = {
|
13 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36",
|
14 |
+
"x-vqd-4": "4-104601921627559888837792224388986469408",
|
15 |
+
"Content-Type": "application/json"
|
16 |
+
}
|
17 |
|
18 |
payload = {
|
19 |
+
"model": "o3-mini",
|
20 |
+
"messages": [
|
21 |
+
{"role": "user", "content": "hi"},
|
22 |
+
{"role": "assistant", "content": "Hi there! How can I help you today?"},
|
23 |
+
{"role": "user", "content": user_input}
|
24 |
+
]
|
25 |
}
|
26 |
|
27 |
try:
|
28 |
+
response = requests.post(url, headers=headers, json=payload, timeout=15, stream=True)
|
29 |
response.raise_for_status()
|
|
|
|
|
|
|
|
|
|
|
30 |
|
31 |
+
full_response = ""
|
32 |
+
for line in response.iter_lines():
|
33 |
+
line = line.decode("utf-8")
|
34 |
+
if line.startswith("data: "):
|
35 |
+
json_str = line[6:].strip()
|
36 |
+
if not json_str or json_str == "[DONE]":
|
37 |
+
continue
|
38 |
+
try:
|
39 |
+
chunk = json.loads(json_str)
|
40 |
+
if "message" in chunk:
|
41 |
+
full_response += chunk["message"]
|
42 |
+
except json.JSONDecodeError:
|
43 |
+
print(f"Invalid JSON: {json_str}")
|
44 |
+
|
45 |
+
return full_response or "No response received"
|
46 |
+
|
47 |
+
except requests.exceptions.HTTPError as e:
|
48 |
+
print(f"HTTP Error: {e}")
|
49 |
+
return "An error occurred. Please try again."
|
50 |
+
except Exception as e:
|
51 |
+
print(f"Unexpected error: {e}")
|
52 |
+
return "An unexpected error occurred."
|
53 |
+
|
54 |
@app.route("/webhook", methods=["GET"])
|
55 |
def verify_webhook():
|
|
|
56 |
mode = request.args.get("hub.mode")
|
57 |
token = request.args.get("hub.verify_token")
|
58 |
challenge = request.args.get("hub.challenge")
|
59 |
|
60 |
+
if mode == "subscribe" and token == "123400": # Replace "123400" with your actual verify token
|
61 |
return challenge
|
62 |
else:
|
63 |
return "Verification failed", 403
|
64 |
|
65 |
@app.route("/webhook", methods=["POST"])
|
66 |
def handle_message():
|
|
|
67 |
body = request.get_json()
|
|
|
68 |
|
69 |
for entry in body["entry"]:
|
70 |
for messaging_event in entry["messaging"]:
|
71 |
+
if "message" in messaging_event and "text" in messaging_event["message"]:
|
72 |
sender_id = messaging_event["sender"]["id"]
|
73 |
+
message_text = messaging_event["message"]["text"]
|
74 |
|
75 |
+
# Get AI response
|
76 |
+
ai_response = duckduckgo_chat(message_text)
|
|
|
77 |
|
78 |
+
# Send response to messaging service
|
79 |
+
headers = {
|
80 |
+
"Authorization": f"Bearer {AI_SERVICE_TOKEN}",
|
81 |
+
"Content-Type": "application/json"
|
82 |
+
}
|
83 |
+
payload = {
|
84 |
+
"recipient_id": sender_id,
|
85 |
+
"message_text": ai_response
|
86 |
+
}
|
87 |
+
requests.post(AI_SERVICE_URL, json=payload, headers=headers)
|
88 |
|
89 |
return "OK", 200
|
90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
if __name__ == "__main__":
|
92 |
app.run(host="0.0.0.0", port=7860, debug=True)
|