From 88230c92b54e517bb4fb85e0bf32ee58282cad6a Mon Sep 17 00:00:00 2001 From: admin Date: Fri, 30 Oct 2026 14:29:36 +0200 Subject: [PATCH] feat(posts): copy button on generated posts with copy-count analytics --- VERSION | 2 +- analytics.py | 7 ++++++- bot.py | 21 ++++++++++++++++++--- keyboards.py | 14 ++++++++++++++ tests/test_writer_features.py | 31 ++++++++++++++++++++++++++++++- 5 files changed, 69 insertions(+), 6 deletions(-) diff --git a/VERSION b/VERSION index 94a02a2..68cc106 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.0+84 +0.1.0+85 diff --git a/analytics.py b/analytics.py index cf18871..369d8aa 100644 --- a/analytics.py +++ b/analytics.py @@ -121,7 +121,12 @@ def all_metrics(period: str = "all", db_path: str | None = None) -> dict[str, ob f"SELECT mode, message_type, COUNT(*) AS total FROM events WHERE event_type='user_message' AND message_type IS NOT NULL{(' AND created_at >= ?' if period != 'all' else '')} GROUP BY mode, message_type", args, ).fetchall() + copy_where = " AND created_at >= ?" if where else "" + copy_row = connection.execute( + f"SELECT COUNT(*) AS total FROM events WHERE event_type = 'post_copy'{copy_where}", args + ).fetchone() result = {key: int(row[key] or 0) for key in ("users", "active_users", "post_generations", "idea_generations", "post_revisions", "generation_messages", "training_messages")} + result["post_copies"] = int(copy_row["total"] or 0) result["message_types"] = {(str(r["mode"]), str(r["message_type"])): int(r["total"]) for r in types} result["period"] = period return result @@ -156,7 +161,7 @@ def render_report(period: str = "all", db_path: str | None = None) -> str: return ( "

πŸ“Š Бтатистика Π±ΠΎΡ‚Π°

" + table("ΠŸΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»ΠΈ", [("АктивныС", "active_users")]) - + table("ГСнСрация", [("ΠŸΠΎΡΡ‚Ρ‹", "post_generations"), ("ИдСи", "idea_generations"), ("ΠŸΡ€Π°Π²ΠΊΠΈ", "post_revisions"), ("БообщСния", "generation_messages")]) + + table("ГСнСрация", [("ΠŸΠΎΡΡ‚Ρ‹", "post_generations"), ("ИдСи", "idea_generations"), ("ΠŸΡ€Π°Π²ΠΊΠΈ", "post_revisions"), ("БообщСния", "generation_messages"), ("ΠšΠΎΠΏΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠΉ поста", "post_copies")]) + "

Π’ΠΈΠΏΡ‹ сообщСний Π² Π³Π΅Π½Π΅Ρ€Π°Ρ†ΠΈΠΈ

" + _html_table(["Π’ΠΈΠΏ", *titles], generation_rows) + table("ΠžΠ±ΡƒΡ‡Π΅Π½ΠΈΠ΅", [("БообщСния", "training_messages")]) + "

Π’ΠΈΠΏΡ‹ сообщСний Π² ΠΎΠ±ΡƒΡ‡Π΅Π½ΠΈΠΈ

" + _html_table(["Π’ΠΈΠΏ", *titles], training_type_rows) diff --git a/bot.py b/bot.py index ffab1a2..6c642e5 100644 --- a/bot.py +++ b/bot.py @@ -41,7 +41,7 @@ from raw_updates import RawUpdateMiddleware, init_raw_updates_db from apinex_client import APINEX_STT_URL, POST_HISTORY_CHAR_LIMIT, POST_HISTORY_LIMIT, classify_intent, classify_prompt_injection, create_tone_profile, create_training_summary, current_operation_id, diagnostic_operation, extract_posts_from_images, extract_transcript, generate_ideas, generate_posts, generate_posts_from_images, transcribe_audio from help_message import WELCOME_RICH_HTML, help_plain_view, help_view, rich_to_plain -from keyboards import MAIN_MENU_VALUE, SUBSCRIPTION_ACTION_VALUE, SUPPORT_VALUE, TRAINING_INFO_VALUE, TRAINING_RESET_VALUE, help_inline_keyboard, main_menu_keyboard, mode_keyboard, resolve_button_text, subscription_plans_keyboard +from keyboards import MAIN_MENU_VALUE, SUBSCRIPTION_ACTION_VALUE, SUPPORT_VALUE, TRAINING_INFO_VALUE, TRAINING_RESET_VALUE, help_inline_keyboard, main_menu_keyboard, mode_keyboard, post_copy_keyboard, resolve_button_text, subscription_plans_keyboard from payments import send_subscription_invoice import support import analytics @@ -758,6 +758,21 @@ async def clear_command(message: Message, state: FSMContext) -> None: ) +@router.callback_query(F.data.startswith("copy_post:")) +async def post_copy_pressed(callback: CallbackQuery) -> None: + """Кнопка Β«Π‘ΠΊΠΎΠΏΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒΒ»: тСкст ΠΊΠΎΠΏΠΈΡ€ΡƒΠ΅Ρ‚ сам Telegram (copy_text), здСсь пишСм Ρ‚ΠΎΠ»ΡŒΠΊΠΎ статистику.""" + if callback.from_user is not None: + await asyncio.to_thread(analytics.record_event, callback.from_user.id, "generation", "post_copy") + message = callback.message + if isinstance(message, Message): + try: + await message.edit_reply_markup(reply_markup=None) + except Exception as exc: + if "message is not modified" not in str(exc).casefold(): + logger.debug("Copy button removal failed: %s", str(exc)[:120]) + await callback.answer() + + @router.callback_query(F.data.startswith("training:reset:")) async def confirm_training_reset(callback: CallbackQuery, state: FSMContext) -> None: parts = (callback.data or "").split(":") @@ -886,8 +901,8 @@ async def _send_idea(message: Message, idea: dict[str, str], user_id: int) -> No async def _send_three_posts(message: Message, posts: list[str], user_id: int | None = None, origin: str = "generated") -> None: - for post in posts: - await message.answer(post) + for index, post in enumerate(posts): + await message.answer(post, reply_markup=post_copy_keyboard(post, index)) if user_id is not None: await asyncio.to_thread(save_generated_posts, user_id, posts, origin) event_type = "post_revision" if origin == "revised" else "post_generation" diff --git a/keyboards.py b/keyboards.py index fc6f84a..1e41882 100644 --- a/keyboards.py +++ b/keyboards.py @@ -2,6 +2,7 @@ from __future__ import annotations from aiogram.types import ( + CopyTextButton, InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton, @@ -101,6 +102,19 @@ def subscription_plans_keyboard() -> InlineKeyboardMarkup: ]) +def post_copy_keyboard(post_text: str, post_index: int) -> InlineKeyboardMarkup: + """Кнопка копирования поста: ΠΊΠ»ΠΈΠΊ ΠΊΠΎΠΏΠΈΡ€ΡƒΠ΅Ρ‚ тСкст (copy_text), Π½Π°ΠΆΠ°Ρ‚ΠΈΠ΅ ΠΏΠΈΡˆΠ΅Ρ‚ΡΡ Π² статистику (callback_data).""" + return InlineKeyboardMarkup( + inline_keyboard=[[ + InlineKeyboardButton( + text="πŸ“‹ Π‘ΠΊΠΎΠΏΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ", + copy_text=CopyTextButton(text=post_text), + callback_data=f"copy_post:{post_index}", + ), + ]], + ) + + def help_inline_keyboard() -> InlineKeyboardMarkup: """Бтандартная inline-ΠΊΠ»Π°Π²ΠΈΠ°Ρ‚ΡƒΡ€Π° для Π½Π°Π²ΠΈΠ³Π°Ρ†ΠΈΠΈ ΠΏΠΎ Ρ€Π°Π·Π΄Π΅Π»Π°ΠΌ справки.""" return InlineKeyboardMarkup( diff --git a/tests/test_writer_features.py b/tests/test_writer_features.py index d67f1a1..78c78aa 100644 --- a/tests/test_writer_features.py +++ b/tests/test_writer_features.py @@ -3,7 +3,7 @@ import json import unittest from types import SimpleNamespace from typing import Any, cast -from unittest.mock import AsyncMock, patch +from unittest.mock import AsyncMock, MagicMock, patch import apinex_client import bot @@ -1222,5 +1222,34 @@ class TrainingSummaryTests(unittest.IsolatedAsyncioTestCase): send.assert_not_awaited() +class PostCopyButtonTests(unittest.IsolatedAsyncioTestCase): + async def test_send_three_posts_attaches_copy_button(self): + message = SimpleNamespace(answer=AsyncMock()) + with ( + patch.object(bot, "save_generated_posts"), + patch.object(bot.analytics, "record_event"), + patch.object(bot.asyncio, "to_thread", new=AsyncMock()), + ): + await bot._send_three_posts(cast(Any, message), ["ΠŸΠΎΡΡ‚ А", "ΠŸΠΎΡΡ‚ Π‘"], user_id=None) + first = message.answer.await_args_list[0] + button = first.kwargs["reply_markup"].inline_keyboard[0][0] + self.assertEqual(button.copy_text.text, "ΠŸΠΎΡΡ‚ А") + self.assertEqual(button.callback_data, "copy_post:0") + + async def test_copy_callback_records_event_and_clears_button(self): + callback = SimpleNamespace( + from_user=SimpleNamespace(id=42), + message=MagicMock(spec=bot.Message), + answer=AsyncMock(), + ) + callback.message.edit_reply_markup = AsyncMock() + with patch.object(bot.asyncio, "to_thread", new=AsyncMock()) as to_thread: + await bot.post_copy_pressed(cast(Any, callback)) + to_thread.assert_awaited_once() + self.assertEqual(to_thread.await_args.args[1:], (42, "generation", "post_copy")) + callback.message.edit_reply_markup.assert_awaited_once_with(reply_markup=None) + callback.answer.assert_awaited_once() + + if __name__ == "__main__": unittest.main() \ No newline at end of file