Alialdlfy1 commited on
Commit
f939e3e
·
verified ·
1 Parent(s): 6b38736

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -143
app.py DELETED
@@ -1,143 +0,0 @@
1
- import os
2
- import sys
3
- import time
4
- import subprocess
5
- import threading
6
- import streamlit as st
7
-
8
- st.set_page_config(page_title="Telegram Auto Poster")
9
- st.title("🤖 بوت النشر التلقائي")
10
-
11
- PID_FILE = "/tmp/telegram_auto_poster_bot.pid"
12
- CORE_LOCK_FILE = "/tmp/telegram_bot_core_running.lock"
13
- LOG_FILE = "/tmp/telegram_auto_poster_bot.log"
14
-
15
-
16
- def _pid_is_running(pid: int) -> bool:
17
- try:
18
- os.kill(pid, 0)
19
- return True
20
- except ProcessLookupError:
21
- return False
22
- except PermissionError:
23
- return True
24
- except Exception:
25
- return False
26
-
27
-
28
- def get_running_pid():
29
- if not os.path.exists(PID_FILE):
30
- return None
31
- try:
32
- raw = open(PID_FILE, "r", encoding="utf-8").read().strip()
33
- if not raw:
34
- return None
35
- pid = int(raw)
36
- if _pid_is_running(pid):
37
- return pid
38
- try:
39
- os.remove(PID_FILE)
40
- except Exception:
41
- pass
42
- return None
43
- except Exception:
44
- return None
45
-
46
-
47
- def _pipe_logs(process: subprocess.Popen):
48
- try:
49
- with open(LOG_FILE, "a", encoding="utf-8") as lf:
50
- for raw in iter(process.stdout.readline, ""):
51
- if not raw:
52
- break
53
- line = raw.rstrip("\n")
54
- print(line, flush=True)
55
- lf.write(line + "\n")
56
- lf.flush()
57
- except Exception as e:
58
- print(f"[app] log pipe failed: {e}", flush=True)
59
-
60
-
61
-
62
- def preflight_storage_check():
63
- """يفحص قاعدة البيانات قبل تشغيل البوت ويستعيد Backup إذا أمكن."""
64
- try:
65
- import database as db
66
- if hasattr(db, "verify_or_recover_storage"):
67
- return db.verify_or_recover_storage()
68
- return {"ok": True, "message": "لا يوجد فحص تخزين في database.py"}
69
- except Exception as e:
70
- return {"ok": False, "message": f"فشل فحص التخزين: {e}"}
71
-
72
- def start_bot_process():
73
- os.makedirs("/data", exist_ok=True)
74
-
75
- storage_status = preflight_storage_check()
76
- if not storage_status.get("ok"):
77
- return None, False, "storage:" + str(storage_status.get("message"))
78
-
79
- existing_pid = get_running_pid()
80
- if existing_pid:
81
- return existing_pid, False, None
82
-
83
- try:
84
- if os.path.exists(CORE_LOCK_FILE):
85
- os.remove(CORE_LOCK_FILE)
86
- except Exception:
87
- pass
88
-
89
- env = os.environ.copy()
90
- env["PYTHONUNBUFFERED"] = "1"
91
-
92
- cmd = [sys.executable, "-u", "-c", "from bot_core import run_bot; run_bot()"]
93
- print(f"[app] starting bot process: {' '.join(cmd)}", flush=True)
94
-
95
- process = subprocess.Popen(
96
- cmd,
97
- env=env,
98
- stdout=subprocess.PIPE,
99
- stderr=subprocess.STDOUT,
100
- text=True,
101
- bufsize=1,
102
- start_new_session=True,
103
- )
104
-
105
- threading.Thread(target=_pipe_logs, args=(process,), daemon=True).start()
106
-
107
- with open(PID_FILE, "w", encoding="utf-8") as f:
108
- f.write(str(process.pid))
109
-
110
- time.sleep(2)
111
- exit_code = process.poll()
112
- if exit_code is not None:
113
- try:
114
- os.remove(PID_FILE)
115
- except Exception:
116
- pass
117
- return process.pid, True, exit_code
118
-
119
- return process.pid, True, None
120
-
121
-
122
- pid, started_now, exit_code = start_bot_process()
123
-
124
- if exit_code is not None:
125
- if isinstance(exit_code, str) and exit_code.startswith("storage:"):
126
- st.error("❌ تم إيقاف التشغيل لحماية بياناتك.")
127
- st.warning(exit_code.replace("storage:", "", 1))
128
- else:
129
- st.error(f"❌ فشل تشغيل البوت. PID: {pid} | Exit code: {exit_code}")
130
- st.warning("افتح Logs وشوف الخطأ الذي يبدأ بـ Traceback أو ERROR.")
131
- elif started_now:
132
- st.success(f"✅ تم تشغيل البوت بنجاح. PID: {pid}")
133
- else:
134
- st.success(f"✅ البوت يعمل مسبقاً. PID: {pid}")
135
-
136
- st.info("البوت يعمل في الخلفية. استخدم تيليجرام للتحكم.")
137
-
138
- with st.expander("معلومات التشغيل"):
139
- st.write("إذا غيّرت Secrets أو رفعت ملفات جديدة، استخدم Restart Space من Hugging Face.")
140
- st.write("PID file:", PID_FILE)
141
- st.write("Core lock file:", CORE_LOCK_FILE)
142
- st.write("Bot log file:", LOG_FILE)
143
- st.write("تم إخفاء سجل البوت من صفحة App حتى تبقى الصفحة خفيفة. راجع تبويب Logs عند الحاجة.")