feat: P7 polls + P8 hashtags
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
This commit is contained in:
@@ -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;
|
||||
Reference in New Issue
Block a user