allboot commited on
Commit
7b336d3
·
verified ·
1 Parent(s): 332f403

Delete app.py

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