nakama/backend/bot.js

114 lines
3.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Telegram Bot для отправки изображений в ЛС
const axios = require('axios');
const config = require('./config');
if (!config.telegramBotToken) {
console.warn('⚠️ TELEGRAM_BOT_TOKEN не установлен! Функция отправки фото в Telegram недоступна.');
}
const TELEGRAM_API = config.telegramBotToken
? `https://api.telegram.org/bot${config.telegramBotToken}`
: null;
// Отправить одно фото пользователю
async function sendPhotoToUser(userId, photoUrl, caption) {
if (!TELEGRAM_API) {
throw new Error('TELEGRAM_BOT_TOKEN не установлен');
}
try {
// Если photoUrl относительный (начинается с /), преобразуем в полный URL
let finalPhotoUrl = photoUrl;
if (photoUrl.startsWith('/')) {
// Если это прокси URL, нужно получить полный URL
// Для production используем домен из переменной окружения или дефолтный
const baseUrl = process.env.FRONTEND_URL || process.env.API_URL || 'https://nakama.glpshchn.ru';
finalPhotoUrl = `${baseUrl}${photoUrl}`;
}
const response = await axios.post(`${TELEGRAM_API}/sendPhoto`, {
chat_id: userId,
photo: finalPhotoUrl,
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) {
if (!TELEGRAM_API) {
throw new Error('TELEGRAM_BOT_TOKEN не установлен');
}
try {
// Telegram поддерживает до 10 фото в одной группе
const batches = [];
for (let i = 0; i < photos.length; i += 10) {
batches.push(photos.slice(i, i + 10));
}
const results = [];
const baseUrl = process.env.FRONTEND_URL || process.env.API_URL || 'https://nakama.glpshchn.ru';
for (const batch of batches) {
const media = batch.map((photo, index) => {
// Преобразуем относительные URL в полные
let photoUrl = photo.url;
if (photoUrl.startsWith('/')) {
photoUrl = `${baseUrl}${photoUrl}`;
}
return {
type: 'photo',
media: photoUrl,
caption: index === 0 ? `<b>Из NakamaSpace</b>\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 = `<b>Из NakamaSpace</b>\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
};