nakama/backend/routes/bot.js

166 lines
5.4 KiB
JavaScript
Raw Normal View History

2025-11-03 22:17:25 +00:00
const express = require('express');
const router = express.Router();
2025-12-15 07:28:47 +00:00
const { sendPhotoToUser, sendPhotosToUser, sendAudioToUser } = require('../bot');
2025-11-03 22:17:25 +00:00
const { authenticate } = require('../middleware/auth');
2025-12-15 07:28:47 +00:00
const Track = require('../models/Track');
2025-11-03 22:17:25 +00:00
// Endpoint для отправки одного фото в ЛС
router.post('/send-photo', authenticate, async (req, res) => {
try {
const { userId, photoUrl, caption } = req.body;
if (!userId || !photoUrl) {
return res.status(400).json({ error: 'userId и photoUrl обязательны' });
}
2025-12-08 14:06:57 +00:00
// Преобразуем userId в число, если это строка (Telegram API ожидает число)
const telegramUserId = typeof userId === 'string' ? parseInt(userId, 10) : userId;
if (isNaN(telegramUserId)) {
return res.status(400).json({ error: 'userId должен быть числом' });
}
// Валидация URL
if (typeof photoUrl !== 'string' || photoUrl.trim().length === 0) {
return res.status(400).json({ error: 'photoUrl должен быть непустой строкой' });
}
const result = await sendPhotoToUser(telegramUserId, photoUrl.trim(), caption);
2025-11-03 22:17:25 +00:00
res.json({
success: true,
message: 'Изображение отправлено в ваш Telegram',
result
});
} catch (error) {
2025-12-08 14:06:57 +00:00
console.error('Ошибка отправки фото:', {
error: error.message,
stack: error.stack,
response: error.response?.data,
userId: req.body?.userId,
photoUrl: req.body?.photoUrl
});
2025-11-03 22:17:25 +00:00
res.status(500).json({
error: 'Ошибка отправки изображения',
2025-12-08 14:06:57 +00:00
details: error.response?.data?.description || error.message
2025-11-03 22:17:25 +00:00
});
}
});
// Endpoint для отправки нескольких фото группой
router.post('/send-photos', authenticate, async (req, res) => {
try {
const { userId, photos } = req.body;
if (!userId || !photos || !Array.isArray(photos) || photos.length === 0) {
return res.status(400).json({ error: 'userId и массив photos обязательны' });
}
if (photos.length > 50) {
return res.status(400).json({ error: 'Максимум 50 фото за раз' });
}
const results = await sendPhotosToUser(userId, photos);
res.json({
success: true,
message: `${photos.length} изображений отправлено в ваш Telegram`,
results
});
} catch (error) {
console.error('Ошибка отправки фото:', error);
res.status(500).json({
error: 'Ошибка отправки изображений',
details: error.message
});
}
});
2025-12-15 07:28:47 +00:00
// Endpoint для отправки трека в ЛС
router.post('/send-track', authenticate, async (req, res) => {
try {
const { userId, trackId } = req.body;
if (!userId || !trackId) {
return res.status(400).json({ error: 'userId и trackId обязательны' });
}
// Преобразуем userId в число
const telegramUserId = typeof userId === 'string' ? parseInt(userId, 10) : userId;
if (isNaN(telegramUserId)) {
return res.status(400).json({ error: 'userId должен быть числом' });
}
// Получить трек из базы
const track = await Track.findById(trackId).populate('artist album');
if (!track) {
return res.status(404).json({ error: 'Трек не найден' });
}
// Отправить трек
const result = await sendAudioToUser(telegramUserId, track.fileUrl, {
title: track.title,
artist: track.artist?.name,
duration: track.file?.duration
});
// Увеличить счетчик скачиваний
track.stats.downloads += 1;
await track.save();
res.json({
success: true,
message: 'Трек отправлен в ваш Telegram',
result
});
} catch (error) {
console.error('Ошибка отправки трека:', {
error: error.message,
stack: error.stack,
response: error.response?.data,
userId: req.body?.userId,
trackId: req.body?.trackId
});
res.status(500).json({
error: 'Ошибка отправки трека',
details: error.response?.data?.description || error.message
});
}
});
2025-12-04 17:44:05 +00:00
// Отправить сообщение всем пользователям (только админы)
router.post('/broadcast', authenticate, async (req, res) => {
try {
// Проверка прав админа
if (req.user.role !== 'admin') {
return res.status(403).json({ error: 'Требуются права администратора' });
}
const { message } = req.body;
if (!message || !message.trim()) {
return res.status(400).json({ error: 'Сообщение обязательно' });
}
const { sendMessageToAllUsers } = require('../bots/mainBot');
const result = await sendMessageToAllUsers(message);
res.json({
success: true,
message: `Сообщение отправлено ${result.sent} пользователям`,
result
});
} catch (error) {
console.error('Ошибка рассылки:', error);
res.status(500).json({
error: 'Ошибка отправки сообщений',
details: error.message
});
}
});
2025-11-03 22:17:25 +00:00
module.exports = router;