allboot commited on
Commit
d551a9f
·
verified ·
1 Parent(s): acd9311

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -761
app.py DELETED
@@ -1,761 +0,0 @@
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_api_request(method: str, data: Dict[str, Any], files: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
525
- """
526
- Direct Telegram API call with longer timeout and retries.
527
- This avoids python-telegram-bot v13 short 5-second connect timeout.
528
- """
529
- url = f"https://api.telegram.org/bot{BOT_TOKEN}/{method}"
530
- last_error = None
531
-
532
- for attempt in range(1, 5):
533
- try:
534
- response = requests.post(
535
- url,
536
- data=data,
537
- files=files,
538
- timeout=(30, 90)
539
- )
540
-
541
- if response.status_code == 200:
542
- result = response.json()
543
- if result.get("ok"):
544
- return result
545
- raise RuntimeError(f"Telegram API returned ok=false: {result}")
546
-
547
- raise RuntimeError(f"Telegram HTTP {response.status_code}: {response.text[:500]}")
548
-
549
- except Exception as e:
550
- last_error = e
551
- logging.warning("Telegram API attempt %s failed for %s: %s", attempt, method, e)
552
- time.sleep(5 * attempt)
553
-
554
- raise RuntimeError(f"Telegram API failed after retries for {method}: {last_error}")
555
-
556
-
557
- def send_text_direct(caption: str) -> None:
558
- telegram_api_request(
559
- "sendMessage",
560
- data={
561
- "chat_id": TELEGRAM_CHANNEL_ID,
562
- "text": caption,
563
- "disable_web_page_preview": "false"
564
- }
565
- )
566
- logging.info("Posted text to Telegram")
567
-
568
-
569
- def send_to_telegram(bot: Bot, caption: str, image_url: Optional[str] = None) -> None:
570
- """
571
- Send post to Telegram.
572
- 1) Try photo with caption.
573
- 2) If photo upload fails, fallback to text.
574
- 3) Uses direct Telegram API with longer timeout and retries.
575
- """
576
- img_path = download_image(image_url) if image_url else None
577
-
578
- try:
579
- if img_path and img_path.exists():
580
- try:
581
- with img_path.open("rb") as f:
582
- telegram_api_request(
583
- "sendPhoto",
584
- data={
585
- "chat_id": TELEGRAM_CHANNEL_ID,
586
- "caption": caption
587
- },
588
- files={
589
- "photo": (img_path.name, f)
590
- }
591
- )
592
- logging.info("Posted photo to Telegram")
593
- return
594
-
595
- except Exception as e:
596
- logging.warning("Photo upload failed, fallback to text: %s", e)
597
- send_text_direct(caption)
598
- logging.info("Posted text fallback to Telegram")
599
- return
600
-
601
- send_text_direct(caption)
602
-
603
- finally:
604
- if img_path:
605
- img_path.unlink(missing_ok=True)
606
-
607
-
608
- def remember_post(data: Dict[str, Any], article: Dict[str, Any], final_text: str) -> None:
609
- link = article.get("link", "")
610
- title = article.get("title", "")
611
-
612
- if link:
613
- data.setdefault("posted_links", []).append(link)
614
- if title:
615
- data.setdefault("posted_titles", []).append(title)
616
-
617
- data["posted_links"] = data.get("posted_links", [])[-700:]
618
- data["posted_titles"] = data.get("posted_titles", [])[-700:]
619
-
620
- data.setdefault("last_posts", []).append({
621
- "time": datetime.now(pytz.timezone(TIMEZONE)).isoformat(),
622
- "mode": article.get("mode"),
623
- "source": article.get("source"),
624
- "category": article.get("category"),
625
- "title": title,
626
- "link": link,
627
- "image": bool(article.get("image_url")),
628
- "text_preview": final_text[:250]
629
- })
630
- data["last_posts"] = data["last_posts"][-40:]
631
- data["last_error"] = ""
632
- save_data(data)
633
-
634
-
635
- def run_once() -> None:
636
- logging.info("Run started")
637
- data = load_data()
638
- bot = Bot(token=BOT_TOKEN)
639
-
640
- try:
641
- article = get_candidate_article(data)
642
-
643
- if article:
644
- generated = generate_post_for_article(article, data)
645
- else:
646
- logging.info("No RSS article found, using fallback B content")
647
- article = generate_fallback_article(data)
648
- generated = article["generated_post"]
649
-
650
- caption = build_caption(generated)
651
- send_to_telegram(bot, caption, article.get("image_url"))
652
- remember_post(data, article, caption)
653
- logging.info("Run completed")
654
-
655
- except Exception as e:
656
- logging.exception("Run failed")
657
- data["last_error"] = f"{datetime.now().isoformat()} | {str(e)}"
658
- save_data(data)
659
-
660
-
661
- def create_status_html() -> str:
662
- data = load_data()
663
- last_posts = data.get("last_posts", [])[-10:]
664
- rows = ""
665
- for p in reversed(last_posts):
666
- rows += f"""
667
- <tr>
668
- <td>{p.get('time','')}</td>
669
- <td>{p.get('category','')}</td>
670
- <td>{p.get('source','')}</td>
671
- <td>{p.get('title','')}</td>
672
- <td>{'نعم' if p.get('image') else 'لا'}</td>
673
- </tr>
674
- """
675
-
676
- last_error = data.get("last_error") or "لا يوجد"
677
- total = len(data.get("posted_links", []))
678
- active_model = data.get("active_gemini_model") or "لم يتم اختياره بعد"
679
-
680
- return f"""
681
- <html dir="rtl" lang="ar">
682
- <head>
683
- <meta charset="utf-8">
684
- <title>Castle Info Bot</title>
685
- <style>
686
- body {{ font-family: Arial, sans-serif; padding: 30px; background: #f7f7f7; }}
687
- .card {{ background: white; padding: 20px; border-radius: 14px; box-shadow: 0 2px 12px #ddd; margin-bottom: 20px; }}
688
- table {{ width:100%; border-collapse: collapse; background: white; }}
689
- td, th {{ border:1px solid #ddd; padding:10px; }}
690
- th {{ background:#eee; }}
691
- code {{ direction:ltr; display:inline-block; white-space: pre-wrap; }}
692
- </style>
693
- </head>
694
- <body>
695
- <div class="card">
696
- <h2>قلعة المعلومات العامة - Bot Status</h2>
697
- <p>الحالة: يعمل ✅</p>
698
- <p>الجدول: كل ساعتين من 10 صباحاً إلى 10 ليلاً بتوقيت العراق</p>
699
- <p>موديل Gemini الحالي: <b>{active_model}</b></p>
700
- <p>عدد الروابط المحفوظة لمنع التكرار: <b>{total}</b></p>
701
- <p>آخر خطأ: <code>{last_error}</code></p>
702
- </div>
703
- <div class="card">
704
- <h3>آخر المنشورات</h3>
705
- <table>
706
- <tr><th>الوقت</th><th>القسم</th><th>المصدر</th><th>العنوان</th><th>صورة</th></tr>
707
- {rows}
708
- </table>
709
- </div>
710
- <div class="card">
711
- <p>للتجربة اليدوية افتح: <code>/run-now-secret</code></p>
712
- </div>
713
- </body>
714
- </html>
715
- """
716
-
717
-
718
- app = Flask(__name__)
719
-
720
- @app.route("/")
721
- def home():
722
- return create_status_html()
723
-
724
- @app.route("/run-now-secret")
725
- def run_now_secret():
726
- run_once()
727
- return "تم تشغيل النشر اليدوي. افحص القناة والسجلات."
728
-
729
- @app.route("/health")
730
- def health():
731
- return "ok"
732
-
733
-
734
- def start_scheduler():
735
- scheduler = BackgroundScheduler(timezone=TIMEZONE)
736
- scheduler.add_job(
737
- run_once,
738
- "cron",
739
- hour="10,12,14,16,18,20,22",
740
- minute=0,
741
- second=0,
742
- id="castle_info_posts",
743
- replace_existing=True
744
- )
745
- scheduler.start()
746
- logging.info("Scheduler started: %s", POST_HOURS)
747
-
748
-
749
- validate_env()
750
- init_gemini()
751
- start_scheduler()
752
-
753
- if RUN_ON_START:
754
- try:
755
- run_once()
756
- except Exception:
757
- logging.exception("RUN_ON_START failed")
758
-
759
- if __name__ == "__main__":
760
- port = int(os.getenv("PORT", "7860"))
761
- app.run(host="0.0.0.0", port=port)