File size: 2,123 Bytes
0127166
a30b2ab
0127166
 
a4c92de
0127166
 
3b38e86
a30b2ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b38e86
0127166
 
a4c92de
 
a30b2ab
 
 
 
 
 
 
 
0127166
a4c92de
a30b2ab
 
 
 
 
 
0127166
 
 
 
a30b2ab
0127166
a4c92de
 
0127166
 
 
 
 
 
a4c92de
c143dce
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import os
import requests
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

SENDGRID_API_KEY = os.getenv("SENDGRID_API_KEY")
EMAIL_TO = os.getenv("EMAIL_TO")

def _get_user_ip():
    try:
        return requests.get("https://api.ipify.org", timeout=5).text
    except requests.RequestException:
        return "Unavailable"

def _get_geo_from_ip(ip):
    try:
        response = requests.get(f"http://ip-api.com/json/{ip}", timeout=5)
        data = response.json()
        if data["status"] == "success":
            return {
                "city": data.get("city", "Unknown"),
                "region": data.get("regionName", "Unknown"),
                "country": data.get("country", "Unknown"),
                "error": ""
            }
        else:
            return {"error": "Lookup failed"}
    except Exception as e:
        return {"error": str(e)}

def send_email_notification(user_message):
    if not SENDGRID_API_KEY or not EMAIL_TO:
        print("[Notifier] Missing SendGrid credentials.")
        return

    ip_address = _get_user_ip()
    geo_info = _get_geo_from_ip(ip_address)

    if geo_info.get("error"):
        location_str = f"IP: {ip_address} (location unavailable)"
    else:
        location_str = f"{geo_info['city']}, {geo_info['region']}, {geo_info['country']} (IP: {ip_address})"

    print("[Notifier] Sending email via SendGrid SDK...")

    html_content = f"""
    <strong>Someone interacted with RezAi!</strong><br><br>
    <b>Message:</b><br>{user_message}<br><br>
    <b>Location:</b><br>{location_str}
    """

    message = Mail(
        from_email=EMAIL_TO,
        to_emails=EMAIL_TO,
        subject="RezAi Interaction",
        html_content=html_content
    )

    try:
        sg = SendGridAPIClient(SENDGRID_API_KEY)
        response = sg.send(message)
        if response.status_code == 202:
            print("[Notifier] βœ… Email sent successfully!")
        else:
            print(f"[Notifier] ❌ SendGrid SDK failed: {response.status_code} – {response.body}")
    except Exception as e:
        print(f"[Notifier] ❌ Exception: {e}")