// Telegram Bot для отправки изображений в ЛС
const axios = require('axios');
const config = require('./config');
const TELEGRAM_API = `https://api.telegram.org/bot${config.telegramBotToken}`;
// Отправить одно фото пользователю
async function sendPhotoToUser(userId, photoUrl, caption) {
try {
const response = await axios.post(`${TELEGRAM_API}/sendPhoto`, {
chat_id: userId,
photo: photoUrl,
caption: caption || '',
parse_mode: 'HTML'
});
return response.data;
} catch (error) {
console.error('Ошибка отправки фото:', error.response?.data || error.message);
throw error;
}
}
// Отправить несколько фото группой (до 10 штук)
async function sendPhotosToUser(userId, photos) {
try {
// Telegram поддерживает до 10 фото в одной группе
const batches = [];
for (let i = 0; i < photos.length; i += 10) {
batches.push(photos.slice(i, i + 10));
}
const results = [];
for (const batch of batches) {
const media = batch.map((photo, index) => ({
type: 'photo',
media: photo.url,
caption: index === 0 ? `Из NakamaSpace\n${batch.length} фото` : undefined,
parse_mode: 'HTML'
}));
const response = await axios.post(`${TELEGRAM_API}/sendMediaGroup`, {
chat_id: userId,
media: media
});
results.push(response.data);
}
return results;
} catch (error) {
console.error('Ошибка отправки фото группой:', error.response?.data || error.message);
throw error;
}
}
// Обработать данные от Web App
async function handleWebAppData(userId, dataString) {
try {
const data = JSON.parse(dataString);
if (data.action === 'send_image') {
const caption = `Из NakamaSpace\n\n${data.caption || ''}`;
await sendPhotoToUser(userId, data.url, caption);
return { success: true, message: 'Изображение отправлено!' };
}
return { success: false, message: 'Неизвестное действие' };
} catch (error) {
console.error('Ошибка обработки данных:', error);
return { success: false, message: error.message };
}
}
module.exports = {
sendPhotoToUser,
sendPhotosToUser,
handleWebAppData
};