feat: target channel context history, custom website extraction needs, and categorized main menu

This commit is contained in:
mamad
2026-08-28 22:14:49 +03:30
parent 8ccecfe699
commit 9551ccce71
8 changed files with 350 additions and 73 deletions
+152 -49
View File
@@ -44,12 +44,10 @@ def clamp_for_telegram(text: str, has_media: bool) -> str:
def get_persian_main_menu(is_paused: bool = False):
pause_btn = "▶️ راه‌اندازی و ادامه سیستم" if is_paused else "🛑 توقف اضطراری سیستم"
return [
[Button.text("📊 آمار و وضعیت ناوگان", resize=True), Button.text("🔑 درخواست کد لاگین", resize=True)],
[Button.text("📡 کانال‌های مبدا", resize=True), Button.text("🎯 کانال‌های مقصد", resize=True)],
[Button.text("🌐 وبسایت‌های مبدا", resize=True), Button.text("📂 دسته‌بندی کانال‌ها", resize=True)],
[Button.text("🧠 تنظیمات و لاگ‌های AI", resize=True), Button.text("⚠️ خطاهای سیستم", resize=True)],
[Button.text(" افزودن کانال مبدا", resize=True), Button.text(" افزودن کانال مقصد", resize=True)],
[Button.text("📨 ارسال پست‌های بررسی‌نشده", resize=True), Button.text(pause_btn, resize=True)],
[Button.text("🏠 منوی اصلی", resize=True), Button.text("📊 آمار و وضعیت ناوگان", resize=True), Button.text("🔑 کد لاگین", resize=True)],
[Button.text("📡 کانال‌های مبدا", resize=True), Button.text("🎯 کانال‌های مقصد", resize=True), Button.text("🌐 وبسایت‌های مبدا", resize=True)],
[Button.text("📂 دسته‌بندی‌ها", resize=True), Button.text("🧠 تنظیمات و لاگ‌های AI", resize=True), Button.text("⚠️ خطاهای سیستم", resize=True)],
[Button.text("➕ افزودن مبدا / مقصد", resize=True), Button.text("📨 پست‌های بررسی‌نشده", resize=True), Button.text(pause_btn, resize=True)],
[Button.text("❓ راهنمای سیستم", resize=True)]
]
@@ -270,6 +268,8 @@ class AdminBotService:
custom_p = getattr(target, "custom_prompt", "") or ""
order_mode = getattr(target, "dispatch_order", "order") or "order"
order_label = "🟢 به ترتیب ورود (FIFO)" if order_mode == "order" else "🎲 تصادفی (Random)"
ctx_count = getattr(target, "context_message_count", 0) or 0
ctx_label = f"🟢 {ctx_count} پیام اخیر کانال مقصد" if ctx_count > 0 else "⚪️ غیرفعال"
card_text = (
f"🎯 <b>تنظیمات کانال مقصد:</b> <b>{target.title}</b>\n\n"
@@ -278,6 +278,7 @@ class AdminBotService:
f"• 📁 <b>دسته‌بندی:</b> <b>{cat_name}</b>\n"
f"• 🌐 <b>زبان کانال:</b> <b>{lang_label}</b>\n"
f"• 🔀 <b>ترتیب ارسال از صف:</b> <b>{order_label}</b>\n"
f"• 📜 <b>پیام‌های زمینه (Context):</b> <b>{ctx_label}</b>\n"
f"• ⏱ <b>فاصله ارسال پست‌ها:</b> هر <b>{target.post_interval_min} دقیقه</b>\n"
f"• 🌙 <b>وضعیت ساعت خواب:</b> <b>{sleep_st}</b>\n"
f"• 📥 <b>پست‌های منتظر در صف:</b> <b>{qsize} پست</b>\n"
@@ -296,19 +297,20 @@ class AdminBotService:
Button.inline("🎭 تغییر لحن و استایل", data=f"st_pers:{target.id}"),
Button.inline("📝 پرامپت و فرامین اختصاصی", data=f"st_cprompt:{target.id}")
],
[
Button.inline(f"📜 پیام‌های زمینه ({ctx_count})", data=f"trg_ctx_menu:{target.id}"),
Button.inline(f"🔀 شیوه ارسال ({'ترتیبی' if order_mode == 'order' else 'تصادفی'})", data=f"trg_order:{target.id}")
],
[
Button.inline("📁 تعیین دسته‌بندی", data=f"trg_cat:{target.id}"),
Button.inline("🏷 تغییر فوتر و تگ‌ها", data=f"st_foot:{target.id}")
],
[
Button.inline("🌐 تنظیم زبان", data=f"st_lang:{target.id}"),
Button.inline(f"🔀 شیوه ارسال ({'ترتیبی' if order_mode == 'order' else 'تصادفی'})", data=f"trg_order:{target.id}")
],
[
Button.inline("⏱ تغییر فاصله ارسال", data=f"st_intv:{target.id}"),
Button.inline("🌙 تنظیم ساعت خواب", data=f"st_slp:{target.id}")
Button.inline("⏱ تغییر فاصله ارسال", data=f"st_intv:{target.id}")
],
[
Button.inline("🌙 تنظیم ساعت خواب", data=f"st_slp:{target.id}"),
Button.inline("🤖 ارسال خودکار از مبدا", data=f"auto_src:{target.id}")
]
]
@@ -321,6 +323,39 @@ class AdminBotService:
])
return card_text, buttons
async def _render_target_context_menu(self, target_id: int):
target = await self.repo.get_target_by_id(target_id)
if not target:
return "❌ کانال مقصد یافت نشد.", []
current_cnt = getattr(target, "context_message_count", 0) or 0
status_text = f"<b>{current_cnt} پیام اخیر</b>" if current_cnt > 0 else "<b>غیرفعال (۰ پیام)</b>"
text = (
f"📜 <b>تنظیم تعداد پیام‌های زمینه (Context History) برای کانال مقصد</b>\n"
f"🎯 کانال مقصد: <b>{target.title or target.channel_id}</b>\n\n"
f"با فعال‌سازی این قابلیت، هنگام بازنویسی هر پست برای این کانال، تعداد مشخصی از <b>آخرین پست‌های منتشرشده در همین کانال مقصد</b> به هوش مصنوعی داده می‌شود تا خط داستانی، لحن نگارش و اخبار مرتبط اخیر رعایت شود.\n\n"
f"• وضعیت کنونی: {status_text}\n\n"
f"<i>تعداد پیام مورد نظر را انتخاب کنید:</i>"
)
buttons = [
[
Button.inline("0️⃣ خاموش (۰)", data=f"trg_ctx_set:{target.id}:0"),
Button.inline("1️⃣ ۱ پیام", data=f"trg_ctx_set:{target.id}:1"),
Button.inline("2️⃣ ۲ پیام", data=f"trg_ctx_set:{target.id}:2"),
],
[
Button.inline("3️⃣ ۳ پیام", data=f"trg_ctx_set:{target.id}:3"),
Button.inline("5️⃣ ۵ پیام", data=f"trg_ctx_set:{target.id}:5"),
Button.inline("🔟 ۱۰ پیام", data=f"trg_ctx_set:{target.id}:10"),
],
[
Button.inline("🔙 بازگشت به کانال مقصد", data=f"trg_view:{target.id}")
]
]
return text, buttons
async def _render_target_language_menu(self, target_id: int) -> Tuple[str, List[List[Button]]]:
target = await self.repo.get_target_by_id(target_id)
if not target:
@@ -965,11 +1000,13 @@ class AdminBotService:
cat_name = cat.name
api_cfg = site.api_config or {}
parser_type = api_cfg.get("parser_type", "نامشخص")
endpoint = api_cfg.get("endpoint_url", site.url)
has_api = bool(api_cfg.get("endpoint_url"))
parser_type = api_cfg.get("parser_type", "در انتظار تحلیل AI") if has_api else "⚠️ در انتظار تحلیل اولیه"
endpoint = api_cfg.get("endpoint_url", "تنظیم نشده (نیازمند تحلیل)")
err_block = f"⚠️ <b>خطای اخیر:</b> <code>{site.last_error}</code>\n\n" if site.last_error else ""
last_fe = site.last_fetched_at.strftime("%Y-%m-%d %H:%M") if site.last_fetched_at else "هنوز دریافت نشده"
last_re = site.last_reanalyzed_at.strftime("%Y-%m-%d %H:%M") if site.last_reanalyzed_at else "انجام نشده"
needs = getattr(site, "custom_instructions", "") or ""
text = (
f"🌐 <b>وبسایت مبدا:</b> <b>{site.name}</b>\n\n"
@@ -977,6 +1014,8 @@ class AdminBotService:
f"• 🔌 <b>اندپوینت دریافت:</b> <code>{endpoint}</code>\n"
f"• 🏷 <b>نوع ساختار:</b> <code>{parser_type}</code>\n"
f"• 📁 <b>دسته‌بندی:</b> <b>{cat_name}</b>\n"
f"• 📝 <b>نیازمندی‌ها و فیلترهای استخراج:</b>\n"
f"<i>{needs or 'ثبت نشده (استخراج تمام اخبار و پست‌ها)'}</i>\n\n"
f"• ⏱ <b>فاصله بررسی:</b> هر <b>{site.check_interval_min} دقیقه</b>\n"
f"• 🔄 <b>دوره تحلیل مجدد AI:</b> هر <b>{site.auto_reanalyze_hours} ساعت</b>\n"
f"• 📥 <b>آخرین دریافت:</b> <code>{last_fe}</code>\n"
@@ -985,19 +1024,20 @@ class AdminBotService:
f"<i>👇 عملیات مورد نظر را انتخاب کنید:</i>"
)
buttons = [
[
Button.inline("🤖 شروع / تکرار تحلیل با AI", data=f"web_reanalyze:{site.id}"),
Button.inline("📝 نیازمندی‌های استخراج", data=f"web_needs:{site.id}")
],
[
Button.inline("🔄 دریافت دستی (Fetch Now)", data=f"web_fetch:{site.id}"),
Button.inline("🤖 تحلیل مجدد هوشمند AI", data=f"web_reanalyze:{site.id}")
Button.inline(" تغییر فاصله بررسی", data=f"web_intv:{site.id}")
],
[
Button.inline("⏱ تغییر فاصله بررسی", data=f"web_intv:{site.id}"),
Button.inline("🔄 دوره تحلیل مجدد AI", data=f"web_reintv:{site.id}")
],
[
Button.inline("📁 تعیین دسته‌بندی", data=f"web_cat:{site.id}"),
Button.inline("🗑 حذف این وبسایت", data=f"del_web:{site.id}")
Button.inline("🔄 دوره تحلیل مجدد AI", data=f"web_reintv:{site.id}"),
Button.inline("📁 تعیین دسته‌بندی", data=f"web_cat:{site.id}")
],
[
Button.inline("🗑 حذف این وبسایت", data=f"del_web:{site.id}"),
Button.inline("🔙 بازگشت به لیست وبسایت‌ها", data="list_web")
]
]
@@ -1163,19 +1203,18 @@ class AdminBotService:
if not targets:
return 0
source = await self.repo.get_source_by_channel_id(post.source_channel_id)
context_posts = []
if source and getattr(source, "context_message_count", 0) > 0:
context_posts = await self.repo.get_recent_source_posts(
source_channel_id=post.source_channel_id,
limit=source.context_message_count,
exclude_post_id=post.id
)
routed = 0
ai_rejected_reasons = []
for target in targets:
try:
context_posts = []
if target and getattr(target, "context_message_count", 0) > 0:
context_posts = await self.repo.get_recent_target_posts(
target_id=target.id,
limit=target.context_message_count,
exclude_post_id=post.id
)
text = post.raw_text or ""
if self.ai_processor:
rewrite_res = await self.ai_processor.rewrite_for_target(
@@ -1345,6 +1384,19 @@ class AdminBotService:
text, buttons = await self._render_categories_menu()
await event.reply(text, parse_mode="html", buttons=buttons or None)
# --- Unified Add Hub ---
@self.client.on(events.NewMessage(pattern=r"(?i)^(/add|➕ افزودن مبدا / مقصد)$"))
async def cmd_add_hub(event: events.NewMessage.Event):
if not self.is_admin(event.sender_id):
return
text = "➕ <b>افزودن منبع یا کانال جدید:</b>\n\nلطفاً نوع مورد نظر را انتخاب کنید:"
buttons = [
[Button.inline("📡 افزودن کانال تلگرام مبدا", data="hub_add_src")],
[Button.inline("🎯 افزودن کانال تلگرام مقصد", data="hub_add_trg")],
[Button.inline("🌐 افزودن وبسایت مبدا (Web)", data="add_web")],
]
await event.reply(text, parse_mode="html", buttons=buttons)
@self.client.on(events.NewMessage(pattern=r"(?i)^(➕ افزودن کانال مقصد)$"))
async def cmd_add_target_prompt(event: events.NewMessage.Event):
if not self.is_admin(event.sender_id):
@@ -1736,7 +1788,6 @@ class AdminBotService:
await event.reply("❌ فرمت نامعتبر است. لطفاً نام و آدرس را با فاصله ارسال کنید (مثال: <code>دیجیاتو https://digiato.com</code>).", parse_mode="html", buttons=menu)
return
# If last part is URL:
if parts[-1].startswith(("http://", "https://", "www.")) or "." in parts[-1]:
url = parts[-1]
name = " ".join(parts[:-1])
@@ -1747,25 +1798,29 @@ class AdminBotService:
if not url.startswith("http://") and not url.startswith("https://"):
url = "https://" + url
loading_msg = await event.reply(
f"🤖 <b>در حال تحلیل وبسایت «{name}» ({url}) توسط هوش مصنوعی...</b>\n<i>(کشف خودکار REST APIها، فیدهای RSS و ساختار داده)</i>",
parse_mode="html"
)
api_cfg = {}
if self.website_analyzer:
ok, cfg, summary = await self.website_analyzer.analyze_website(url)
if ok and cfg:
api_cfg = cfg
site_id = await self.repo.add_source_website(name=name, url=url, api_config=api_cfg)
site_id = await self.repo.add_source_website(name=name, url=url, api_config={})
card, buttons = await self._render_website_config(site_id)
await loading_msg.edit(
f"✅ <b>وبسایت «{name}» با موفقیت افزوده و پیکربندی شد!</b>\n\n{card}",
await event.reply(
f"✅ <b>وبسایت «{name}» افزوده شد!</b>\n\n"
f"اکنون می‌توانید با دکمه <b>📝 نیازمندی‌های استخراج</b> موضوعات مدنظرتان را تعیین کنید یا با دکمه <b>🤖 شروع / تکرار تحلیل با AI</b> استخراج خودکار را آغاز کنید.\n\n"
f"{card}",
parse_mode="html",
buttons=buttons
)
# 8.2. Waiting for Website Custom Needs / Extraction Instructions
elif action == "wait_website_needs":
site_id = state.get("site_id")
self.user_states.pop(event.sender_id, None)
instr = "" if text.strip() in ("/clear", "clear", "حذف", "پاک") else text.strip()
await self.repo.update_source_website_custom_instructions(site_id, instr)
card, buttons = await self._render_website_config(site_id)
if instr:
await event.reply("✅ <b>نیازمندی‌ها و فیلترهای استخراج وبسایت با موفقیت ذخیره شد!</b>", parse_mode="html")
else:
await event.reply("✅ <b>فیلتر اختصاصی حذف شد (استخراج عمومی فعال شد).</b>", parse_mode="html")
await event.reply(card, parse_mode="html", buttons=buttons)
# 8.2. Waiting for Website Fetch Interval
elif action == "wait_website_intv":
site_id = state.get("site_id")
@@ -2579,6 +2634,55 @@ class AdminBotService:
await event.edit(card, parse_mode="html", buttons=buttons)
await event.answer("🎲 شیوه ارسال روی تصادفی تنظیم شد." if new_order == "random" else "🟢 شیوه ارسال روی به ترتیب تنظیم شد.")
elif data.startswith("trg_ctx_menu:"):
target_id = int(data.split(":")[1])
text, buttons = await self._render_target_context_menu(target_id)
await event.edit(text, parse_mode="html", buttons=buttons)
await event.answer()
elif data.startswith("trg_ctx_set:"):
_, target_id_str, cnt_str = data.split(":")
target_id = int(target_id_str)
cnt = int(cnt_str)
await self.repo.update_target_context_count(target_id, cnt)
card, buttons = await self._render_target_config(target_id)
await event.edit(card, parse_mode="html", buttons=buttons or None)
await event.answer(f"✅ پیام‌های زمینه کانال مقصد روی {cnt} تنظیم شد.")
elif data.startswith("web_needs:"):
site_id = int(data.split(":")[1])
site = await self.repo.get_source_website_by_id(site_id)
if not site:
await event.answer("وبسایت یافت نشد.", alert=True)
return
self.user_states[event.sender_id] = {"action": "wait_website_needs", "site_id": site_id}
await event.reply(
f"📝 <b>تعیین نیازمندی‌ها و فیلترهای استخراج از «{site.name}»:</b>\n\n"
f"چه موضوعات، بخش‌ها یا کلیدواژه‌هایی مد نظر شماست؟ این متن به عنوان دستورالعمل در تحلیل AI قرار می‌گیرد:\n"
f"<i>(مثال: <code>فقط مقالات مربوط به هوش مصنوعی، فناوری و سخت‌افزار</code> یا <code>/clear</code> برای حذف فیلتر)</i>",
parse_mode="html",
buttons=get_cancel_button()
)
await event.answer()
elif data == "hub_add_src":
self.user_states[event.sender_id] = {"action": "wait_source_fwd"}
guide = (
"📡 <b>افزودن کانال مبدا جدید:</b>\n\n"
"یک پیام از کانال مورد نظر را فوروارد کنید یا آیدی/یوزرنیم آن را بفرستید."
)
await event.reply(guide, parse_mode="html", buttons=get_cancel_button())
await event.answer()
elif data == "hub_add_trg":
self.user_states[event.sender_id] = {"action": "wait_target_fwd"}
guide = (
"🎯 <b>افزودن کانال مقصد جدید:</b>\n\n"
"یک پیام از کانال مقصد را فوروارد کنید یا آیدی/یوزرنیم آن را بفرستید."
)
await event.reply(guide, parse_mode="html", buttons=get_cancel_button())
await event.answer()
elif data.startswith("auto_src:"):
target_id = int(data.split(":")[1])
text, buttons = await self._render_auto_sources(target_id)
@@ -2758,12 +2862,11 @@ class AdminBotService:
except Exception:
pass
source = await self.repo.get_source_by_channel_id(post.source_channel_id)
context_posts = []
if source and getattr(source, "context_message_count", 0) > 0:
context_posts = await self.repo.get_recent_source_posts(
source_channel_id=post.source_channel_id,
limit=source.context_message_count,
if target and getattr(target, "context_message_count", 0) > 0:
context_posts = await self.repo.get_recent_target_posts(
target_id=target.id,
limit=target.context_message_count,
exclude_post_id=post.id
)
+5 -2
View File
@@ -38,7 +38,7 @@ class WebsiteAnalyzer:
def __init__(self, llm: LLMClient):
self.llm = llm
async def analyze_website(self, url: str) -> Tuple[bool, Dict[str, Any], str]:
async def analyze_website(self, url: str, custom_instructions: str = "") -> Tuple[bool, Dict[str, Any], str]:
"""Discover endpoints and prompt AI to build the extractor schema."""
clean_url = url.strip()
if not clean_url.startswith("http://") and not clean_url.startswith("https://"):
@@ -109,11 +109,14 @@ class WebsiteAnalyzer:
except Exception as e:
return False, {}, f"خطا در برقراری ارتباط با وبسایت: {e}"
custom_block = f"\nUser Extraction Needs / Filtering Instructions:\n{custom_instructions.strip()}\n" if custom_instructions and custom_instructions.strip() else ""
prompt = (
f"Website Target URL: {clean_url}\n"
f"{custom_block}"
f"Discovery Notes:\n" + "\n".join(discovered_info) + "\n\n"
f"Data / Feed Sample:\n{sample_data}\n\n"
f"Determine the best endpoint_url, parser_type, and field mappings to regularly extract the latest news/articles from this site."
f"Determine the best endpoint_url, parser_type, and field mappings to regularly extract the latest news/articles from this site matching the user requirements."
)
try:
+4 -2
View File
@@ -110,7 +110,8 @@ class WebsiteCollectorService:
if not site:
return False, "وبسایت یافت نشد."
ok, api_cfg, summary = await self.analyzer.analyze_website(site.url)
custom_inst = getattr(site, "custom_instructions", "") or ""
ok, api_cfg, summary = await self.analyzer.analyze_website(site.url, custom_instructions=custom_inst)
if ok and api_cfg:
await self.repo.update_source_website_api_config(site_id, api_cfg)
return True, f"✅ وبسایت «{site.name}» با موفقیت تحلیل شد:\n{summary}"
@@ -133,7 +134,8 @@ class WebsiteCollectorService:
endpoint_url = api_cfg.get("endpoint_url")
if not endpoint_url:
# Trigger initial analysis
ok, new_cfg, _ = await self.analyzer.analyze_website(site.url)
custom_inst = getattr(site, "custom_instructions", "") or ""
ok, new_cfg, _ = await self.analyzer.analyze_website(site.url, custom_instructions=custom_inst)
if ok and new_cfg:
await self.repo.update_source_website_api_config(site_id, new_cfg)
api_cfg = new_cfg