Ainew / server.js
Ainew AI
πŸ€– Add Telegram channel support
e3b44dc
Raw
History Blame Contribute Delete
2.71 kB
const http = require('http');
const fs = require('fs');
const path = require('path');
const { spawn } = require('child_process');
const GATEWAY_PORT = 18789;
const WEB_PORT = 7860;
// Start OpenClaw Gateway as child process
console.log('πŸ€– Checking Telegram...');
if (process.env.TELEGRAM_BOT_TOKEN) {
console.log(`βœ… Telegram Bot Token found (${process.env.TELEGRAM_BOT_TOKEN.substring(0, 8)}...${process.env.TELEGRAM_BOT_TOKEN.slice(-4)})`);
} else {
console.log('⚠️ No Telegram Bot Token set');
}
const gateway = spawn('openclaw', ['gateway', '--port', String(GATEWAY_PORT), '--bind', 'lan'], {
stdio: ['pipe', 'inherit', 'inherit'],
env: {
...process.env,
OPENCLAW_CONFIG_PATH: '/app/openclaw.json',
}
});
gateway.on('error', (err) => {
console.error('❌ Failed to start OpenClaw Gateway:', err);
});
gateway.on('exit', (code) => {
console.log(`❌ OpenClaw Gateway exited with code ${code}`);
});
// Read HTML template
const html = fs.readFileSync(path.join(__dirname, 'index.html'), 'utf-8');
// Create web server for chat UI
const server = http.createServer((req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
// Serve static files
if (url.pathname === '/' || url.pathname === '/index.html') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(html);
return;
}
// Proxy API requests to OpenClaw Gateway
if (url.pathname.startsWith('/api/')) {
const options = {
hostname: '127.0.0.1',
port: GATEWAY_PORT,
path: url.pathname + url.search,
method: req.method,
headers: {
...req.headers,
host: `127.0.0.1:${GATEWAY_PORT}`,
}
};
const proxyReq = http.request(options, (proxyRes) => {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res);
});
proxyReq.on('error', (err) => {
res.writeHead(502, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Gateway unavailable', details: err.message }));
});
req.pipe(proxyReq);
return;
}
// 404 for everything else
res.writeHead(404);
res.end('Not Found');
});
server.listen(WEB_PORT, '0.0.0.0', () => {
console.log(`🌐 Web UI running on http://0.0.0.0:${WEB_PORT}`);
console.log(`🦞 OpenClaw Gateway running on http://127.0.0.1:${GATEWAY_PORT}`);
});
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('Shutting down...');
gateway.kill('SIGTERM');
server.close();
process.exit(0);
});