File size: 5,908 Bytes
f56987b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# kyrexis/messenger_integration.py
"""
Kyrexis Messenger AI Integration — Messenger Platform API + Sovereign Node

Real-time AI responses with quantum-enhanced processing.

The page_access_token is loaded from the KYREXIS_PAGE_ACCESS_TOKEN env var
(or passed explicitly). Never commit real tokens.
"""

from __future__ import annotations

import hashlib  # noqa: F401  (spec surface)
import json  # noqa: F401
import os
import time
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional

import requests


@dataclass
class MessengerMessage:
    """Messenger message structure."""

    recipient_id: str
    sender_id: str
    text: str
    timestamp: float
    attachments: Optional[List[Dict]] = None
    quick_replies: Optional[List[Dict]] = None


class KyrexisMessengerIntegration:
    """
    Kyrexis AI Messenger Integration — full Messenger Platform API.

    Quantum-enhanced message processing via the Kyrexis core. When no
    page access token is configured (or network is unavailable), the
    integration still works as a local echo/processor for testing.
    """

    def __init__(self, page_access_token: Optional[str] = None, verify_token: Optional[str] = None):
        self.page_access_token = (
            page_access_token
            or os.environ.get("KYREXIS_PAGE_ACCESS_TOKEN", "")
        )
        self.verify_token = verify_token
        self.base_url = "https://graph.facebook.com/v13.0"
        self.messages: List[Dict[str, Any]] = []
        self.conversations: Dict[str, List[Dict[str, Any]]] = {}
        self.active = False
        self.kyrexis_core = None

    def initialize(self, kyrexis_core) -> "KyrexisMessengerIntegration":
        """Initialize with the Kyrexis AI core."""
        self.kyrexis_core = kyrexis_core
        self.active = True
        print("🧠 Kyrexis Messenger Integration initialized")
        return self

    def send_message(
        self, recipient_id: str, message: str, quick_replies: Optional[List[Dict]] = None
    ) -> Dict[str, Any]:
        """Send a message via the Messenger Platform API."""
        if not self.active:
            raise RuntimeError("Messenger integration not active")

        data = {
            "recipient": {"id": recipient_id},
            "message": {"text": message},
        }
        if quick_replies:
            data["message"]["quick_replies"] = quick_replies

        # No token configured → local-mode (recorded, not transmitted)
        if not self.page_access_token:
            result = {"local": True, "message_id": f"local_{int(time.time())}"}
        else:
            response = requests.post(
                f"{self.base_url}/me/messages?access_token={self.page_access_token}",
                headers={"Content-Type": "application/json"},
                json=data,
                timeout=30,
            )
            if response.status_code != 200:
                raise Exception(f"Failed to send message: {response.text}")
            result = response.json()

        self.messages.append({
            "type": "outgoing",
            "recipient": recipient_id,
            "text": message,
            "timestamp": time.time(),
            "response": result,
        })
        return result

    def process_message(self, message: MessengerMessage) -> str:
        """Process an incoming message with the Kyrexis AI core."""
        if self.kyrexis_core is not None:
            response = self.kyrexis_core.generate_response(
                message.text, {"sender": message.sender_id}
            )
        else:
            response = f"🔮 Kyrexis AI: Message received at {time.time():.0f}"

        conversation_id = message.sender_id
        self.conversations.setdefault(conversation_id, []).append({
            "incoming": message.text,
            "response": response,
            "timestamp": time.time(),
        })
        return response

    def handle_webhook(self, payload: Dict[str, Any]) -> Dict[str, Any]:
        """Handle an incoming Messenger webhook payload."""
        if "entry" not in payload:
            return {"error": "Invalid webhook payload"}

        results = []
        for entry in payload["entry"]:
            sender_id = entry.get("sender", {}).get("id")
            if not sender_id:
                continue
            for messaging in entry.get("messaging", []):
                if "message" not in messaging:
                    continue
                message_data = messaging["message"]
                text = message_data.get("text", "")
                if not text:
                    continue
                msg = MessengerMessage(
                    recipient_id=messaging.get("recipient", {}).get("id"),
                    sender_id=sender_id,
                    text=text,
                    timestamp=messaging.get("timestamp", time.time()),
                )
                response = self.process_message(msg)
                send_result = self.send_message(sender_id, response)
                results.append({
                    "sender": sender_id,
                    "received": text,
                    "response": response,
                    "send_result": send_result,
                })
        return {"status": "success", "processed": len(results), "results": results}

    def get_conversation(self, user_id: str) -> List[Dict]:
        """Conversation history for a user."""
        return self.conversations.get(user_id, [])

    def get_status(self) -> Dict[str, Any]:
        """Integration status."""
        return {
            "active": self.active,
            "total_messages": len(self.messages),
            "total_conversations": len(self.conversations),
            "kyrexis_connected": self.kyrexis_core is not None,
            "token_configured": bool(self.page_access_token),
        }


# Singleton
messenger = KyrexisMessengerIntegration()