Spaces:
Running
on
Zero
Running
on
Zero
Update notifier.py
Browse files- notifier.py +38 -1
notifier.py
CHANGED
@@ -1,22 +1,59 @@
|
|
1 |
import os
|
|
|
2 |
from sendgrid import SendGridAPIClient
|
3 |
from sendgrid.helpers.mail import Mail
|
4 |
|
5 |
SENDGRID_API_KEY = os.getenv("SENDGRID_API_KEY")
|
6 |
EMAIL_TO = os.getenv("EMAIL_TO")
|
7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
def send_email_notification(user_message):
|
9 |
if not SENDGRID_API_KEY or not EMAIL_TO:
|
10 |
print("[Notifier] Missing SendGrid credentials.")
|
11 |
return
|
12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
print("[Notifier] Sending email via SendGrid SDK...")
|
14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
message = Mail(
|
16 |
from_email=EMAIL_TO,
|
17 |
to_emails=EMAIL_TO,
|
18 |
subject="RezAi Interaction",
|
19 |
-
html_content=
|
20 |
)
|
21 |
|
22 |
try:
|
|
|
1 |
import os
|
2 |
+
import requests
|
3 |
from sendgrid import SendGridAPIClient
|
4 |
from sendgrid.helpers.mail import Mail
|
5 |
|
6 |
SENDGRID_API_KEY = os.getenv("SENDGRID_API_KEY")
|
7 |
EMAIL_TO = os.getenv("EMAIL_TO")
|
8 |
|
9 |
+
def _get_user_ip():
|
10 |
+
try:
|
11 |
+
return requests.get("https://api.ipify.org", timeout=5).text
|
12 |
+
except requests.RequestException:
|
13 |
+
return "Unavailable"
|
14 |
+
|
15 |
+
def _get_geo_from_ip(ip):
|
16 |
+
try:
|
17 |
+
response = requests.get(f"http://ip-api.com/json/{ip}", timeout=5)
|
18 |
+
data = response.json()
|
19 |
+
if data["status"] == "success":
|
20 |
+
return {
|
21 |
+
"city": data.get("city", "Unknown"),
|
22 |
+
"region": data.get("regionName", "Unknown"),
|
23 |
+
"country": data.get("country", "Unknown"),
|
24 |
+
"error": ""
|
25 |
+
}
|
26 |
+
else:
|
27 |
+
return {"error": "Lookup failed"}
|
28 |
+
except Exception as e:
|
29 |
+
return {"error": str(e)}
|
30 |
+
|
31 |
def send_email_notification(user_message):
|
32 |
if not SENDGRID_API_KEY or not EMAIL_TO:
|
33 |
print("[Notifier] Missing SendGrid credentials.")
|
34 |
return
|
35 |
|
36 |
+
ip_address = _get_user_ip()
|
37 |
+
geo_info = _get_geo_from_ip(ip_address)
|
38 |
+
|
39 |
+
if geo_info.get("error"):
|
40 |
+
location_str = f"IP: {ip_address} (location unavailable)"
|
41 |
+
else:
|
42 |
+
location_str = f"{geo_info['city']}, {geo_info['region']}, {geo_info['country']} (IP: {ip_address})"
|
43 |
+
|
44 |
print("[Notifier] Sending email via SendGrid SDK...")
|
45 |
|
46 |
+
html_content = f"""
|
47 |
+
<strong>Someone interacted with RezAi!</strong><br><br>
|
48 |
+
<b>Message:</b><br>{user_message}<br><br>
|
49 |
+
<b>Location:</b><br>{location_str}
|
50 |
+
"""
|
51 |
+
|
52 |
message = Mail(
|
53 |
from_email=EMAIL_TO,
|
54 |
to_emails=EMAIL_TO,
|
55 |
subject="RezAi Interaction",
|
56 |
+
html_content=html_content
|
57 |
)
|
58 |
|
59 |
try:
|