allboot commited on
Commit
b8ea391
·
verified ·
1 Parent(s): 6d214d8

Upload app.py

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