From 6e32241fe82cf40c5d4d1460fa04b0efb42edb57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B8=D0=BA=20=28Claude=29?= Date: Thu, 11 Jun 2026 19:54:31 +0300 Subject: [PATCH] feat: P7 polls + P8 hashtags MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P7 — Опросы в Telegram: - routes/polls.js: POST /api/channels/:id/poll (sendPoll + schedule support) - DB: scheduled_posts.post_type + meta для отложенных опросов - scheduledPostsRunner: обработка post_type='poll' через sendPoll - index.js: роут /api/channels подключён P8 — Хештеги: - ai.js: generateHashtags() через Claude Haiku, JSON-массив тегов - routes/generate.js: POST /api/generate/hashtags --- index.js | 1 + src/routes/generate.js | 14 ++++ src/routes/polls.js | 106 +++++++++++++++++++++++++++ src/services/ai.js | 31 ++++++++ src/services/scheduledPostsRunner.js | 20 ++++- 5 files changed, 170 insertions(+), 2 deletions(-) create mode 100644 src/routes/polls.js diff --git a/index.js b/index.js index 7b09756..1c8211a 100644 --- a/index.js +++ b/index.js @@ -101,6 +101,7 @@ app.use('/api/calendar', calendarRoutes); app.use('/api/metrics', metricsRoutes); app.use('/api/usage', usageRoutes); app.use('/api/billing', require('./src/routes/billing')); +app.use('/api/channels', require('./src/routes/polls')); app.get('/health', (req, res) => { res.json({ ok: true, service: 'zeropost-engine', time: new Date() }); diff --git a/src/routes/generate.js b/src/routes/generate.js index 22ae705..b0befb9 100644 --- a/src/routes/generate.js +++ b/src/routes/generate.js @@ -117,6 +117,20 @@ router.get('/image-styles', async (_, res) => { }); // POST /api/generate/topics-ideas — синхронные идеи тем для канала +router.post('/hashtags', async (req, res) => { + try { + const { channelId, postText, count = 8 } = req.body; + const userId = req.headers['x-user-id'] ? parseInt(req.headers['x-user-id']) : null; + if (!postText?.trim()) return res.status(400).json({ error: 'postText обязателен' }); + const channel = channelId ? await channelsSvc.getChannel(channelId, userId) : null; + const ai = require('../services/ai'); + const tags = await ai.generateHashtags(channel, { postText, count }); + res.json({ hashtags: tags }); + } catch (err) { + res.status(500).json({ error: err.message }); + } +}); + router.post('/topics-ideas', async (req, res) => { try { const { channelId, count = 7 } = req.body; diff --git a/src/routes/polls.js b/src/routes/polls.js new file mode 100644 index 0000000..efc39da --- /dev/null +++ b/src/routes/polls.js @@ -0,0 +1,106 @@ +/** + * polls.js — публикация опросов в Telegram. + * POST /api/channels/:id/poll + * + * Body: + * question string (до 300 символов) + * options string[] (2-10 вариантов, каждый до 100 символов) + * is_anonymous boolean (default: true) + * allows_multiple_answers boolean (default: false) + * type 'regular' | 'quiz' (default: 'regular') + * correct_option_id int (только для quiz) + * explanation string (только для quiz, до 200 символов) + * schedule_at ISO datetime (null = сейчас) + */ +const express = require('express'); +const router = express.Router(); +const axios = require('axios'); +const { query } = require('../config/db'); +const channelsSvc = require('../services/channels'); +const settings = require('../services/settings'); + +function uid(req) { return req.headers['x-user-id'] ? parseInt(req.headers['x-user-id']) : null; } + +// POST /api/channels/:id/poll +router.post('/:id/poll', async (req, res) => { + const userId = uid(req); + if (!userId) return res.status(401).json({ error: 'x-user-id required' }); + + const channel = await channelsSvc.getFullChannel(req.params.id); + if (!channel) return res.status(404).json({ error: 'Channel not found' }); + if (channel.user_id && channel.user_id !== userId) return res.status(403).json({ error: 'Forbidden' }); + if (channel.platform !== 'telegram') return res.status(400).json({ error: 'Опросы поддерживаются только в Telegram' }); + if (!channel.bot_token || !channel.tg_channel_id) return res.status(400).json({ error: 'Бот и канал не настроены' }); + + const { + question, + options = [], + is_anonymous = true, + allows_multiple_answers = false, + type = 'regular', + correct_option_id, + explanation, + schedule_at = null, + } = req.body; + + // Валидация + if (!question?.trim()) return res.status(400).json({ error: 'question обязателен' }); + if (question.length > 300) return res.status(400).json({ error: 'question максимум 300 символов' }); + if (options.length < 2) return res.status(400).json({ error: 'Минимум 2 варианта ответа' }); + if (options.length > 10) return res.status(400).json({ error: 'Максимум 10 вариантов' }); + if (options.some(o => !o?.trim())) return res.status(400).json({ error: 'Пустые варианты не допускаются' }); + if (options.some(o => o.length > 100)) return res.status(400).json({ error: 'Вариант максимум 100 символов' }); + if (type === 'quiz' && correct_option_id == null) + return res.status(400).json({ error: 'correct_option_id обязателен для quiz' }); + + try { + if (schedule_at) { + // Сохраняем в scheduled_posts для отложенной публикации + const { rows: [job] } = await query(` + INSERT INTO scheduled_posts + (channel_id, text, post_type, scheduled_at, status, meta) + VALUES ($1, $2, 'poll', $3, 'pending', $4) + RETURNING id + `, [ + channel.id, + question, + new Date(schedule_at), + JSON.stringify({ question, options, is_anonymous, allows_multiple_answers, type, correct_option_id, explanation }), + ]); + return res.json({ scheduled: true, job_id: job.id, scheduled_at }); + } + + // Отправляем сразу + const result = await sendPoll({ channel, question, options, is_anonymous, allows_multiple_answers, type, correct_option_id, explanation }); + res.json({ ok: true, message_id: result }); + } catch (err) { + console.error('[polls] error:', err.message); + res.status(500).json({ error: err.message }); + } +}); + +async function sendPoll({ channel, question, options, is_anonymous, allows_multiple_answers, type, correct_option_id, explanation }) { + const base = await settings.get('TELEGRAM_API_BASE', 'https://api.telegram.org'); + const url = `${base}/bot${channel.bot_token}/sendPoll`; + + const body = { + chat_id: channel.tg_channel_id, + question: question.trim(), + options: options.map(o => o.trim()), + is_anonymous, + type, + }; + + if (type === 'regular') body.allows_multiple_answers = allows_multiple_answers; + if (type === 'quiz') { + body.correct_option_id = correct_option_id; + if (explanation?.trim()) body.explanation = explanation.trim().slice(0, 200); + } + + const res = await axios.post(url, body, { timeout: 15_000 }); + if (!res.data?.ok) throw new Error(`TG sendPoll: ${res.data?.description || 'unknown error'}`); + return res.data.result?.message_id; +} + +module.exports = router; +module.exports.sendPoll = sendPoll; diff --git a/src/services/ai.js b/src/services/ai.js index 06921fc..843caf6 100644 --- a/src/services/ai.js +++ b/src/services/ai.js @@ -290,6 +290,36 @@ async function generateArticle(channel, opts = {}) { }; } +/** + * Генерация хештегов для поста. + * Возвращает массив строк без # (добавляем в UI). + */ +async function generateHashtags(channel, { postText, count = 8 }) { + const niche = channel?.niche || ''; + const platform = channel?.platform || 'telegram'; + const system = `Ты эксперт по SMM. Генерируй хештеги для постов. +Платформа: ${platform}. Ниша: ${niche || 'общая'}. +ПРАВИЛА: +- Только релевантные хештеги на русском или английском (по контексту) +- Без символа # — просто слова +- Без пробелов внутри тега (используй_подчёркивание) +- Популярные + нишевые, не слишком общие (не #жизнь, #фото) +- Ответь ТОЛЬКО JSON-массивом строк, без пояснений`; + + const userMsg = `Пост:\n${postText.slice(0, 1000)}\n\nДай ${count} хештегов.`; + const result = await chat(config.ai.models.topics || 'claude-haiku-4-5-20251001', system, userMsg, 0.5, 300); + + try { + const clean = result.replace(/```json|```/g, '').trim(); + const tags = JSON.parse(clean); + if (!Array.isArray(tags)) throw new Error('not array'); + return tags.slice(0, count).map(t => String(t).replace(/^#/, '').replace(/\s+/g, '_').toLowerCase()); + } catch { + // Fallback — парсим вручную + return result.match(/\b[a-zа-яё][a-zа-яё0-9_]{2,29}\b/gi)?.slice(0, count) || []; + } +} + module.exports = { chat, image, @@ -297,4 +327,5 @@ module.exports = { transformPost, generateTopics, generateArticle, + generateHashtags, }; diff --git a/src/services/scheduledPostsRunner.js b/src/services/scheduledPostsRunner.js index 86a3c8d..78b268d 100644 --- a/src/services/scheduledPostsRunner.js +++ b/src/services/scheduledPostsRunner.js @@ -325,10 +325,26 @@ async function publishOne(scheduledPost) { // imgSource === 'none' → photoUrl остаётся null } - if (!text) throw new Error('Empty text and no article'); + if (!text && scheduledPost.post_type !== 'poll') throw new Error('Empty text and no article'); let messageId; - if (channel.platform === 'telegram' || !channel.platform) { + + // Опрос — отдельная ветка + if (scheduledPost.post_type === 'poll') { + if (channel.platform !== 'telegram') throw new Error('Опросы только в Telegram'); + const { sendPoll } = require('../routes/polls'); + const meta = scheduledPost.meta || {}; + messageId = await sendPoll({ + channel, + question: meta.question || scheduledPost.text, + options: meta.options || [], + is_anonymous: meta.is_anonymous ?? true, + allows_multiple_answers: meta.allows_multiple_answers ?? false, + type: meta.type || 'regular', + correct_option_id: meta.correct_option_id, + explanation: meta.explanation, + }); + } else if (channel.platform === 'telegram' || !channel.platform) { messageId = await publishToTelegram({ channel, text, photoUrl, article }); } else if (channel.platform === 'vk') { messageId = await publishToVK({ channel, text, photoUrl, article });