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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
import random
|
| 6 |
+
import logging
|
| 7 |
+
import html
|
| 8 |
+
import asyncio
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Dict, List, Optional, Any, Tuple
|
| 12 |
+
|
| 13 |
+
import pytz
|
| 14 |
+
import requests
|
| 15 |
+
import feedparser
|
| 16 |
+
import google.generativeai as genai
|
| 17 |
+
from bs4 import BeautifulSoup
|
| 18 |
+
from PIL import Image
|
| 19 |
+
from apscheduler.schedulers.background import BackgroundScheduler
|
| 20 |
+
from telegram import Bot
|
| 21 |
+
from telegram.error import TelegramError
|
| 22 |
+
from pyrogram import Client, enums
|
| 23 |
+
from flask import Flask
|
| 24 |
+
|
| 25 |
+
# =========================
|
| 26 |
+
# Castle Info Bot
|
| 27 |
+
# Telegram + RSS + Gemini
|
| 28 |
+
# Auto Gemini model discovery
|
| 29 |
+
# =========================
|
| 30 |
+
|
| 31 |
+
logging.basicConfig(
|
| 32 |
+
level=logging.INFO,
|
| 33 |
+
format="%(asctime)s | %(levelname)s | %(message)s"
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
BOT_TOKEN = os.getenv("BOT_TOKEN", "").strip()
|
| 37 |
+
API_ID = int(os.getenv("API_ID", "0") or "0")
|
| 38 |
+
API_HASH = os.getenv("API_HASH", "").strip()
|
| 39 |
+
TELEGRAM_CHANNEL_ID = os.getenv("TELEGRAM_CHANNEL_ID", "").strip()
|
| 40 |
+
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY", "").strip()
|
| 41 |
+
|
| 42 |
+
TIMEZONE = os.getenv("TIMEZONE", "Asia/Baghdad").strip()
|
| 43 |
+
RUN_ON_START = os.getenv("RUN_ON_START", "false").lower() == "true"
|
| 44 |
+
|
| 45 |
+
# Optional. If you set GEMINI_MODEL in Secrets, bot tries it first.
|
| 46 |
+
# If empty, bot auto-discovers available models.
|
| 47 |
+
PREFERRED_GEMINI_MODEL = os.getenv("GEMINI_MODEL", "").strip()
|
| 48 |
+
|
| 49 |
+
POST_HOURS = [10, 12, 14, 16, 18, 20, 22]
|
| 50 |
+
|
| 51 |
+
SIGNATURE = """#قلعة_المعلومات_العامة
|
| 52 |
+
اشتـــرك الآن :- https://t.me/CastleInfoiq"""
|
| 53 |
+
DATA_DIR = Path(os.getenv("DATA_DIR", "."))
|
| 54 |
+
DATA_FILE = DATA_DIR / "data.json"
|
| 55 |
+
BACKUP_FILE = DATA_DIR / "data.backup.json"
|
| 56 |
+
|
| 57 |
+
USER_AGENT = (
|
| 58 |
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 59 |
+
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 60 |
+
"Chrome/125.0 Safari/537.36"
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
RSS_SOURCES = [
|
| 64 |
+
{
|
| 65 |
+
"name": "NASA",
|
| 66 |
+
"category": "فضاء",
|
| 67 |
+
"url": "https://www.nasa.gov/rss/dyn/breaking_news.rss",
|
| 68 |
+
"hashtags": "#فضاء #ناسا #الكون #معلومات_عامة"
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"name": "NASA Science",
|
| 72 |
+
"category": "فضاء",
|
| 73 |
+
"url": "https://science.nasa.gov/feed/",
|
| 74 |
+
"hashtags": "#فضاء #علوم #الكون #معلومات_عامة"
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"name": "ScienceDaily",
|
| 78 |
+
"category": "علوم",
|
| 79 |
+
"url": "https://www.sciencedaily.com/rss/top.xml",
|
| 80 |
+
"hashtags": "#علوم #اكتشافات #معرفة #معلومات_عامة"
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"name": "ScienceDaily Space",
|
| 84 |
+
"category": "فضاء",
|
| 85 |
+
"url": "https://www.sciencedaily.com/rss/space_time.xml",
|
| 86 |
+
"hashtags": "#فضاء #علوم #الكون #معلومات_عامة"
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"name": "ScienceDaily Matter",
|
| 90 |
+
"category": "علوم",
|
| 91 |
+
"url": "https://www.sciencedaily.com/rss/matter_energy.xml",
|
| 92 |
+
"hashtags": "#علوم #اكتشافات #تكنولوجيا #معلومات_عامة"
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
"name": "World History Encyclopedia",
|
| 96 |
+
"category": "تاريخ",
|
| 97 |
+
"url": "https://www.worldhistory.org/rss/",
|
| 98 |
+
"hashtags": "#تاريخ #حضارات #معرفة #معلومات_عامة"
|
| 99 |
+
}
|
| 100 |
+
]
|
| 101 |
+
|
| 102 |
+
FALLBACK_TOPICS = [
|
| 103 |
+
"قصة بناء الأهرامات وأسرارها العلمية",
|
| 104 |
+
"كيف غيّر نيوتن فهم البشر للكون",
|
| 105 |
+
"أغرب أسرار كوكب المشتري",
|
| 106 |
+
"قصة مكتبة الإسكندرية ولماذا بقيت لغزاً",
|
| 107 |
+
"كيف بدأت الثورة الصناعية وغيرت العالم",
|
| 108 |
+
"العلماء الذين غيروا مجرى التاريخ",
|
| 109 |
+
"أسرار الثقوب السوداء بطريقة مبسطة",
|
| 110 |
+
"حضارة وادي الرافدين وأثرها على العالم",
|
| 111 |
+
"كيف تعمل الذاكرة داخل دماغ الإنسان",
|
| 112 |
+
"اختراعات ظهرت بالصدفة وغيرت حياتنا",
|
| 113 |
+
"لماذا كان اكتشاف الكهرباء نقطة تحول في التاريخ",
|
| 114 |
+
"كيف عرف الإنسان الزمن قبل اختراع الساعة"
|
| 115 |
+
]
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def validate_env() -> None:
|
| 119 |
+
missing = []
|
| 120 |
+
if not BOT_TOKEN:
|
| 121 |
+
missing.append("BOT_TOKEN")
|
| 122 |
+
if not TELEGRAM_CHANNEL_ID:
|
| 123 |
+
missing.append("TELEGRAM_CHANNEL_ID")
|
| 124 |
+
if not GOOGLE_API_KEY:
|
| 125 |
+
missing.append("GOOGLE_API_KEY")
|
| 126 |
+
if missing:
|
| 127 |
+
raise RuntimeError("Missing secrets: " + ", ".join(missing))
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def load_data() -> Dict[str, Any]:
|
| 131 |
+
default = {
|
| 132 |
+
"posted_links": [],
|
| 133 |
+
"posted_titles": [],
|
| 134 |
+
"last_posts": [],
|
| 135 |
+
"last_error": "",
|
| 136 |
+
"active_gemini_model": "",
|
| 137 |
+
"created_at": datetime.utcnow().isoformat()
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
if not DATA_FILE.exists():
|
| 141 |
+
save_data(default)
|
| 142 |
+
return default
|
| 143 |
+
|
| 144 |
+
try:
|
| 145 |
+
data = json.loads(DATA_FILE.read_text(encoding="utf-8"))
|
| 146 |
+
if not isinstance(data, dict):
|
| 147 |
+
raise ValueError("data.json is not a JSON object")
|
| 148 |
+
for k, v in default.items():
|
| 149 |
+
data.setdefault(k, v)
|
| 150 |
+
return data
|
| 151 |
+
except Exception as e:
|
| 152 |
+
logging.error("data.json corrupted, trying backup: %s", e)
|
| 153 |
+
if BACKUP_FILE.exists():
|
| 154 |
+
try:
|
| 155 |
+
data = json.loads(BACKUP_FILE.read_text(encoding="utf-8"))
|
| 156 |
+
if isinstance(data, dict):
|
| 157 |
+
for k, v in default.items():
|
| 158 |
+
data.setdefault(k, v)
|
| 159 |
+
save_data(data)
|
| 160 |
+
return data
|
| 161 |
+
except Exception as e2:
|
| 162 |
+
logging.error("backup restore failed: %s", e2)
|
| 163 |
+
|
| 164 |
+
save_data(default)
|
| 165 |
+
return default
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def save_data(data: Dict[str, Any]) -> None:
|
| 169 |
+
try:
|
| 170 |
+
if DATA_FILE.exists() and DATA_FILE.stat().st_size > 5:
|
| 171 |
+
BACKUP_FILE.write_text(DATA_FILE.read_text(encoding="utf-8"), encoding="utf-8")
|
| 172 |
+
except Exception:
|
| 173 |
+
pass
|
| 174 |
+
|
| 175 |
+
tmp = DATA_FILE.with_suffix(".tmp")
|
| 176 |
+
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 177 |
+
tmp.replace(DATA_FILE)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def normalize_text(text: str) -> str:
|
| 181 |
+
text = BeautifulSoup(text or "", "html.parser").get_text(" ", strip=True)
|
| 182 |
+
text = re.sub(r"\s+", " ", text).strip()
|
| 183 |
+
return text
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def clean_title(title: str) -> str:
|
| 187 |
+
return normalize_text(title)[:180]
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def fetch_url(url: str, timeout: int = 20) -> Optional[str]:
|
| 191 |
+
try:
|
| 192 |
+
r = requests.get(
|
| 193 |
+
url,
|
| 194 |
+
headers={"User-Agent": USER_AGENT, "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"},
|
| 195 |
+
timeout=timeout,
|
| 196 |
+
allow_redirects=True
|
| 197 |
+
)
|
| 198 |
+
if r.status_code == 200 and r.text:
|
| 199 |
+
return r.text
|
| 200 |
+
logging.warning("fetch failed %s status=%s", url, r.status_code)
|
| 201 |
+
except Exception as e:
|
| 202 |
+
logging.warning("fetch exception %s | %s", url, e)
|
| 203 |
+
return None
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def extract_image_from_entry(entry: Any, article_url: str = "") -> Optional[str]:
|
| 207 |
+
candidates = []
|
| 208 |
+
|
| 209 |
+
try:
|
| 210 |
+
for m in getattr(entry, "media_content", []) or []:
|
| 211 |
+
if m.get("url"):
|
| 212 |
+
candidates.append(m.get("url"))
|
| 213 |
+
except Exception:
|
| 214 |
+
pass
|
| 215 |
+
|
| 216 |
+
try:
|
| 217 |
+
for m in getattr(entry, "media_thumbnail", []) or []:
|
| 218 |
+
if m.get("url"):
|
| 219 |
+
candidates.append(m.get("url"))
|
| 220 |
+
except Exception:
|
| 221 |
+
pass
|
| 222 |
+
|
| 223 |
+
for key in ["image", "thumbnail"]:
|
| 224 |
+
try:
|
| 225 |
+
val = entry.get(key)
|
| 226 |
+
if val:
|
| 227 |
+
candidates.append(val)
|
| 228 |
+
except Exception:
|
| 229 |
+
pass
|
| 230 |
+
|
| 231 |
+
try:
|
| 232 |
+
summary = entry.get("summary", "") or entry.get("description", "")
|
| 233 |
+
soup = BeautifulSoup(summary, "html.parser")
|
| 234 |
+
img = soup.find("img")
|
| 235 |
+
if img and img.get("src"):
|
| 236 |
+
candidates.append(img.get("src"))
|
| 237 |
+
except Exception:
|
| 238 |
+
pass
|
| 239 |
+
|
| 240 |
+
if article_url:
|
| 241 |
+
html = fetch_url(article_url, timeout=12)
|
| 242 |
+
if html:
|
| 243 |
+
soup = BeautifulSoup(html, "html.parser")
|
| 244 |
+
for attr, value in [
|
| 245 |
+
("property", "og:image"),
|
| 246 |
+
("name", "twitter:image"),
|
| 247 |
+
("property", "twitter:image")
|
| 248 |
+
]:
|
| 249 |
+
tag = soup.find("meta", attrs={attr: value})
|
| 250 |
+
if tag and tag.get("content"):
|
| 251 |
+
candidates.append(tag.get("content"))
|
| 252 |
+
|
| 253 |
+
for c in candidates:
|
| 254 |
+
if isinstance(c, str) and c.startswith("http"):
|
| 255 |
+
return c
|
| 256 |
+
return None
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def extract_article_text(entry: Any, url: str) -> str:
|
| 260 |
+
parts = []
|
| 261 |
+
|
| 262 |
+
for key in ["title", "summary", "description"]:
|
| 263 |
+
try:
|
| 264 |
+
val = entry.get(key, "")
|
| 265 |
+
if val:
|
| 266 |
+
parts.append(normalize_text(val))
|
| 267 |
+
except Exception:
|
| 268 |
+
pass
|
| 269 |
+
|
| 270 |
+
html = fetch_url(url, timeout=15)
|
| 271 |
+
if html:
|
| 272 |
+
soup = BeautifulSoup(html, "html.parser")
|
| 273 |
+
for bad in soup(["script", "style", "noscript", "header", "footer", "nav", "aside"]):
|
| 274 |
+
bad.decompose()
|
| 275 |
+
|
| 276 |
+
article = soup.find("article") or soup.find("main") or soup.body
|
| 277 |
+
if article:
|
| 278 |
+
paragraphs = [normalize_text(p.get_text(" ", strip=True)) for p in article.find_all("p")]
|
| 279 |
+
paragraphs = [p for p in paragraphs if len(p) > 45]
|
| 280 |
+
if paragraphs:
|
| 281 |
+
parts.append(" ".join(paragraphs[:9]))
|
| 282 |
+
|
| 283 |
+
text = normalize_text(" ".join(parts))
|
| 284 |
+
return text[:6000]
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def get_candidate_article(data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
| 288 |
+
sources = RSS_SOURCES[:]
|
| 289 |
+
random.shuffle(sources)
|
| 290 |
+
|
| 291 |
+
posted_links = set(data.get("posted_links", []))
|
| 292 |
+
posted_titles = set(data.get("posted_titles", []))
|
| 293 |
+
|
| 294 |
+
for source in sources:
|
| 295 |
+
try:
|
| 296 |
+
logging.info("Checking RSS: %s", source["name"])
|
| 297 |
+
feed = feedparser.parse(source["url"])
|
| 298 |
+
entries = list(feed.entries or [])
|
| 299 |
+
except Exception as e:
|
| 300 |
+
logging.warning("RSS parse failed %s | %s", source["name"], e)
|
| 301 |
+
continue
|
| 302 |
+
|
| 303 |
+
random.shuffle(entries)
|
| 304 |
+
|
| 305 |
+
for entry in entries[:14]:
|
| 306 |
+
try:
|
| 307 |
+
link = (entry.get("link", "") or "").strip()
|
| 308 |
+
title = clean_title(entry.get("title", ""))
|
| 309 |
+
|
| 310 |
+
if not link or not title:
|
| 311 |
+
continue
|
| 312 |
+
if link in posted_links or title in posted_titles:
|
| 313 |
+
continue
|
| 314 |
+
|
| 315 |
+
article_text = extract_article_text(entry, link)
|
| 316 |
+
if len(article_text) < 220:
|
| 317 |
+
logging.info("Skipping weak article: %s", title)
|
| 318 |
+
continue
|
| 319 |
+
|
| 320 |
+
image_url = extract_image_from_entry(entry, link)
|
| 321 |
+
|
| 322 |
+
return {
|
| 323 |
+
"mode": "rss",
|
| 324 |
+
"source": source["name"],
|
| 325 |
+
"category": source["category"],
|
| 326 |
+
"hashtags": source["hashtags"],
|
| 327 |
+
"title": title,
|
| 328 |
+
"link": link,
|
| 329 |
+
"text": article_text,
|
| 330 |
+
"image_url": image_url
|
| 331 |
+
}
|
| 332 |
+
except Exception as e:
|
| 333 |
+
logging.warning("Entry skipped due error: %s", e)
|
| 334 |
+
continue
|
| 335 |
+
|
| 336 |
+
return None
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def init_gemini() -> None:
|
| 340 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def discover_gemini_models() -> List[str]:
|
| 344 |
+
"""Return models that support generateContent, ordered by preference."""
|
| 345 |
+
fallback_names = [
|
| 346 |
+
"gemini-2.5-flash",
|
| 347 |
+
"gemini-2.5-flash-lite",
|
| 348 |
+
"gemini-2.0-flash",
|
| 349 |
+
"gemini-2.0-flash-lite",
|
| 350 |
+
"gemini-1.5-flash",
|
| 351 |
+
"gemini-1.5-flash-latest"
|
| 352 |
+
]
|
| 353 |
+
|
| 354 |
+
discovered = []
|
| 355 |
+
try:
|
| 356 |
+
for m in genai.list_models():
|
| 357 |
+
name = getattr(m, "name", "") or ""
|
| 358 |
+
methods = list(getattr(m, "supported_generation_methods", []) or [])
|
| 359 |
+
if "generateContent" in methods:
|
| 360 |
+
# API returns names like "models/gemini-2.0-flash"
|
| 361 |
+
discovered.append(name.replace("models/", ""))
|
| 362 |
+
except Exception as e:
|
| 363 |
+
logging.warning("list_models failed, using fallback model names: %s", e)
|
| 364 |
+
|
| 365 |
+
candidates = []
|
| 366 |
+
if PREFERRED_GEMINI_MODEL:
|
| 367 |
+
candidates.append(PREFERRED_GEMINI_MODEL.replace("models/", ""))
|
| 368 |
+
|
| 369 |
+
for n in fallback_names:
|
| 370 |
+
if n not in candidates:
|
| 371 |
+
candidates.append(n)
|
| 372 |
+
|
| 373 |
+
for n in discovered:
|
| 374 |
+
# Put flash models first, avoid embedding/vision-only/preview if possible.
|
| 375 |
+
low = n.lower()
|
| 376 |
+
if "embedding" in low or "aqa" in low:
|
| 377 |
+
continue
|
| 378 |
+
if n not in candidates:
|
| 379 |
+
candidates.append(n)
|
| 380 |
+
|
| 381 |
+
logging.info("Gemini candidate models: %s", candidates)
|
| 382 |
+
return candidates
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def generate_with_auto_model(prompt: str, data: Dict[str, Any]) -> Tuple[str, str]:
|
| 386 |
+
init_gemini()
|
| 387 |
+
candidates = discover_gemini_models()
|
| 388 |
+
last_error = None
|
| 389 |
+
|
| 390 |
+
for name in candidates:
|
| 391 |
+
try:
|
| 392 |
+
logging.info("Trying Gemini model: %s", name)
|
| 393 |
+
model = genai.GenerativeModel(name)
|
| 394 |
+
response = model.generate_content(prompt)
|
| 395 |
+
text = (getattr(response, "text", "") or "").strip()
|
| 396 |
+
text = re.sub(r"\n{3,}", "\n\n", text).replace("**", "").strip()
|
| 397 |
+
if len(text) < 80:
|
| 398 |
+
raise RuntimeError(f"Gemini response too short from {name}")
|
| 399 |
+
data["active_gemini_model"] = name
|
| 400 |
+
save_data(data)
|
| 401 |
+
logging.info("Gemini model success: %s", name)
|
| 402 |
+
return text, name
|
| 403 |
+
except Exception as e:
|
| 404 |
+
last_error = e
|
| 405 |
+
logging.warning("Gemini model failed: %s | %s", name, e)
|
| 406 |
+
time.sleep(1)
|
| 407 |
+
|
| 408 |
+
raise RuntimeError(f"All Gemini models failed. Last error: {last_error}")
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def build_article_prompt(article: Dict[str, Any]) -> str:
|
| 412 |
+
category = article.get("category", "معلومات عامة")
|
| 413 |
+
title = article.get("title", "")
|
| 414 |
+
text = article.get("text", "")
|
| 415 |
+
suggested_hashtags = article.get("hashtags", "#معلومات_عامة")
|
| 416 |
+
|
| 417 |
+
return f"""
|
| 418 |
+
أنت محرر قناة تيليجرام عربية اسمها قلعة المعلومات العامة.
|
| 419 |
+
|
| 420 |
+
حوّل المادة التالية إلى منشور عربي قصير بأسلوب قصة تشويق يشد القارئ حتى النهاية.
|
| 421 |
+
|
| 422 |
+
القواعد المهمة جداً:
|
| 423 |
+
- اكتب عنواناً جذاباً قصيراً في السطر الأول.
|
| 424 |
+
- بعدها اكتب ملخصاً قصصياً من 4 إلى 8 أسطر فقط.
|
| 425 |
+
- لا تستخدم تعداد نقاط.
|
| 426 |
+
- لا تكتب عبارة: أهم النقاط.
|
| 427 |
+
- لا تذكر اسم المصدر داخل المنشور.
|
| 428 |
+
- لا تترجم حرفياً، أعد الصياغة كأنك كاتب محترف.
|
| 429 |
+
- اجعل كل جملة تكمل التي قبلها وتزيد الفضول.
|
| 430 |
+
- لا تخترع معلومة غير موجودة في المادة.
|
| 431 |
+
- لا تبالغ علمياً ولا تكتب ادعاءات غير مؤكدة.
|
| 432 |
+
- اختم النص بإحساس دهشة أو معلومة قوية.
|
| 433 |
+
- أضف في نهاية المنشور سطر هاشتاكات مناسب، 3 إلى 6 هاشتاكات حسب الموضوع فقط.
|
| 434 |
+
- اجعل الهاشتاكات في آخر سطر مستقل فقط، ولا تضع أي هاشتاك داخل النص.
|
| 435 |
+
- لا تضف #قلعة_المعلومات_العامة؛ هذا يضاف تلقائياً داخل التوقيع.
|
| 436 |
+
- لا تكتب رابط القناة ولا عبارة الاشتراك؛ التوقيع سيضاف تلقائياً.
|
| 437 |
+
- الأسلوب عربي مفهوم قريب للفصحى، مع لمسة سهلة للقارئ العراقي.
|
| 438 |
+
- طول المنشور كله قبل الهاشتاكات لا يتجاوز 900 حرف.
|
| 439 |
+
|
| 440 |
+
التصنيف: {category}
|
| 441 |
+
العنوان الأصلي: {title}
|
| 442 |
+
هاشتاكات مقترحة: {suggested_hashtags}
|
| 443 |
+
|
| 444 |
+
المادة:
|
| 445 |
+
{text}
|
| 446 |
+
"""
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def build_fallback_prompt(topic: str) -> str:
|
| 450 |
+
return f"""
|
| 451 |
+
اكتب منشور تيليجرام عربي لقناة معلومات عامة عن الموضوع التالي:
|
| 452 |
+
{topic}
|
| 453 |
+
|
| 454 |
+
القواعد:
|
| 455 |
+
- عنوان جذاب قصير في السطر الأول.
|
| 456 |
+
- نص قصصي مشوق من 4 إلى 8 أسطر.
|
| 457 |
+
- كل جملة تقود لما بعدها وتزيد فضول القارئ.
|
| 458 |
+
- لا تستخدم تعداد نقاط.
|
| 459 |
+
- لا تكتب "أهم النقاط".
|
| 460 |
+
- لا تذكر مصادر.
|
| 461 |
+
- لا تخترع أرقاماً دقيقة إذا لم تكن متأكداً.
|
| 462 |
+
- أضف في نهاية المنشور سطر هاشتاكات مناسب، 3 إلى 6 هاشتاكات حسب الموضوع فقط.
|
| 463 |
+
- اجعل الهاشتاكات في آخر سطر مستقل فقط، ولا تضع أي هاشتاك داخل النص.
|
| 464 |
+
- لا تضف #قلعة_المعلومات_العامة؛ هذا يضاف تلقائياً داخل التوقيع.
|
| 465 |
+
- لا تضف رابط القناة ولا عبارة الاشتراك.
|
| 466 |
+
- طول المنشور قبل الهاشتاكات لا يتجاوز 900 حرف.
|
| 467 |
+
"""
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def generate_post_for_article(article: Dict[str, Any], data: Dict[str, Any]) -> str:
|
| 471 |
+
return generate_with_auto_model(build_article_prompt(article), data)[0]
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def generate_fallback_article(data: Dict[str, Any]) -> Dict[str, Any]:
|
| 475 |
+
used = set(data.get("posted_titles", []))
|
| 476 |
+
topics = [t for t in FALLBACK_TOPICS if t not in used]
|
| 477 |
+
if not topics:
|
| 478 |
+
topics = FALLBACK_TOPICS[:]
|
| 479 |
+
topic = random.choice(topics)
|
| 480 |
+
|
| 481 |
+
generated, model_name = generate_with_auto_model(build_fallback_prompt(topic), data)
|
| 482 |
+
|
| 483 |
+
return {
|
| 484 |
+
"mode": "fallback",
|
| 485 |
+
"source": f"Gemini:{model_name}",
|
| 486 |
+
"category": "معلومات عامة",
|
| 487 |
+
"title": topic,
|
| 488 |
+
"link": "fallback:" + topic,
|
| 489 |
+
"text": topic,
|
| 490 |
+
"image_url": None,
|
| 491 |
+
"generated_post": generated
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def build_caption(post: str) -> str:
|
| 496 |
+
"""
|
| 497 |
+
Build final Telegram caption EXACTLY in the requested format:
|
| 498 |
+
|
| 499 |
+
<b>Title</b>
|
| 500 |
+
|
| 501 |
+
<b>Body paragraphs</b>
|
| 502 |
+
|
| 503 |
+
━━━━━━━━━━━━
|
| 504 |
+
|
| 505 |
+
<b>لأنك تستحق أن تعرف</b>
|
| 506 |
+
|
| 507 |
+
#topic_hashtags
|
| 508 |
+
|
| 509 |
+
#قلعة_المعلومات_العامة
|
| 510 |
+
|
| 511 |
+
اشتـــرك الآن :- https://t.me/CastleInfoiq
|
| 512 |
+
"""
|
| 513 |
+
raw = (post or "").replace("**", "").strip()
|
| 514 |
+
raw = re.sub(r"\n{3,}", "\n\n", raw)
|
| 515 |
+
|
| 516 |
+
lines = [line.strip() for line in raw.splitlines() if line.strip()]
|
| 517 |
+
if not lines:
|
| 518 |
+
lines = ["معلومة جديدة تستحق أن تعرفها"]
|
| 519 |
+
|
| 520 |
+
title = lines[0]
|
| 521 |
+
|
| 522 |
+
hashtags_lines = []
|
| 523 |
+
body_lines = []
|
| 524 |
+
|
| 525 |
+
for line in lines[1:]:
|
| 526 |
+
if "#" in line:
|
| 527 |
+
hashtags_lines.append(line)
|
| 528 |
+
else:
|
| 529 |
+
body_lines.append(line)
|
| 530 |
+
|
| 531 |
+
# Keep only topic hashtags generated by Gemini, remove channel hashtag if Gemini added it.
|
| 532 |
+
hashtags_text = " ".join(hashtags_lines).strip()
|
| 533 |
+
hashtags = re.findall(r"#\S+", hashtags_text)
|
| 534 |
+
hashtags = [h for h in hashtags if h != "#قلعة_المعلومات_العامة"]
|
| 535 |
+
|
| 536 |
+
# If Gemini failed to provide hashtags, add safe generic ones.
|
| 537 |
+
if not hashtags:
|
| 538 |
+
hashtags = ["#علوم", "#معرفة", "#معلومات_عامة"]
|
| 539 |
+
|
| 540 |
+
# Limit hashtags to keep caption clean.
|
| 541 |
+
hashtags_line = " ".join(hashtags[:6])
|
| 542 |
+
|
| 543 |
+
body = "\n\n".join(body_lines).strip()
|
| 544 |
+
if not body:
|
| 545 |
+
body = "تفاصيل هذه المعلومة تكشف جانباً مثيراً من عالم المعرفة، وتفتح أمام القارئ سؤالاً جديداً: كم من الأسرار ما زال مخفياً حولنا؟"
|
| 546 |
+
|
| 547 |
+
# Telegram photo caption max is 1024. Keep body safe before HTML escaping.
|
| 548 |
+
fixed_tail_plain = "\n\n━━━━━━━━━━━━\n\nلأنك تستحق أن تعرف\n\n" + hashtags_line + "\n\n" + SIGNATURE
|
| 549 |
+
available = 940 - len(title) - len(fixed_tail_plain)
|
| 550 |
+
if available < 250:
|
| 551 |
+
available = 250
|
| 552 |
+
|
| 553 |
+
if len(body) > available:
|
| 554 |
+
body = body[:available].rstrip()
|
| 555 |
+
last_dot = max(body.rfind("."), body.rfind("!"), body.rfind("؟"))
|
| 556 |
+
if last_dot > 180:
|
| 557 |
+
body = body[:last_dot + 1]
|
| 558 |
+
else:
|
| 559 |
+
body += "..."
|
| 560 |
+
|
| 561 |
+
safe_title = html.escape(title)
|
| 562 |
+
safe_body = html.escape(body)
|
| 563 |
+
safe_hashtags = html.escape(hashtags_line)
|
| 564 |
+
safe_signature = html.escape(SIGNATURE)
|
| 565 |
+
|
| 566 |
+
return (
|
| 567 |
+
f"<b>{safe_title}</b>\n\n"
|
| 568 |
+
f"<b>{safe_body}</b>\n\n"
|
| 569 |
+
f"━━━━━━━━━━━━\n\n"
|
| 570 |
+
f"<b>لأنك تستحق أن تعرف</b>\n\n"
|
| 571 |
+
f"{safe_hashtags}\n\n"
|
| 572 |
+
f"{safe_signature}"
|
| 573 |
+
)
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def download_image(image_url: str) -> Optional[Path]:
|
| 577 |
+
"""
|
| 578 |
+
Download article image and always convert it to Telegram-safe JPG.
|
| 579 |
+
This fixes PHOTO_EXT_INVALID and unsupported formats like webp/png without valid extension.
|
| 580 |
+
"""
|
| 581 |
+
if not image_url:
|
| 582 |
+
return None
|
| 583 |
+
|
| 584 |
+
raw_path = None
|
| 585 |
+
jpg_path = None
|
| 586 |
+
|
| 587 |
+
try:
|
| 588 |
+
r = requests.get(
|
| 589 |
+
image_url,
|
| 590 |
+
headers={"User-Agent": USER_AGENT},
|
| 591 |
+
timeout=30,
|
| 592 |
+
allow_redirects=True
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
ct = r.headers.get("content-type", "")
|
| 596 |
+
if r.status_code != 200 or not r.content:
|
| 597 |
+
logging.warning("image rejected status=%s content-type=%s", r.status_code, ct)
|
| 598 |
+
return None
|
| 599 |
+
|
| 600 |
+
raw_path = DATA_DIR / f"raw_image_{int(time.time())}"
|
| 601 |
+
raw_path.write_bytes(r.content)
|
| 602 |
+
|
| 603 |
+
jpg_path = DATA_DIR / f"image_{int(time.time())}.jpg"
|
| 604 |
+
|
| 605 |
+
with Image.open(raw_path) as im:
|
| 606 |
+
# Convert transparency/palette/CMYK/etc. to RGB JPG
|
| 607 |
+
if im.mode in ("RGBA", "LA", "P"):
|
| 608 |
+
background = Image.new("RGB", im.size, (255, 255, 255))
|
| 609 |
+
if im.mode == "P":
|
| 610 |
+
im = im.convert("RGBA")
|
| 611 |
+
background.paste(im, mask=im.split()[-1] if im.mode in ("RGBA", "LA") else None)
|
| 612 |
+
im = background
|
| 613 |
+
else:
|
| 614 |
+
im = im.convert("RGB")
|
| 615 |
+
|
| 616 |
+
# Reduce very large images for Telegram stability
|
| 617 |
+
max_side = 2000
|
| 618 |
+
w, h = im.size
|
| 619 |
+
if max(w, h) > max_side:
|
| 620 |
+
ratio = max_side / float(max(w, h))
|
| 621 |
+
im = im.resize((int(w * ratio), int(h * ratio)))
|
| 622 |
+
|
| 623 |
+
quality = 88
|
| 624 |
+
im.save(jpg_path, format="JPEG", quality=quality, optimize=True)
|
| 625 |
+
|
| 626 |
+
# If still too large, compress more
|
| 627 |
+
if jpg_path.exists() and jpg_path.stat().st_size > 8_000_000:
|
| 628 |
+
with Image.open(jpg_path) as im:
|
| 629 |
+
im = im.convert("RGB")
|
| 630 |
+
im.save(jpg_path, format="JPEG", quality=72, optimize=True)
|
| 631 |
+
|
| 632 |
+
if not jpg_path.exists() or jpg_path.stat().st_size < 1000:
|
| 633 |
+
return None
|
| 634 |
+
|
| 635 |
+
return jpg_path
|
| 636 |
+
|
| 637 |
+
except Exception as e:
|
| 638 |
+
logging.warning("image download/convert failed: %s", e)
|
| 639 |
+
return None
|
| 640 |
+
|
| 641 |
+
finally:
|
| 642 |
+
try:
|
| 643 |
+
if raw_path and raw_path.exists():
|
| 644 |
+
raw_path.unlink(missing_ok=True)
|
| 645 |
+
except Exception:
|
| 646 |
+
pass
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def send_to_telegram(bot: Bot, caption: str, image_url: Optional[str] = None) -> None:
|
| 650 |
+
"""
|
| 651 |
+
Telegram sender using Pyrogram.
|
| 652 |
+
Fixed for Flask request threads by creating an asyncio event loop inside the thread.
|
| 653 |
+
Requires Secrets:
|
| 654 |
+
- API_ID
|
| 655 |
+
- API_HASH
|
| 656 |
+
- BOT_TOKEN
|
| 657 |
+
"""
|
| 658 |
+
img_path = download_image(image_url) if image_url else None
|
| 659 |
+
|
| 660 |
+
if not API_ID or not API_HASH:
|
| 661 |
+
raise RuntimeError("API_ID/API_HASH are missing. Add them to HuggingFace Secrets to use Pyrogram sender.")
|
| 662 |
+
|
| 663 |
+
loop = asyncio.new_event_loop()
|
| 664 |
+
asyncio.set_event_loop(loop)
|
| 665 |
+
|
| 666 |
+
try:
|
| 667 |
+
with Client(
|
| 668 |
+
"castle_info_bot",
|
| 669 |
+
api_id=API_ID,
|
| 670 |
+
api_hash=API_HASH,
|
| 671 |
+
bot_token=BOT_TOKEN,
|
| 672 |
+
in_memory=True
|
| 673 |
+
) as app:
|
| 674 |
+
if img_path and img_path.exists():
|
| 675 |
+
try:
|
| 676 |
+
app.send_photo(
|
| 677 |
+
chat_id=TELEGRAM_CHANNEL_ID,
|
| 678 |
+
photo=str(img_path),
|
| 679 |
+
caption=caption,
|
| 680 |
+
parse_mode=enums.ParseMode.HTML
|
| 681 |
+
)
|
| 682 |
+
logging.info("Posted photo to Telegram via Pyrogram")
|
| 683 |
+
return
|
| 684 |
+
except Exception as e:
|
| 685 |
+
logging.warning("Pyrogram photo failed, fallback to text: %s", e)
|
| 686 |
+
|
| 687 |
+
app.send_message(
|
| 688 |
+
chat_id=TELEGRAM_CHANNEL_ID,
|
| 689 |
+
text=caption,
|
| 690 |
+
parse_mode=enums.ParseMode.HTML,
|
| 691 |
+
disable_web_page_preview=True
|
| 692 |
+
)
|
| 693 |
+
logging.info("Posted text to Telegram via Pyrogram")
|
| 694 |
+
|
| 695 |
+
finally:
|
| 696 |
+
if img_path:
|
| 697 |
+
img_path.unlink(missing_ok=True)
|
| 698 |
+
try:
|
| 699 |
+
loop.close()
|
| 700 |
+
except Exception:
|
| 701 |
+
pass
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
def remember_post(data: Dict[str, Any], article: Dict[str, Any], final_text: str) -> None:
|
| 705 |
+
link = article.get("link", "")
|
| 706 |
+
title = article.get("title", "")
|
| 707 |
+
|
| 708 |
+
if link:
|
| 709 |
+
data.setdefault("posted_links", []).append(link)
|
| 710 |
+
if title:
|
| 711 |
+
data.setdefault("posted_titles", []).append(title)
|
| 712 |
+
|
| 713 |
+
data["posted_links"] = data.get("posted_links", [])[-700:]
|
| 714 |
+
data["posted_titles"] = data.get("posted_titles", [])[-700:]
|
| 715 |
+
|
| 716 |
+
data.setdefault("last_posts", []).append({
|
| 717 |
+
"time": datetime.now(pytz.timezone(TIMEZONE)).isoformat(),
|
| 718 |
+
"mode": article.get("mode"),
|
| 719 |
+
"source": article.get("source"),
|
| 720 |
+
"category": article.get("category"),
|
| 721 |
+
"title": title,
|
| 722 |
+
"link": link,
|
| 723 |
+
"image": bool(article.get("image_url")),
|
| 724 |
+
"text_preview": final_text[:250]
|
| 725 |
+
})
|
| 726 |
+
data["last_posts"] = data["last_posts"][-40:]
|
| 727 |
+
data["last_error"] = ""
|
| 728 |
+
save_data(data)
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
def run_once() -> None:
|
| 732 |
+
logging.info("Run started")
|
| 733 |
+
data = load_data()
|
| 734 |
+
bot = Bot(token=BOT_TOKEN)
|
| 735 |
+
|
| 736 |
+
try:
|
| 737 |
+
article = get_candidate_article(data)
|
| 738 |
+
|
| 739 |
+
if article:
|
| 740 |
+
generated = generate_post_for_article(article, data)
|
| 741 |
+
else:
|
| 742 |
+
logging.info("No RSS article found, using fallback B content")
|
| 743 |
+
article = generate_fallback_article(data)
|
| 744 |
+
generated = article["generated_post"]
|
| 745 |
+
|
| 746 |
+
caption = build_caption(generated)
|
| 747 |
+
send_to_telegram(bot, caption, article.get("image_url"))
|
| 748 |
+
remember_post(data, article, caption)
|
| 749 |
+
logging.info("Run completed")
|
| 750 |
+
|
| 751 |
+
except Exception as e:
|
| 752 |
+
logging.exception("Run failed")
|
| 753 |
+
data["last_error"] = f"{datetime.now().isoformat()} | {str(e)}"
|
| 754 |
+
save_data(data)
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
def create_status_html() -> str:
|
| 758 |
+
data = load_data()
|
| 759 |
+
last_posts = data.get("last_posts", [])[-10:]
|
| 760 |
+
rows = ""
|
| 761 |
+
for p in reversed(last_posts):
|
| 762 |
+
rows += f"""
|
| 763 |
+
<tr>
|
| 764 |
+
<td>{p.get('time','')}</td>
|
| 765 |
+
<td>{p.get('category','')}</td>
|
| 766 |
+
<td>{p.get('source','')}</td>
|
| 767 |
+
<td>{p.get('title','')}</td>
|
| 768 |
+
<td>{'نعم' if p.get('image') else 'لا'}</td>
|
| 769 |
+
</tr>
|
| 770 |
+
"""
|
| 771 |
+
|
| 772 |
+
last_error = data.get("last_error") or "لا يوجد"
|
| 773 |
+
total = len(data.get("posted_links", []))
|
| 774 |
+
active_model = data.get("active_gemini_model") or "لم يتم اختياره بعد"
|
| 775 |
+
|
| 776 |
+
return f"""
|
| 777 |
+
<html dir="rtl" lang="ar">
|
| 778 |
+
<head>
|
| 779 |
+
<meta charset="utf-8">
|
| 780 |
+
<title>Castle Info Bot</title>
|
| 781 |
+
<style>
|
| 782 |
+
body {{ font-family: Arial, sans-serif; padding: 30px; background: #f7f7f7; }}
|
| 783 |
+
.card {{ background: white; padding: 20px; border-radius: 14px; box-shadow: 0 2px 12px #ddd; margin-bottom: 20px; }}
|
| 784 |
+
table {{ width:100%; border-collapse: collapse; background: white; }}
|
| 785 |
+
td, th {{ border:1px solid #ddd; padding:10px; }}
|
| 786 |
+
th {{ background:#eee; }}
|
| 787 |
+
code {{ direction:ltr; display:inline-block; white-space: pre-wrap; }}
|
| 788 |
+
</style>
|
| 789 |
+
</head>
|
| 790 |
+
<body>
|
| 791 |
+
<div class="card">
|
| 792 |
+
<h2>قلعة المعلومات العامة - Bot Status</h2>
|
| 793 |
+
<p>الحالة: يعمل ✅</p>
|
| 794 |
+
<p>الجدول: كل ساعتين من 10 صباحاً إلى 10 ليلاً بتوقيت العراق</p>
|
| 795 |
+
<p>موديل Gemini الحالي: <b>{active_model}</b></p>
|
| 796 |
+
<p>عدد الروابط المحفوظة لمنع التكرار: <b>{total}</b></p>
|
| 797 |
+
<p>آخر خطأ: <code>{last_error}</code></p>
|
| 798 |
+
</div>
|
| 799 |
+
<div class="card">
|
| 800 |
+
<h3>آخر المنشورات</h3>
|
| 801 |
+
<table>
|
| 802 |
+
<tr><th>الوقت</th><th>القسم</th><th>المصدر</th><th>العنوان</th><th>صورة</th></tr>
|
| 803 |
+
{rows}
|
| 804 |
+
</table>
|
| 805 |
+
</div>
|
| 806 |
+
<div class="card">
|
| 807 |
+
<p>للتجربة اليدوية افتح: <code>/run-now-secret</code></p>
|
| 808 |
+
</div>
|
| 809 |
+
</body>
|
| 810 |
+
</html>
|
| 811 |
+
"""
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
app = Flask(__name__)
|
| 815 |
+
|
| 816 |
+
@app.route("/")
|
| 817 |
+
def home():
|
| 818 |
+
return create_status_html()
|
| 819 |
+
|
| 820 |
+
@app.route("/run-now-secret")
|
| 821 |
+
def run_now_secret():
|
| 822 |
+
run_once()
|
| 823 |
+
return "تم تشغيل النشر اليدوي. افحص القناة والسجلات."
|
| 824 |
+
|
| 825 |
+
@app.route("/health")
|
| 826 |
+
def health():
|
| 827 |
+
return "ok"
|
| 828 |
+
|
| 829 |
+
|
| 830 |
+
def start_scheduler():
|
| 831 |
+
scheduler = BackgroundScheduler(timezone=TIMEZONE)
|
| 832 |
+
scheduler.add_job(
|
| 833 |
+
run_once,
|
| 834 |
+
"cron",
|
| 835 |
+
hour="10,12,14,16,18,20,22",
|
| 836 |
+
minute=0,
|
| 837 |
+
second=0,
|
| 838 |
+
id="castle_info_posts",
|
| 839 |
+
replace_existing=True,
|
| 840 |
+
max_instances=1,
|
| 841 |
+
coalesce=True,
|
| 842 |
+
misfire_grace_time=300
|
| 843 |
+
)
|
| 844 |
+
scheduler.start()
|
| 845 |
+
logging.info("Scheduler started: %s", POST_HOURS)
|
| 846 |
+
|
| 847 |
+
|
| 848 |
+
validate_env()
|
| 849 |
+
init_gemini()
|
| 850 |
+
start_scheduler()
|
| 851 |
+
|
| 852 |
+
if RUN_ON_START:
|
| 853 |
+
try:
|
| 854 |
+
run_once()
|
| 855 |
+
except Exception:
|
| 856 |
+
logging.exception("RUN_ON_START failed")
|
| 857 |
+
|
| 858 |
+
if __name__ == "__main__":
|
| 859 |
+
port = int(os.getenv("PORT", "7860"))
|
| 860 |
+
app.run(host="0.0.0.0", port=port)
|