Kyrexi AI Bot Integration
Connect Baileys (UDMODZ Edition) to the Kyrexi AI Ecosystem to deploy an autonomous, streaming AI assistant directly inside WhatsApp. Kyrexi can generate text, draw images, generate video notes, manage conversation memory, and explain Baileys code to users in real-time.
🏗️ Architecture
graph LR
User["📱 WhatsApp User"]
Baileys["⚡ Baileys (amiudmodz)"]
KyrexiAPI["🧠 Kyrexi AI Endpoint"]
User -->|Sends Message| Baileys
Baileys -->|HTTP POST Stream| KyrexiAPI
KyrexiAPI -->|Stream Chunks| Baileys
Baileys -->|Real-time reply / Media| User
🚀 Setup & Integration
To connect your bot to Kyrexi AI, use the following production-ready implementation. It handles:
- Interactive Menu & Status Commands
- Dynamic AI Session Memory Clearing
- Streaming Text Responses
- Native Image & Video Note (PTV) Generation
Create bot.js in your project:
const makeWASocket = require('amiudmodz').default;
const { useMultiFileAuthState } = require('amiudmodz');
const axios = require('axios');
const fs = require('fs');
const KYREXI_KEY = 'kx_xfs0xp9p55nr5lscl7knx'; // Your Kyrexi Auth Key
const KYREXI_URL = 'https://kyrexi.udmodz.site';
const API_SECRET = 'uplink_alpha_92';
async function start() {
const { state, saveCreds } = await useMultiFileAuthState('auth_info');
const sock = makeWASocket({
auth: state,
printQRInTerminal: true
});
sock.ev.on('creds.update', saveCreds);
// Establish connection
sock.ev.on('connection.update', ({ connection }) => {
if (connection === 'open') {
console.log('🤖 Kyrexi AI WhatsApp Bot is Online!');
}
});
// Handle incoming messages
sock.ev.on('messages.upsert', async ({ messages, type }) => {
if (!messages?.length) return;
const msg = messages[0];
if (!msg.message || msg.key.fromMe) return;
const jid = msg.key.remoteJid;
// Don't respond to status updates, newsletter channels, or groups
if (!jid || jid.endsWith('@g.us') || jid.endsWith('@newsletter') || jid === 'status@broadcast') return;
const text = (msg.message.conversation || msg.message.extendedTextMessage?.text || '').trim();
if (!text) return;
const cmd = text.toLowerCase();
// Command: Clear Memory
if (cmd === '/clear' || cmd === '/reset') {
const chatId = `chat_${jid.replace(/\D/g, '')}`;
try {
await axios.delete(`${KYREXI_URL}/api/chats/${chatId}?secret=${API_SECRET}`, {
headers: { 'x-kyrexi-secret': API_SECRET }
});
await sock.sendMessage(jid, { text: '🌸 *AI Memory Cleared!* Start fresh.' }, { quoted: msg });
} catch (err) {
console.error('Failed to clear memory:', err.message);
}
return;
}
// Default: Chat with AI (Stream response)
await handleAiChat(sock, jid, msg, text);
});
}
/**
* Handle AI chat streaming & media generation responses
*/
async function handleAiChat(sock, jid, quoteMsg, prompt) {
try {
await sock.sendPresenceUpdate('composing', jid);
const phone = jid.replace(/\D/g, '');
const userId = `wa_${phone}`;
const chatId = `chat_${phone}`;
let hasSentProgressNotice = false;
const response = await fetch(`${KYREXI_URL}/api/chats/${chatId}/messages/stream`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'User-Agent': 'Kyrexi-Official-WhatsApp',
'x-kyrexi-secret': API_SECRET
},
body: JSON.stringify({ message: prompt, userId, chatId })
});
if (!response.ok) throw new Error(`Kyrexi HTTP Error ${response.status}`);
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let textResponse = '';
let base64Image = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
const raw = line.slice(6).trim();
if (raw === '[DONE]') continue;
try {
const payload = JSON.parse(raw);
if (payload.response) {
textResponse += payload.response;
// Send typing or media rendering notice
if (!hasSentProgressNotice && (textResponse.includes('Kyrexi is filming') || textResponse.includes('Kyrexi is painting'))) {
hasSentProgressNotice = true;
await sock.sendMessage(jid, { text: '🎨 *Kyrexi is processing your media request...* Please hold.' }, { quoted: quoteMsg });
}
} else if (payload.response_type === 'img_chunk' && payload.chunk) {
base64Image += payload.chunk;
} else if (payload.response_type === 'img_end') {
// Media output: Image
await sock.sendMessage(jid, {
image: Buffer.from(base64Image, 'base64'),
caption: 'Here is your generated image! 🎨'
}, { quoted: quoteMsg });
return;
}
} catch (e) {
// Parse err
}
}
}
// Clean up markdown/thinking tags from response text
const cleanReply = textResponse
.replace(/<thinking>[\s\S]*?<\/thinking>/g, '')
.replace(/<[^>]*>/g, '')
.trim();
if (!hasSentProgressNotice && cleanReply) {
await sock.sendMessage(jid, {
text: cleanReply,
contextInfo: {
externalAdReply: {
title: 'Kyrexi AI',
body: 'Connected with Baileys UDMODZ Edition',
thumbnailUrl: 'https://kyrexi.udmodz.site/kyrexi.png',
mediaType: 1
}
}
}, { quoted: quoteMsg });
}
} catch (err) {
console.error('AI chat failed:', err.message);
await sock.sendMessage(jid, { text: '😅 Kyrexi AI is temporarily unavailable. Please try again later.' }, { quoted: quoteMsg });
}
}
start().catch(console.error);
🎓 Dynamic Learning Assistant
Deploying the Kyrexi bot creates an interactive assistant right on WhatsApp. Users can ask questions to learn Baileys concepts dynamically, e.g.:
- "Show me how to send a custom template message using Baileys"
- "Explain the connection event listeners in Baileys"
- "How do I configure group metadata caching?"
Kyrexi uses the prompt history and its integrated reasoning engine to provide clean, styled code blocks and tables formatted specifically for WhatsApp.