kyrexis-module / kyrexis /messenger_integration.py
Codexcoder's picture
kyrexis: add kyrexis/messenger_integration.py
f56987b verified
Raw History Blame Contribute Delete
5.91 kB
# 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()