Codexcoder commited on
Commit
f56987b
·
verified ·
1 Parent(s): c7ae49e

kyrexis: add kyrexis/messenger_integration.py

Browse files
Files changed (1) hide show
  1. kyrexis/messenger_integration.py +166 -0
kyrexis/messenger_integration.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # kyrexis/messenger_integration.py
2
+ """
3
+ Kyrexis Messenger AI Integration — Messenger Platform API + Sovereign Node
4
+
5
+ Real-time AI responses with quantum-enhanced processing.
6
+
7
+ The page_access_token is loaded from the KYREXIS_PAGE_ACCESS_TOKEN env var
8
+ (or passed explicitly). Never commit real tokens.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import hashlib # noqa: F401 (spec surface)
14
+ import json # noqa: F401
15
+ import os
16
+ import time
17
+ from dataclasses import dataclass, field
18
+ from typing import Any, Dict, List, Optional
19
+
20
+ import requests
21
+
22
+
23
+ @dataclass
24
+ class MessengerMessage:
25
+ """Messenger message structure."""
26
+
27
+ recipient_id: str
28
+ sender_id: str
29
+ text: str
30
+ timestamp: float
31
+ attachments: Optional[List[Dict]] = None
32
+ quick_replies: Optional[List[Dict]] = None
33
+
34
+
35
+ class KyrexisMessengerIntegration:
36
+ """
37
+ Kyrexis AI Messenger Integration — full Messenger Platform API.
38
+
39
+ Quantum-enhanced message processing via the Kyrexis core. When no
40
+ page access token is configured (or network is unavailable), the
41
+ integration still works as a local echo/processor for testing.
42
+ """
43
+
44
+ def __init__(self, page_access_token: Optional[str] = None, verify_token: Optional[str] = None):
45
+ self.page_access_token = (
46
+ page_access_token
47
+ or os.environ.get("KYREXIS_PAGE_ACCESS_TOKEN", "")
48
+ )
49
+ self.verify_token = verify_token
50
+ self.base_url = "https://graph.facebook.com/v13.0"
51
+ self.messages: List[Dict[str, Any]] = []
52
+ self.conversations: Dict[str, List[Dict[str, Any]]] = {}
53
+ self.active = False
54
+ self.kyrexis_core = None
55
+
56
+ def initialize(self, kyrexis_core) -> "KyrexisMessengerIntegration":
57
+ """Initialize with the Kyrexis AI core."""
58
+ self.kyrexis_core = kyrexis_core
59
+ self.active = True
60
+ print("🧠 Kyrexis Messenger Integration initialized")
61
+ return self
62
+
63
+ def send_message(
64
+ self, recipient_id: str, message: str, quick_replies: Optional[List[Dict]] = None
65
+ ) -> Dict[str, Any]:
66
+ """Send a message via the Messenger Platform API."""
67
+ if not self.active:
68
+ raise RuntimeError("Messenger integration not active")
69
+
70
+ data = {
71
+ "recipient": {"id": recipient_id},
72
+ "message": {"text": message},
73
+ }
74
+ if quick_replies:
75
+ data["message"]["quick_replies"] = quick_replies
76
+
77
+ # No token configured → local-mode (recorded, not transmitted)
78
+ if not self.page_access_token:
79
+ result = {"local": True, "message_id": f"local_{int(time.time())}"}
80
+ else:
81
+ response = requests.post(
82
+ f"{self.base_url}/me/messages?access_token={self.page_access_token}",
83
+ headers={"Content-Type": "application/json"},
84
+ json=data,
85
+ timeout=30,
86
+ )
87
+ if response.status_code != 200:
88
+ raise Exception(f"Failed to send message: {response.text}")
89
+ result = response.json()
90
+
91
+ self.messages.append({
92
+ "type": "outgoing",
93
+ "recipient": recipient_id,
94
+ "text": message,
95
+ "timestamp": time.time(),
96
+ "response": result,
97
+ })
98
+ return result
99
+
100
+ def process_message(self, message: MessengerMessage) -> str:
101
+ """Process an incoming message with the Kyrexis AI core."""
102
+ if self.kyrexis_core is not None:
103
+ response = self.kyrexis_core.generate_response(
104
+ message.text, {"sender": message.sender_id}
105
+ )
106
+ else:
107
+ response = f"🔮 Kyrexis AI: Message received at {time.time():.0f}"
108
+
109
+ conversation_id = message.sender_id
110
+ self.conversations.setdefault(conversation_id, []).append({
111
+ "incoming": message.text,
112
+ "response": response,
113
+ "timestamp": time.time(),
114
+ })
115
+ return response
116
+
117
+ def handle_webhook(self, payload: Dict[str, Any]) -> Dict[str, Any]:
118
+ """Handle an incoming Messenger webhook payload."""
119
+ if "entry" not in payload:
120
+ return {"error": "Invalid webhook payload"}
121
+
122
+ results = []
123
+ for entry in payload["entry"]:
124
+ sender_id = entry.get("sender", {}).get("id")
125
+ if not sender_id:
126
+ continue
127
+ for messaging in entry.get("messaging", []):
128
+ if "message" not in messaging:
129
+ continue
130
+ message_data = messaging["message"]
131
+ text = message_data.get("text", "")
132
+ if not text:
133
+ continue
134
+ msg = MessengerMessage(
135
+ recipient_id=messaging.get("recipient", {}).get("id"),
136
+ sender_id=sender_id,
137
+ text=text,
138
+ timestamp=messaging.get("timestamp", time.time()),
139
+ )
140
+ response = self.process_message(msg)
141
+ send_result = self.send_message(sender_id, response)
142
+ results.append({
143
+ "sender": sender_id,
144
+ "received": text,
145
+ "response": response,
146
+ "send_result": send_result,
147
+ })
148
+ return {"status": "success", "processed": len(results), "results": results}
149
+
150
+ def get_conversation(self, user_id: str) -> List[Dict]:
151
+ """Conversation history for a user."""
152
+ return self.conversations.get(user_id, [])
153
+
154
+ def get_status(self) -> Dict[str, Any]:
155
+ """Integration status."""
156
+ return {
157
+ "active": self.active,
158
+ "total_messages": len(self.messages),
159
+ "total_conversations": len(self.conversations),
160
+ "kyrexis_connected": self.kyrexis_core is not None,
161
+ "token_configured": bool(self.page_access_token),
162
+ }
163
+
164
+
165
+ # Singleton
166
+ messenger = KyrexisMessengerIntegration()