# Telegram Bot Hosting Dashboard (Node.js + React)
Here's a simplified structure for your Telegram bot hosting dashboard that you can deploy on Vercel:
## Folder Structure
```
/telegram-bot-host/
├── /api/ # Vercel serverless functions
│ └── bot-manager.js # Node.js backend API
├── /public/ # Static files
├── /src/ # React frontend
│ ├── App.js # Main component
│ └── index.js # React entry point
├── package.json # Project dependencies
└── vercel.json # Vercel configuration
```
## 1. Backend (Node.js API) - `/api/bot-manager.js`
```javascript
const { Telegraf } = require('telegraf');
const fs = require('fs');
const path = require('path');
// In-memory storage (replace with database in production)
let bots = {};
module.exports = async (req, res) => {
if (req.method === 'GET') {
// Return list of bots
return res.json({ bots });
}
if (req.method === 'POST') {
const { action, botName, botToken } = req.body;
try {
if (action === 'create') {
// Create new bot
const bot = new Telegraf(botToken);
bots[botName] = { bot, token: botToken, running: false };
// Simple echo bot functionality
bot.on('text', (ctx) => ctx.reply(`Echo: ${ctx.message.text}`));
return res.json({ success: true, message: 'Bot created' });
}
if (action === 'start') {
// Start bot
if (!bots[botName]) throw new Error('Bot not found');
bots[botName].bot.launch();
bots[botName].running = true;
return res.json({ success: true, message: 'Bot started' });
}
if (action === 'stop') {
// Stop bot
if (!bots[botName]) throw new Error('Bot not found');
bots[botName].bot.stop();
bots[botName].running = false;
return res.json({ success: true, message: 'Bot stopped' });
}
if (action === 'delete') {
// Delete bot
if (bots[botName]?.running) {
bots[botName].bot.stop();
}
delete bots[botName];
return res.json({ success: true, message: 'Bot deleted' });
}
} catch (error) {
return res.status(500).json({ success: false, message: error.message });
}
}
return res.status(404).json({ error: 'Not found' });
};
```
## 2. Frontend (React) - `/src/App.js`
```jsx
import React, { useState, useEffect } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Container, Row, Col, Card, Button, Modal, Form } from 'react-bootstrap';
function App() {
const [bots, setBots] = useState([]);
const [showModal, setShowModal] = useState(false);
const [botName, setBotName] = useState('');
const [botToken, setBotToken] = useState('');
useEffect(() => {
fetch('/api/bot-manager')
.then(res => res.json())
.then(data => setBots(Object.keys(data.bots || {}).map(name => ({
name,
running: data.bots[name].running
}))));
}, []);
const handleCreateBot = () => {
fetch('/api/bot-manager', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'create', botName, botToken })
})
.then(res => res.json())
.then(() => {
setBots([...bots, { name: botName, running: false }]);
setShowModal(false);
setBotName('');
setBotToken('');
});
};
const handleBotAction = (botName, action) => {
fetch('/api/bot-manager', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action, botName })
})
.then(res => res.json())
.then(() => {
setBots(bots.map(bot =>
bot.name === botName ? { ...bot, running: action === 'start' } : bot
));
});
};
const handleDeleteBot = (botName) => {
fetch('/api/bot-manager', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'delete', botName })
})
.then(res => res.json())
.then(() => {
setBots(bots.filter(bot => bot.name !== botName));
});
};
return (
<Container className="mt-5">
<Row className="mb-4">
<Col>
<h1>Telegram Bot Hosting</h1>
<Button variant="primary" onClick={() => setShowModal(true)}>
Create New Bot
</Button>
</Col>
</Row>
<Row>
{bots.map((bot, index) => (
<Col md={4} key={index} className="mb-4">
<Card>
<Card.Body>
<Card.Title>{bot.name}</Card.Title>
<Card.Text>
Status: {bot.running ? 'Running' : 'Stopped'}
</Card.Text>
<div className="d-flex justify-content-between">
{bot.running ? (
<Button variant="danger" onClick={() => handleBotAction(bot.name, 'stop')}>
Stop
</Button>
) : (
<Button variant="success" onClick={() => handleBotAction(bot.name, 'start')}>
Start
</Button>
)}
<Button variant="warning" onClick={() => handleDeleteBot(bot.name)}>
Delete
</Button>
</div>
</Card.Body>
</Card>
</Col>
))}
</Row>
<Modal show={showModal} onHide={() => setShowModal(false)}>
<Modal.Header closeButton>
<Modal.Title>Create New Bot</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form>
<Form.Group className="mb-3">
<Form.Label>Bot Name</Form.Label>
<Form.Control
type="text"
value={botName}
onChange={(e) => setBotName(e.target.value)}
/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Bot Token</Form.Label>
<Form.Control
type="text"
value={botToken}
onChange={(e) => setBotToken(e.target.value)}
placeholder="From @BotFather"
/>
</Form.Group>
</Form>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={() => setShowModal(false)}>
Close
</Button>
<Button variant="primary" onClick={handleCreateBot}>
Create Bot
</Button>
</Modal.Footer>
</Modal>
</Container>
);
}
export default App;
```
## 3. Configuration Files
### `/package.json`
```json
{
"name": "telegram-bot-host",
"version": "1.0.0",
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"dependencies": {
"bootstrap": "^5.3.0",
"react": "^18.2.0",
"react-bootstrap": "^2.7.2",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"telegraf": "^4.11.2",
"web-vitals": "^2.1.4"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
}
}
```
### `/vercel.json`
```json
{
"version": 2,
"builds": [
{
"src": "package.json",
"use": "@vercel/static-build",
"config": { "distDir": "build" }
},
{
"src": "api/bot-manager.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/api/(.*)",
"dest": "/api/bot-manager"
},
{
"src": "/(.*)",
"dest": "/"
}
]
}
```
## Important Notes:
1. **This is a simplified version** - In production, you should:
- Use a proper database instead of in-memory storage
- Add authentication
- Implement error handling
- Add rate limiting
- Secure your API endpoints
2. **Vercel Limitations**:
- Serverless functions have execution time limits
- Bots will stop when the function ends (not persistent)
- For persistent bots, consider a dedicated server or cloud VM
3. **To Deploy**:
- Push this code to a GitHub repository
- Import it in Vercel
- Vercel will automatically detect and deploy both frontend and API
4. **Environment Variables**:
- You may want to add sensitive data (like default bot tokens) in Vercel's environment variables
Would you like me to explain any specific part in more detail or make adjustments to any functionality?
Comments
Post a Comment