Alialdlfy1 commited on
Commit
b1a682f
·
verified ·
1 Parent(s): e0ae7c6

Upload 7 files

Browse files
Files changed (7) hide show
  1. Dockerfile +13 -0
  2. README.md +13 -0
  3. app.py +129 -0
  4. bot_core.py +1322 -0
  5. config.py +23 -0
  6. database.py +412 -0
  7. requirements.txt +3 -0
Dockerfile ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9-slim
2
+
3
+ WORKDIR /code
4
+
5
+ # إنشاء مجلد البيانات الدائمة
6
+ RUN mkdir -p /data
7
+
8
+ COPY requirements.txt .
9
+ RUN pip install --no-cache-dir -r requirements.txt
10
+
11
+ COPY . .
12
+
13
+ CMD ["streamlit", "run", "app.py", "--server.port=7860", "--server.address=0.0.0.0"]
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Teleautoadminbot
3
+ emoji: 📉
4
+ colorFrom: green
5
+ colorTo: yellow
6
+ sdk: docker
7
+ app_file: app.py
8
+ pinned: false
9
+ license: apache-2.0
10
+ ---
11
+
12
+ # بوت النشر التلقائي عبر تيليجرام
13
+ يعمل على Hugging Face مع Docker.
app.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def start_bot_process():
62
+ os.makedirs("/data", exist_ok=True)
63
+
64
+ existing_pid = get_running_pid()
65
+ if existing_pid:
66
+ return existing_pid, False, None
67
+
68
+ try:
69
+ if os.path.exists(CORE_LOCK_FILE):
70
+ os.remove(CORE_LOCK_FILE)
71
+ except Exception:
72
+ pass
73
+
74
+ env = os.environ.copy()
75
+ env["PYTHONUNBUFFERED"] = "1"
76
+
77
+ cmd = [sys.executable, "-u", "-c", "from bot_core import run_bot; run_bot()"]
78
+ print(f"[app] starting bot process: {' '.join(cmd)}", flush=True)
79
+
80
+ process = subprocess.Popen(
81
+ cmd,
82
+ env=env,
83
+ stdout=subprocess.PIPE,
84
+ stderr=subprocess.STDOUT,
85
+ text=True,
86
+ bufsize=1,
87
+ start_new_session=True,
88
+ )
89
+
90
+ threading.Thread(target=_pipe_logs, args=(process,), daemon=True).start()
91
+
92
+ with open(PID_FILE, "w", encoding="utf-8") as f:
93
+ f.write(str(process.pid))
94
+
95
+ time.sleep(2)
96
+ exit_code = process.poll()
97
+ if exit_code is not None:
98
+ try:
99
+ os.remove(PID_FILE)
100
+ except Exception:
101
+ pass
102
+ return process.pid, True, exit_code
103
+
104
+ return process.pid, True, None
105
+
106
+
107
+ pid, started_now, exit_code = start_bot_process()
108
+
109
+ if exit_code is not None:
110
+ st.error(f"❌ فشل تشغيل البوت. PID: {pid} | Exit code: {exit_code}")
111
+ st.warning("افتح Logs وشوف الخطأ الذي يبدأ بـ Traceback أو ERROR.")
112
+ elif started_now:
113
+ st.success(f"✅ تم تشغيل البوت بنجاح. PID: {pid}")
114
+ else:
115
+ st.success(f"✅ البوت يعمل مسبقاً. PID: {pid}")
116
+
117
+ st.info("البوت يعمل في الخلفية. استخدم تيليجرام للتحكم.")
118
+
119
+ with st.expander("معلومات التشغيل"):
120
+ st.write("إذا غيّرت Secrets أو رفعت ملفات جديدة، استخدم Restart Space من Hugging Face.")
121
+ st.write("PID file:", PID_FILE)
122
+ st.write("Core lock file:", CORE_LOCK_FILE)
123
+ st.write("Bot log file:", LOG_FILE)
124
+ if os.path.exists(LOG_FILE):
125
+ try:
126
+ tail = open(LOG_FILE, "r", encoding="utf-8", errors="ignore").read().splitlines()[-80:]
127
+ st.code("\n".join(tail))
128
+ except Exception as e:
129
+ st.write(f"تعذر قراءة اللوج: {e}")
bot_core.py ADDED
@@ -0,0 +1,1322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import re
3
+ import logging
4
+ import tempfile
5
+ import os
6
+ import time
7
+
8
+ from pyrogram import Client, filters
9
+ from pyrogram.handlers import MessageHandler, CallbackQueryHandler
10
+ from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
11
+ from pyrogram.errors import MessageNotModified
12
+
13
+ import config
14
+ import database as db
15
+
16
+ logging.basicConfig(level=logging.INFO)
17
+ logger = logging.getLogger(__name__)
18
+
19
+ bot_client = None
20
+ user_client = None
21
+ user_states = {}
22
+ _middle_peer_warmed = False
23
+ _middle_auto_ignore_until = 0.0
24
+
25
+
26
+ def is_admin(user_id):
27
+ return user_id in config.ADMINS
28
+
29
+ def clean_text(text):
30
+ if not text:
31
+ return text
32
+
33
+ if isinstance(text, str):
34
+ text = re.sub(r'https?://\S+', '', text)
35
+ text = re.sub(r'@\w+', '', text)
36
+
37
+ for word in db.get_blocked_words():
38
+ if word and word in text:
39
+ return None
40
+
41
+ return '\n'.join(line for line in text.splitlines() if line.strip())
42
+
43
+ return text
44
+
45
+ def apply_tail(text, tail):
46
+ if tail:
47
+ return f"{text}\n{tail}" if text else tail
48
+ return text
49
+
50
+ async def notify_admins(text):
51
+ for admin_id in config.ADMINS:
52
+ try:
53
+ await bot_client.send_message(admin_id, f"⚠️ {text}")
54
+ except Exception as e:
55
+ logger.error(f"فشل إشعار الأدمن {admin_id}: {e}")
56
+
57
+ async def hydrate_peer(client, chat_id, label="peer"):
58
+ """يحاول تحميل الـ peer داخل جلسة Pyrogram حتى لا يظهر Peer id invalid."""
59
+ try:
60
+ chat = await client.get_chat(int(chat_id))
61
+ logger.info(f"✅ تم تحميل {label}: {getattr(chat, 'id', chat_id)}")
62
+ return chat
63
+ except Exception as first_error:
64
+ logger.warning(f"⚠️ فشل get_chat أول مرة لـ {label}={chat_id}: {first_error}. سيتم فحص الحوارات...")
65
+
66
+ try:
67
+ async for dialog in client.get_dialogs(limit=300):
68
+ if dialog.chat and int(dialog.chat.id) == int(chat_id):
69
+ logger.info(f"✅ تم العثور على {label} داخل الحوارات: {chat_id}")
70
+ return dialog.chat
71
+ except Exception as dialog_error:
72
+ logger.warning(f"⚠️ فشل فحص الحوارات لـ {label}: {dialog_error}")
73
+
74
+ chat = await client.get_chat(int(chat_id))
75
+ return chat
76
+
77
+ async def warm_middle_peer():
78
+ """تحميل القناة الوسيطة داخل جلسة الحساب والبوت قبل أي تحويل ميديا."""
79
+ global _middle_peer_warmed
80
+ if _middle_peer_warmed:
81
+ return True
82
+
83
+ ok = True
84
+ try:
85
+ await hydrate_peer(user_client, config.MIDDLE_CHANNEL, "القناة الوسيطة / user_client")
86
+ except Exception as e:
87
+ ok = False
88
+ logger.error(f"❌ user_client لا يستطيع الوصول للقناة الوسيطة {config.MIDDLE_CHANNEL}: {e}")
89
+
90
+ try:
91
+ await hydrate_peer(bot_client, config.MIDDLE_CHANNEL, "القناة الوسيطة / bot_client")
92
+ except Exception as e:
93
+ ok = False
94
+ logger.error(f"❌ bot_client لا يستطيع الوصول للقناة الوسيطة {config.MIDDLE_CHANNEL}: {e}")
95
+
96
+ _middle_peer_warmed = ok
97
+ return ok
98
+
99
+ async def forward_to_middle(source_chat_id, message_ids):
100
+ """يحّول رسالة أو مجموعة رسائل إلى القناة الوسيطة مع إعادة محاولة عند Peer id invalid."""
101
+ await warm_middle_peer()
102
+ try:
103
+ return await user_client.forward_messages(
104
+ chat_id=config.MIDDLE_CHANNEL,
105
+ from_chat_id=int(source_chat_id),
106
+ message_ids=message_ids
107
+ )
108
+ except Exception as e:
109
+ logger.warning(f"⚠️ فشل التوجيه للوسيطة، سيتم إعادة تحميل الـ peer والمحاولة مرة ثانية: {e}")
110
+ global _middle_peer_warmed
111
+ _middle_peer_warmed = False
112
+ await warm_middle_peer()
113
+ return await user_client.forward_messages(
114
+ chat_id=config.MIDDLE_CHANNEL,
115
+ from_chat_id=int(source_chat_id),
116
+ message_ids=message_ids
117
+ )
118
+
119
+ async def copy_middle_messages_to_target(target, middle_messages, caption=None):
120
+ """ينسخ رسائل الوسيطة لقناة النشر. يحاول الحفاظ على الألبوم قدر الإمكان."""
121
+ if not isinstance(middle_messages, (list, tuple)):
122
+ middle_messages = [middle_messages]
123
+
124
+ middle_messages = [m for m in middle_messages if m]
125
+ if not middle_messages:
126
+ return False
127
+
128
+ # إذا كانت مجموعة ميديا، نحاول copy_media_group حتى تبقى كألبوم.
129
+ if len(middle_messages) > 1:
130
+ try:
131
+ captions = None
132
+ if caption:
133
+ captions = [caption] + [""] * (len(middle_messages) - 1)
134
+ await bot_client.copy_media_group(
135
+ chat_id=int(target),
136
+ from_chat_id=config.MIDDLE_CHANNEL,
137
+ message_id=middle_messages[0].id,
138
+ captions=captions
139
+ )
140
+ logger.info(f"✅ نُشر ألبوم ميديا إلى {target} بعدد {len(middle_messages)}")
141
+ return True
142
+ except Exception as album_error:
143
+ logger.warning(f"⚠️ فشل copy_media_group إلى {target}، سيتم النسخ رسالة رسالة: {album_error}")
144
+
145
+ for idx, m in enumerate(middle_messages):
146
+ await bot_client.copy_message(
147
+ chat_id=int(target),
148
+ from_chat_id=config.MIDDLE_CHANNEL,
149
+ message_id=m.id,
150
+ caption=caption if idx == 0 and caption else None
151
+ )
152
+ await asyncio.sleep(0.25)
153
+
154
+ logger.info(f"✅ نُشر ميديا إلى {target} بعدد {len(middle_messages)}")
155
+ return True
156
+
157
+ async def safe_edit(callback, text, reply_markup=None):
158
+ try:
159
+ await callback.edit_message_text(text, reply_markup=reply_markup)
160
+ except MessageNotModified:
161
+ try:
162
+ await callback.answer()
163
+ except Exception:
164
+ pass
165
+ except Exception as e:
166
+ logger.error(f"فشل تعديل الرسالة: {e}")
167
+ try:
168
+ await callback.answer("حدث خطأ أثناء تحديث القائمة.", show_alert=True)
169
+ except Exception:
170
+ pass
171
+
172
+ async def resolve_chat_id(raw, prefer_user=True):
173
+ chat = await resolve_chat_info(raw, prefer_user=prefer_user)
174
+ return int(chat.id)
175
+
176
+
177
+ def normalize_chat_input(raw):
178
+ raw = str(raw).strip()
179
+ match = re.match(r'(?:https?://)?t\.me/([A-Za-z0-9_]+)', raw)
180
+ if match:
181
+ raw = "@" + match.group(1)
182
+ return raw
183
+
184
+
185
+ def split_bulk_lines(text):
186
+ items = []
187
+ for line in str(text or "").splitlines():
188
+ line = line.strip()
189
+ if not line:
190
+ continue
191
+ if "," in line and "t.me/" not in line:
192
+ items.extend([p.strip() for p in line.split(",") if p.strip()])
193
+ else:
194
+ items.append(line)
195
+ seen = set()
196
+ unique = []
197
+ for item in items:
198
+ key = normalize_chat_input(item).lower()
199
+ if key not in seen:
200
+ seen.add(key)
201
+ unique.append(item)
202
+ return unique
203
+
204
+
205
+ async def resolve_chat_info(raw, prefer_user=True):
206
+ raw = normalize_chat_input(raw)
207
+ value = int(raw) if re.fullmatch(r"-?\d+", raw) else raw
208
+ clients = [user_client, bot_client] if prefer_user else [bot_client, user_client]
209
+ last_error = None
210
+ for c in [x for x in clients if x]:
211
+ try:
212
+ return await c.get_chat(value)
213
+ except Exception as e:
214
+ last_error = e
215
+ raise last_error or ValueError("تعذر جلب معلومات القناة")
216
+
217
+
218
+ def chat_title(chat, fallback=""):
219
+ return getattr(chat, "title", None) or getattr(chat, "first_name", None) or getattr(chat, "username", None) or str(fallback)
220
+
221
+
222
+ def chat_username(chat):
223
+ return getattr(chat, "username", None) or ""
224
+
225
+
226
+ def chat_link_from_username(username):
227
+ return f"https://t.me/{username}" if username else ""
228
+
229
+
230
+ def chat_type_name(chat):
231
+ return str(getattr(chat, "type", "")).replace("ChatType.", "")
232
+
233
+
234
+ def chat_meta(chat, fallback=""):
235
+ username = chat_username(chat)
236
+ title = chat_title(chat, fallback)
237
+ return {
238
+ "name": title,
239
+ "title": title,
240
+ "username": username,
241
+ "link": chat_link_from_username(username),
242
+ "chat_type": chat_type_name(chat),
243
+ }
244
+
245
+
246
+ def entity_name(record_or_id, is_source=False):
247
+ if isinstance(record_or_id, dict):
248
+ return record_or_id.get("title") or record_or_id.get("name") or record_or_id.get("username") or str(record_or_id.get("id", ""))
249
+ if is_source and hasattr(db, "get_source_meta"):
250
+ return entity_name(db.get_source_meta(record_or_id))
251
+ return str(record_or_id)
252
+
253
+
254
+ def entity_details_line(item, is_source=False):
255
+ if is_source:
256
+ meta = db.get_source_meta(item) if not isinstance(item, dict) else item
257
+ item_id = meta.get("id", item)
258
+ else:
259
+ meta = item
260
+ item_id = item.get("id")
261
+ name = entity_name(meta)
262
+ username = meta.get("username") or ""
263
+ username_txt = f"@{username}" if username else "لا يوجد يوزر"
264
+ return f"• {name}\n {username_txt}\n ID: `{item_id}`"
265
+
266
+
267
+ async def show_public_sources_menu_from_message(message):
268
+ srcs = db.get_public_sources()
269
+ meta_list = db.get_all_public_sources_with_meta() if hasattr(db, "get_all_public_sources_with_meta") else [{"id": s, "name": str(s)} for s in srcs]
270
+ text = f"**المصادر العامة ({len(srcs)}):**\n"
271
+ text += "\n\n".join(entity_details_line(m, is_source=True) for m in meta_list) if srcs else "لا توجد."
272
+ buttons = [
273
+ [InlineKeyboardButton("➕ إضافة مصدر/مصادر", callback_data="add_public_src")],
274
+ [InlineKeyboardButton("🗑 حذف مصدر عام", callback_data="del_public_src")],
275
+ [InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")],
276
+ ]
277
+ await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons))
278
+
279
+
280
+ async def show_blocked_words_menu_from_message(message):
281
+ words = db.get_blocked_words()
282
+ text = "**الكلمات المحظورة:**\n" + (", ".join(words) if words else "لا توجد.")
283
+ buttons = [
284
+ [InlineKeyboardButton("➕ إضافة كلمة", callback_data="add_blocked_word")],
285
+ [InlineKeyboardButton("🗑 حذف كلمة", callback_data="del_blocked_word")],
286
+ [InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")],
287
+ ]
288
+ await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons))
289
+
290
+
291
+ async def show_special_sources_menu_from_message(message, ch_id):
292
+ ch = db.get_channel(ch_id)
293
+ if not ch:
294
+ await message.reply("❌ القناة غير موجودة.")
295
+ return
296
+ sources = ch.get("special_sources", [])
297
+ text = "**المصادر المخصصة:**\n"
298
+ text += "\n".join(f"• {entity_name(s, is_source=True)}\n ID: `{s}`" for s in sources) if sources else "لا توجد."
299
+ buttons = [
300
+ [InlineKeyboardButton("➕ إضافة", callback_data=f"addspecsrc_{ch_id}")],
301
+ [InlineKeyboardButton("🗑 حذف", callback_data=f"delspecsrc_{ch_id}")],
302
+ [InlineKeyboardButton("🔙 رجوع", callback_data=f"ch_{ch_id}")],
303
+ ]
304
+ await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons))
305
+
306
+
307
+ def format_bulk_report(title, results):
308
+ ok = [r for r in results if r[0] == "ok"]
309
+ exists = [r for r in results if r[0] == "exists"]
310
+ failed = [r for r in results if r[0] == "fail"]
311
+ lines = [title, "", f"✅ تمت الإضافة: {len(ok)}", f"⚠️ موجود مسبقاً: {len(exists)}", f"❌ فشل: {len(failed)}"]
312
+ if ok:
313
+ lines.append("\n**المضافة:**")
314
+ lines.extend([f"• {name}" for _, name, _ in ok[:30]])
315
+ if exists:
316
+ lines.append("\n**الموجودة مسبقاً:**")
317
+ lines.extend([f"• {name}" for _, name, _ in exists[:20]])
318
+ if failed:
319
+ lines.append("\n**الفاشلة:**")
320
+ lines.extend([f"• {raw}: {err}" for _, raw, err in failed[:20]])
321
+ return "\n".join(lines)
322
+
323
+ main_keyboard = InlineKeyboardMarkup([
324
+ [
325
+ InlineKeyboardButton("📢 إدارة قنوات النشر", callback_data="menu_channels"),
326
+ InlineKeyboardButton("🌐 إدارة المصادر العامة", callback_data="menu_public_src")
327
+ ],
328
+ [
329
+ InlineKeyboardButton("🚫 إدارة الكلمات المحظورة", callback_data="menu_blocked"),
330
+ InlineKeyboardButton("📊 إدارة الإحصائيات", callback_data="stats")
331
+ ],
332
+ [
333
+ InlineKeyboardButton("📥 تصدير الإعدادات", callback_data="export_data"),
334
+ InlineKeyboardButton("📤 استيراد الإعدادات", callback_data="import_data")
335
+ ]
336
+ ])
337
+
338
+ async def start(client, message):
339
+ user_id = message.from_user.id
340
+ user_states.pop(user_id, None)
341
+
342
+ logger.info(f"📥 /start من ID: {user_id}")
343
+
344
+ if not is_admin(user_id):
345
+ await message.reply(f"❌ غير مصرح. معرفك: `{user_id}`")
346
+ return
347
+
348
+ await message.reply("أهلاً بك في لوحة تحكم البوت:", reply_markup=main_keyboard)
349
+
350
+ async def export_callback(client, callback):
351
+ try:
352
+ data_str = db.export_data()
353
+
354
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False, encoding='utf-8') as tmp:
355
+ tmp.write(data_str)
356
+ tmp_path = tmp.name
357
+
358
+ await callback.message.reply_document(document=tmp_path, file_name=f"backup_{int(time.time())}.json")
359
+ os.unlink(tmp_path)
360
+ await callback.answer("تم إرسال ملف النسخة الاحتياطية.")
361
+ except Exception as e:
362
+ logger.error(f"فشل التصدير: {e}")
363
+ await callback.answer("فشل التصدير.", show_alert=True)
364
+
365
+ async def import_callback(client, callback):
366
+ user_states[callback.from_user.id] = {"state": "waiting_import"}
367
+ await safe_edit(callback, "أرسل ملف JSON الذي تريد استيراده:")
368
+
369
+ async def handle_import(client, message):
370
+ if not is_admin(message.from_user.id):
371
+ return
372
+
373
+ uid = message.from_user.id
374
+
375
+ if uid not in user_states or user_states[uid].get("state") != "waiting_import":
376
+ return
377
+
378
+ if not message.document:
379
+ await message.reply("❌ أرفق ملف JSON صحيح.")
380
+ return
381
+
382
+ try:
383
+ file_path = await message.download()
384
+ with open(file_path, "r", encoding="utf-8") as f:
385
+ data = f.read()
386
+
387
+ result = db.import_data(data)
388
+ if isinstance(result, dict):
389
+ report = (
390
+ "✅ تم استيراد الإعدادات بنجاح.\n\n"
391
+ f"• قنوات النشر: {result.get('channels', 0)}\n"
392
+ f"• المصادر العامة: {result.get('public_sources', 0)}\n"
393
+ f"• الكلمات المحظورة: {result.get('blocked_words', 0)}\n"
394
+ f"• آخر رسائل المصادر: {result.get('last_source_messages', 0)}"
395
+ )
396
+ else:
397
+ report = "✅ تم استيراد الإعدادات بنجاح."
398
+ await message.reply(report, reply_markup=main_keyboard)
399
+ except Exception as e:
400
+ await message.reply(f"❌ فشل الاستيراد: {e}")
401
+ finally:
402
+ user_states.pop(uid, None)
403
+
404
+ def channel_buttons(ch_id, ch):
405
+ paused_text = "⏸️ موقوفة" if ch.get('paused') else "✅ شغالة"
406
+
407
+ return InlineKeyboardMarkup([
408
+ [InlineKeyboardButton(f"⏯️ {paused_text}", callback_data=f"toggle_{ch_id}")],
409
+ [InlineKeyboardButton("📝 التوقيع", callback_data=f"tailmenu_{ch_id}")],
410
+ [InlineKeyboardButton("🔍 المصادر المخصصة", callback_data=f"specsrc_{ch_id}")],
411
+ [InlineKeyboardButton("🗑 حذف القناة", callback_data=f"delchannel_{ch_id}")],
412
+ [InlineKeyboardButton("🔙 رجوع", callback_data="menu_channels")]
413
+ ])
414
+
415
+ async def menu_channels(client, callback):
416
+ channels = db.get_all_channels()
417
+
418
+ if not channels:
419
+ text = "لا توجد قنوات."
420
+ buttons = [[InlineKeyboardButton("➕ إضافة قناة/قنوات", callback_data="add_channel")], [InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")]]
421
+ else:
422
+ text = f"**قنوات النشر ({len(channels)}):**\n"
423
+ buttons = []
424
+ for ch in channels:
425
+ paused = " ⏸️" if ch.get('paused') else ""
426
+ name = entity_name(ch)
427
+ username = ch.get("username") or ""
428
+ username_txt = f"@{username}" if username else "لا يوجد يوزر"
429
+ text += f"\n✅ {name}{paused}\n {username_txt}\n ID: `{ch['id']}`\n"
430
+ buttons.append([InlineKeyboardButton(f"{name} ⚙️", callback_data=f"ch_{ch['id']}")])
431
+ buttons.append([InlineKeyboardButton("➕ إضافة قناة/قنوات", callback_data="add_channel")])
432
+ buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")])
433
+ await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
434
+
435
+ async def show_channels_menu_from_message(message):
436
+ channels = db.get_all_channels()
437
+ if not channels:
438
+ text = "لا توجد قنوات."
439
+ buttons = [[InlineKeyboardButton("➕ إضافة قناة/قنوات", callback_data="add_channel")], [InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")]]
440
+ else:
441
+ text = f"**قنوات النشر ({len(channels)}):**\n"
442
+ buttons = []
443
+ for ch in channels:
444
+ paused = " ⏸️" if ch.get('paused') else ""
445
+ name = entity_name(ch)
446
+ username = ch.get("username") or ""
447
+ username_txt = f"@{username}" if username else "لا يوجد يوزر"
448
+ text += f"\n✅ {name}{paused}\n {username_txt}\n ID: `{ch['id']}`\n"
449
+ buttons.append([InlineKeyboardButton(f"{name} ⚙️", callback_data=f"ch_{ch['id']}")])
450
+ buttons.append([InlineKeyboardButton("➕ إضافة قناة/قنوات", callback_data="add_channel")])
451
+ buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")])
452
+ await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons))
453
+
454
+ async def channel_settings(client, callback):
455
+ ch_id = callback.data.split("_", 1)[1]
456
+ ch = db.get_channel(ch_id)
457
+ if not ch:
458
+ await callback.answer("غير موجودة.")
459
+ return
460
+ name = entity_name(ch)
461
+ username = ch.get("username") or ""
462
+ username_txt = f"@{username}" if username else "لا يوجد يوزر"
463
+ text = (
464
+ f"📢 **اسم القناة:**\n{name}\n\n"
465
+ f"👤 **اليوزر:** {username_txt}\n"
466
+ f"🆔 **ID:** `{ch_id}`\n"
467
+ f"📊 **الحالة:** {'⏸️ موقوفة' if ch.get('paused') else '✅ شغالة'}\n"
468
+ f"🧾 **عدد المنشورات:** {ch.get('posts_count', 0)}\n"
469
+ f"📝 **التوقيع:** {ch.get('tail') or 'لا يوجد'}"
470
+ )
471
+ await safe_edit(callback, text, channel_buttons(ch_id, ch))
472
+
473
+ async def add_channel_prompt(client, callback):
474
+ user_states.pop(callback.from_user.id, None)
475
+ user_states[callback.from_user.id] = {"state": "waiting_channel_id"}
476
+ await safe_edit(callback, "أرسل قناة واحدة أو عدة قنوات نشر.\nكل رابط/يوزر/ID بسطر مستقل:")
477
+
478
+ async def toggle_pause(client, callback):
479
+ ch_id = callback.data.split("_", 1)[1]
480
+ ch = db.get_channel(ch_id)
481
+
482
+ if not ch:
483
+ await callback.answer("غير موجودة.")
484
+ return
485
+
486
+ db.update_channel(ch_id, "paused", not ch.get("paused"))
487
+ await callback.answer("تم التحديث.")
488
+ await channel_settings(client, callback)
489
+
490
+ async def delete_channel_prompt(client, callback):
491
+ channels = db.get_all_channels()
492
+ if not channels:
493
+ await callback.answer("لا توجد قنوات.")
494
+ return
495
+ buttons = []
496
+ for ch in channels:
497
+ name = entity_name(ch)
498
+ buttons.append([InlineKeyboardButton(f"🗑 حذف {name}", callback_data=f"confirm_del_{ch['id']}")])
499
+ buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="menu_channels")])
500
+ await safe_edit(callback, "اختر القناة التي تريد حذفها:", InlineKeyboardMarkup(buttons))
501
+
502
+ async def confirm_delete_channel(client, callback):
503
+ ch_id = callback.data.split("_", 2)[2]
504
+ db.delete_channel(ch_id)
505
+ await callback.answer("تم الحذف.")
506
+ await menu_channels(client, callback)
507
+
508
+ async def tail_menu(client, callback):
509
+ ch_id = callback.data.split("_", 1)[1]
510
+ ch = db.get_channel(ch_id)
511
+
512
+ if not ch:
513
+ await callback.answer("غير موجودة.")
514
+ return
515
+
516
+ current = ch.get("tail", "")
517
+ text = f"التوقيع الحالي:\n`{current}`" if current else "لا يوجد توقيع."
518
+
519
+ buttons = [
520
+ [InlineKeyboardButton("✏️ تعديل/إضافة", callback_data=f"edittail_{ch_id}")],
521
+ [InlineKeyboardButton("🗑 حذف التوقيع", callback_data=f"deltail_{ch_id}")],
522
+ [InlineKeyboardButton("🔙 رجوع", callback_data=f"ch_{ch_id}")]
523
+ ]
524
+
525
+ await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
526
+
527
+ async def edit_tail_prompt(client, callback):
528
+ ch_id = callback.data.split("_", 1)[1]
529
+ user_states.pop(callback.from_user.id, None)
530
+ user_states[callback.from_user.id] = {"state": "waiting_tail", "ch_id": ch_id}
531
+ await safe_edit(callback, "أرسل نص التوقيع الجديد:")
532
+
533
+ async def delete_tail(client, callback):
534
+ ch_id = callback.data.split("_", 1)[1]
535
+ db.update_channel(ch_id, "tail", "")
536
+ await callback.answer("تم حذف التوقيع.")
537
+ await tail_menu(client, callback)
538
+
539
+ async def menu_public_sources(client, callback):
540
+ srcs = db.get_public_sources()
541
+ meta_list = db.get_all_public_sources_with_meta() if hasattr(db, "get_all_public_sources_with_meta") else [{"id": s, "name": str(s)} for s in srcs]
542
+ text = f"**المصادر العامة ({len(srcs)}):**\n"
543
+ text += "\n\n".join(entity_details_line(m, is_source=True) for m in meta_list) if srcs else "لا توجد."
544
+ buttons = [[InlineKeyboardButton("➕ إضافة مصدر/مصادر", callback_data="add_public_src")], [InlineKeyboardButton("🗑 حذف مصدر عام", callback_data="del_public_src")], [InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")]]
545
+ await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
546
+
547
+ async def add_public_src_prompt(client, callback):
548
+ user_states.pop(callback.from_user.id, None)
549
+ user_states[callback.from_user.id] = {"state": "waiting_public_source"}
550
+ await safe_edit(callback, "أرسل مصدر واحد أو عدة مصادر عامة.\nكل رابط/يوزر/ID بسطر مستقل:")
551
+
552
+ async def del_public_src_prompt(client, callback):
553
+ srcs = db.get_public_sources()
554
+ if not srcs:
555
+ await callback.answer("لا توجد مصادر.")
556
+ return
557
+ buttons = []
558
+ for idx, src in enumerate(srcs):
559
+ name = entity_name(src, is_source=True)
560
+ buttons.append([InlineKeyboardButton(f"🗑 حذف {name}", callback_data=f"del_pub_idx_{idx}")])
561
+ buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="menu_public_src")])
562
+ await safe_edit(callback, "اختر المصدر للحذف:", InlineKeyboardMarkup(buttons))
563
+
564
+ async def confirm_del_public_src(client, callback):
565
+ idx = int(callback.data.split("_")[-1])
566
+ srcs = db.get_public_sources()
567
+
568
+ if idx < 0 or idx >= len(srcs):
569
+ await callback.answer("المصدر غير موجود.")
570
+ return
571
+
572
+ db.remove_public_source(srcs[idx])
573
+ await callback.answer("تم الحذف.")
574
+ await menu_public_sources(client, callback)
575
+
576
+ async def menu_blocked_words(client, callback):
577
+ words = db.get_blocked_words()
578
+
579
+ text = "**الكلمات المحظورة:**\n"
580
+ text += ", ".join(words) if words else "لا توجد."
581
+
582
+ buttons = [
583
+ [InlineKeyboardButton("➕ إضافة كلمة", callback_data="add_blocked_word")],
584
+ [InlineKeyboardButton("🗑 حذف كلمة", callback_data="del_blocked_word")],
585
+ [InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")]
586
+ ]
587
+
588
+ await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
589
+
590
+ async def add_blocked_word_prompt(client, callback):
591
+ user_states.pop(callback.from_user.id, None)
592
+ user_states[callback.from_user.id] = {"state": "waiting_blocked_word"}
593
+ await safe_edit(callback, "أرسل الكلمة المحظورة:")
594
+
595
+ async def del_blocked_word_prompt(client, callback):
596
+ words = db.get_blocked_words()
597
+
598
+ if not words:
599
+ await callback.answer("لا توجد.")
600
+ return
601
+
602
+ buttons = []
603
+
604
+ for idx, word in enumerate(words):
605
+ buttons.append([InlineKeyboardButton(f"حذف {word}", callback_data=f"delword_idx_{idx}")])
606
+
607
+ buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="menu_blocked")])
608
+ await safe_edit(callback, "اختر الكلمة:", InlineKeyboardMarkup(buttons))
609
+
610
+ async def confirm_del_blocked_word(client, callback):
611
+ idx = int(callback.data.split("_")[-1])
612
+ words = db.get_blocked_words()
613
+
614
+ if idx < 0 or idx >= len(words):
615
+ await callback.answer("الكلمة غير موجودة.")
616
+ return
617
+
618
+ db.remove_blocked_word(words[idx])
619
+ await callback.answer("تم الحذف.")
620
+ await menu_blocked_words(client, callback)
621
+
622
+ async def manage_special_sources(client, callback):
623
+ ch_id = callback.data.split("_", 1)[1]
624
+ ch = db.get_channel(ch_id)
625
+ if not ch:
626
+ await callback.answer("غير موجودة.")
627
+ return
628
+ sources = ch.get("special_sources", [])
629
+ text = "**المصادر المخصصة:**\n"
630
+ text += "\n".join(f"• {entity_name(s, is_source=True)}\n ID: `{s}`" for s in sources) if sources else "لا توجد."
631
+ buttons = [[InlineKeyboardButton("➕ إضافة", callback_data=f"addspecsrc_{ch_id}")], [InlineKeyboardButton("🗑 حذف", callback_data=f"delspecsrc_{ch_id}")], [InlineKeyboardButton("🔙 رجوع", callback_data=f"ch_{ch_id}")]]
632
+ await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
633
+
634
+ async def add_special_source_prompt(client, callback):
635
+ ch_id = callback.data.split("_", 1)[1]
636
+ user_states.pop(callback.from_user.id, None)
637
+ user_states[callback.from_user.id] = {
638
+ "state": "waiting_special_source",
639
+ "ch_id": ch_id
640
+ }
641
+ await safe_edit(callback, "أرسل رابط أو يوزر أو ID المصدر المخصص:")
642
+
643
+ async def delete_special_source_prompt(client, callback):
644
+ ch_id = callback.data.split("_", 1)[1]
645
+ ch = db.get_channel(ch_id)
646
+ if not ch:
647
+ await callback.answer("غير موجودة.")
648
+ return
649
+ sources = ch.get("special_sources", [])
650
+ if not sources:
651
+ await callback.answer("لا توجد مصادر.")
652
+ return
653
+ buttons = []
654
+ for idx, src in enumerate(sources):
655
+ name = entity_name(src, is_source=True)
656
+ buttons.append([InlineKeyboardButton(f"🗑 حذف {name}", callback_data=f"confdelspec_{ch_id}_{idx}")])
657
+ buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data=f"specsrc_{ch_id}")])
658
+ await safe_edit(callback, "اختر المصدر لحذفه:", InlineKeyboardMarkup(buttons))
659
+
660
+ async def confirm_delete_special_source(client, callback):
661
+ parts = callback.data.split("_")
662
+ ch_id = parts[1]
663
+ idx = int(parts[2])
664
+
665
+ ch = db.get_channel(ch_id)
666
+
667
+ if not ch:
668
+ await callback.answer("غير موجودة.")
669
+ return
670
+
671
+ sources = ch.get("special_sources", [])
672
+
673
+ if idx < 0 or idx >= len(sources):
674
+ await callback.answer("المصدر غير موجود.")
675
+ return
676
+
677
+ sources.pop(idx)
678
+ db.update_channel(ch_id, "special_sources", sources)
679
+
680
+ await callback.answer("تم الحذف.")
681
+ await manage_special_sources(client, callback)
682
+
683
+ async def show_stats(client, callback):
684
+ channels = db.get_all_channels()
685
+ total_posts = sum(ch.get("posts_count", 0) for ch in channels)
686
+ pub_src = len(db.get_public_sources())
687
+ words = len(db.get_blocked_words())
688
+
689
+ text = "📊 **الإحصائيات:**\n\n"
690
+ text += f"• إجمالي المنشورات: **{total_posts}**\n"
691
+ text += f"• قنوات النشر: {len(channels)}\n"
692
+ text += f"• المصادر العامة: {pub_src}\n"
693
+ text += f"• الكلمات المحظورة: {words}\n\n"
694
+
695
+ if channels:
696
+ text += "**تفصيل المنشورات:**\n"
697
+ for ch in channels:
698
+ text += f"`{ch['id']}`: {ch.get('posts_count', 0)}\n"
699
+
700
+ await safe_edit(
701
+ callback,
702
+ text,
703
+ InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")]])
704
+ )
705
+
706
+ async def handle_text_input(client, message):
707
+ if not is_admin(message.from_user.id):
708
+ return
709
+ uid = message.from_user.id
710
+ if uid not in user_states:
711
+ return
712
+ state = user_states[uid].get("state")
713
+ text = message.text.strip()
714
+ try:
715
+ if state == "waiting_channel_id":
716
+ results = []
717
+ for raw in split_bulk_lines(text):
718
+ try:
719
+ chat = await resolve_chat_info(raw, prefer_user=False)
720
+ meta = chat_meta(chat, raw)
721
+ created = db.add_channel(chat.id, **meta)
722
+ results.append(("ok" if created else "exists", meta["title"], raw))
723
+ except Exception as e:
724
+ results.append(("fail", raw, str(e)))
725
+ await message.reply(format_bulk_report("📢 نتيجة إضافة قنوات النشر", results))
726
+ await show_channels_menu_from_message(message)
727
+ elif state == "waiting_tail":
728
+ ch_id = user_states[uid]["ch_id"]
729
+ db.update_channel(ch_id, "tail", text)
730
+ await message.reply("✅ تم حفظ التوقيع.")
731
+ ch = db.get_channel(ch_id)
732
+ if ch:
733
+ await message.reply(f"إعدادات القناة: {entity_name(ch)}", reply_markup=channel_buttons(ch_id, ch))
734
+ elif state == "waiting_public_source":
735
+ results = []
736
+ for raw in split_bulk_lines(text):
737
+ try:
738
+ chat = await resolve_chat_info(raw, prefer_user=True)
739
+ meta = chat_meta(chat, raw)
740
+ created = db.add_public_source(chat.id, **meta)
741
+ results.append(("ok" if created else "exists", meta["title"], raw))
742
+ except Exception as e:
743
+ results.append(("fail", raw, str(e)))
744
+ await message.reply(format_bulk_report("🌐 نتيجة إضافة المصادر العامة", results))
745
+ await show_public_sources_menu_from_message(message)
746
+ elif state == "waiting_blocked_word":
747
+ added = 0
748
+ exists = 0
749
+ for word in split_bulk_lines(text):
750
+ if db.add_blocked_word(word):
751
+ added += 1
752
+ else:
753
+ exists += 1
754
+ await message.reply(f"✅ تمت إضافة {added} كلمة.\n⚠️ موجودة مسبقاً/فارغة: {exists}")
755
+ await show_blocked_words_menu_from_message(message)
756
+ elif state == "waiting_special_source":
757
+ ch_id = user_states[uid]["ch_id"]
758
+ ch = db.get_channel(ch_id)
759
+ if not ch:
760
+ await message.reply("❌ القناة غير موجودة.")
761
+ return
762
+ sources = ch.get("special_sources", [])
763
+ results = []
764
+ for raw in split_bulk_lines(text):
765
+ try:
766
+ chat = await resolve_chat_info(raw, prefer_user=True)
767
+ meta = chat_meta(chat, raw)
768
+ db.update_source_meta(chat.id, **meta) if hasattr(db, "update_source_meta") else None
769
+ if int(chat.id) not in [int(x) for x in sources]:
770
+ sources.append(int(chat.id))
771
+ results.append(("ok", meta["title"], raw))
772
+ else:
773
+ results.append(("exists", meta["title"], raw))
774
+ except Exception as e:
775
+ results.append(("fail", raw, str(e)))
776
+ db.update_channel(ch_id, "special_sources", sources)
777
+ await message.reply(format_bulk_report("🔍 نتيجة إضافة المصادر المخصصة", results))
778
+ await show_special_sources_menu_from_message(message, ch_id)
779
+ except Exception as e:
780
+ logger.error(f"خطأ في إدخال المستخدم: {e}")
781
+ await message.reply(f"❌ فشل التنفيذ: {e}")
782
+ finally:
783
+ user_states.pop(uid, None)
784
+
785
+ def _to_int_set(values):
786
+ result = set()
787
+ for value in values or []:
788
+ try:
789
+ result.add(int(value))
790
+ except Exception:
791
+ pass
792
+ return result
793
+
794
+
795
+ def get_targets_for_source(source_id):
796
+ """يرجع قنوات النشر التي يجب أن تستقبل منشوراً من هذا المصدر."""
797
+ source_id = int(source_id)
798
+ all_channels = db.get_all_channels()
799
+ public_sources = _to_int_set(db.get_public_sources())
800
+ target_ids = set()
801
+
802
+ logger.info(f"🧭 فحص المصدر {source_id}")
803
+ logger.info(f"🧭 المصادر العامة المخزونة: {sorted(public_sources)}")
804
+ logger.info(f"🧭 عدد قنوات النشر: {len(all_channels)}")
805
+
806
+ if source_id in public_sources:
807
+ logger.info("🟢 المصدر مطابق للمصادر العامة")
808
+ for ch in all_channels:
809
+ specials = ch.get("special_sources") or []
810
+ paused = bool(ch.get("paused"))
811
+ logger.info(f"🧭 قناة {ch.get('id')} | paused={paused} | special_sources={specials}")
812
+ if not specials and not paused:
813
+ try:
814
+ target_ids.add(int(ch["id"]))
815
+ except Exception as e:
816
+ logger.error(f"تعذر تحويل قناة النشر إلى رقم: {ch.get('id')} | {e}")
817
+ else:
818
+ logger.info("🟡 المصدر غير موجود ضمن المصادر العامة")
819
+
820
+ for ch in all_channels:
821
+ paused = bool(ch.get("paused"))
822
+ specials = _to_int_set(ch.get("special_sources") or [])
823
+ if source_id in specials and not paused:
824
+ try:
825
+ target_ids.add(int(ch["id"]))
826
+ logger.info(f"🟢 المصدر مطابق لمصدر مخصص للقناة {ch.get('id')}")
827
+ except Exception as e:
828
+ logger.error(f"تعذر تحويل قناة النشر إلى رقم: {ch.get('id')} | {e}")
829
+
830
+ logger.info(f"🎯 القنوات المستهدفة: {target_ids}")
831
+ return target_ids
832
+
833
+
834
+ def blocked_word_in_text(text):
835
+ if not text:
836
+ return None
837
+ for word in db.get_blocked_words():
838
+ if word and word in text:
839
+ return word
840
+ return None
841
+
842
+
843
+ def unsupported_media_reason(message):
844
+ """يرجع سبب التجاهل إذا كان المنشور يحتوي ملصق أو صورة متحركة/GIF."""
845
+ if getattr(message, "sticker", None):
846
+ return "ملصق"
847
+ if getattr(message, "animation", None):
848
+ return "صورة متحركة / GIF"
849
+ return None
850
+
851
+
852
+ def mark_middle_auto_forward_window(seconds=4):
853
+ """يمنع middle_channel_handler من نشر النسخة التي وصلت للوسيطة تلقائياً حتى لا تتكرر."""
854
+ global _middle_auto_ignore_until
855
+ _middle_auto_ignore_until = max(_middle_auto_ignore_until, time.monotonic() + seconds)
856
+
857
+
858
+ def is_middle_auto_forward_window_active():
859
+ return time.monotonic() <= _middle_auto_ignore_until
860
+
861
+
862
+ async def publish_source_message(message, source_id, origin="updates"):
863
+ raw_text = message.text or message.caption or ""
864
+ source_id = int(source_id)
865
+
866
+ logger.info(f"📨 [{origin}] رسالة من {source_id} | message_id={message.id} | نص: {str(raw_text)[:80]}...")
867
+
868
+ target_ids = get_targets_for_source(source_id)
869
+ if not target_ids:
870
+ logger.info("🟡 لا توجد قنوات مستهدفة لهذا المصدر، تم اعتبار المنشور معالجاً حتى لا يتكرر.")
871
+ return True
872
+
873
+ bad_word = blocked_word_in_text(raw_text)
874
+ if bad_word:
875
+ logger.info(f"⛔ منشور مرفوض بسبب كلمة محظورة: {bad_word}")
876
+ return True
877
+
878
+ unsupported_reason = unsupported_media_reason(message)
879
+ if unsupported_reason:
880
+ logger.info(f"⛔ تم تجاهل المنشور لأنه يحتوي {unsupported_reason}")
881
+ return True
882
+
883
+ if message.media:
884
+ try:
885
+ mark_middle_auto_forward_window()
886
+ fwd = await forward_to_middle(message.chat.id, message.id)
887
+ mark_middle_auto_forward_window()
888
+ await asyncio.sleep(0.5)
889
+ middle_messages = fwd if isinstance(fwd, list) else [fwd]
890
+ middle_messages = [m for m in middle_messages if m]
891
+ logger.info(f"✅ تم تمرير منشور ميديا إلى الوسيطة | ids={[m.id for m in middle_messages]}")
892
+ except Exception as e:
893
+ logger.error(f"فشل التوجيه للوسيطة من المصدر {source_id}: {e}")
894
+ await notify_admins(f"فشل توجيه رسالة من {source_id} إلى الوسيطة: {e}")
895
+ return False
896
+
897
+ any_success = False
898
+ for target in target_ids:
899
+ try:
900
+ ch = db.get_channel(target)
901
+ if not ch:
902
+ logger.warning(f"القناة {target} غير موجودة في قاعدة البيانات")
903
+ continue
904
+
905
+ cleaned = clean_text(raw_text)
906
+ if cleaned is None:
907
+ logger.info("⛔ النص بعد التنظيف مرفوض لكلمة محظورة")
908
+ continue
909
+
910
+ final = apply_tail(cleaned, ch.get("tail", ""))
911
+ ok = await copy_middle_messages_to_target(target, middle_messages, final if final else None)
912
+ if ok:
913
+ db.increment_post_count(target)
914
+ any_success = True
915
+ await asyncio.sleep(0.5)
916
+
917
+ except Exception as e:
918
+ logger.error(f"نشر فاشل إلى {target}: {e}")
919
+ await notify_admins(f"فشل النشر إلى {target}: {e}")
920
+
921
+ return any_success
922
+
923
+ else:
924
+ any_success = False
925
+ for target in target_ids:
926
+ try:
927
+ ch = db.get_channel(target)
928
+ if not ch:
929
+ logger.warning(f"القناة {target} غير موجودة في قاعدة البيانات")
930
+ continue
931
+
932
+ cleaned = clean_text(raw_text)
933
+ if cleaned is None:
934
+ logger.info("⛔ النص بعد التنظيف مرفوض لكلمة محظورة")
935
+ continue
936
+
937
+ final = apply_tail(cleaned, ch.get("tail", ""))
938
+
939
+ if final:
940
+ await bot_client.send_message(target, final)
941
+ else:
942
+ logger.info("🟡 منشور نصي فارغ بعد التنظيف؛ لن يتم إرساله.")
943
+ continue
944
+
945
+ db.increment_post_count(target)
946
+ any_success = True
947
+ logger.info(f"✅ نُشر نص إلى {target}")
948
+ await asyncio.sleep(0.5)
949
+
950
+ except Exception as e:
951
+ logger.error(f"إرسال فاشل إلى {target}: {e}")
952
+ await notify_admins(f"فشل الإرسال إلى {target}: {e}")
953
+
954
+ return any_success
955
+
956
+
957
+ async def publish_source_album(messages, source_id, origin="polling"):
958
+ """ينشر مجموعة ميديا من المصدر إلى الوسيطة ثم إلى قنوات النشر بنفس ترتيب الرسائل."""
959
+ if not messages:
960
+ return True
961
+
962
+ messages = sorted(messages, key=lambda m: m.id)
963
+ first = messages[0]
964
+ raw_text = first.caption or first.text or ""
965
+ source_id = int(source_id)
966
+ ids = [m.id for m in messages]
967
+
968
+ logger.info(f"📨 [{origin}] ألبوم من {source_id} | message_ids={ids} | نص: {str(raw_text)[:80]}...")
969
+
970
+ target_ids = get_targets_for_source(source_id)
971
+ if not target_ids:
972
+ logger.info("🟡 لا توجد قنوات مستهدفة لهذا الألبوم، تم اعتباره معالجاً حتى لا يتكرر.")
973
+ return True
974
+
975
+ bad_word = blocked_word_in_text(raw_text)
976
+ if bad_word:
977
+ logger.info(f"⛔ ألبوم مرفوض بسبب كلمة محظورة: {bad_word}")
978
+ return True
979
+
980
+ for item in messages:
981
+ unsupported_reason = unsupported_media_reason(item)
982
+ if unsupported_reason:
983
+ logger.info(f"⛔ تم تجاهل الألبوم لأنه يحتوي {unsupported_reason}")
984
+ return True
985
+
986
+ try:
987
+ mark_middle_auto_forward_window()
988
+ fwd = await forward_to_middle(source_id, ids)
989
+ mark_middle_auto_forward_window()
990
+ await asyncio.sleep(0.8)
991
+ middle_messages = fwd if isinstance(fwd, list) else [fwd]
992
+ middle_messages = sorted([m for m in middle_messages if m], key=lambda m: m.id)
993
+ logger.info(f"✅ تم تمرير الألبوم إلى الوسيطة | middle_ids={[m.id for m in middle_messages]}")
994
+ except Exception as e:
995
+ logger.error(f"فشل توجيه الألبوم للوسيطة من المصدر {source_id}: {e}")
996
+ await notify_admins(f"فشل توجيه ألبوم من {source_id} إلى الوسيطة: {e}")
997
+ return False
998
+
999
+ any_success = False
1000
+ for target in target_ids:
1001
+ try:
1002
+ ch = db.get_channel(target)
1003
+ if not ch:
1004
+ logger.warning(f"القناة {target} غير موجودة في قاعدة البيانات")
1005
+ continue
1006
+
1007
+ cleaned = clean_text(raw_text)
1008
+ if cleaned is None:
1009
+ logger.info("⛔ النص بعد التنظيف مرفوض لكلمة محظورة")
1010
+ continue
1011
+
1012
+ final = apply_tail(cleaned, ch.get("tail", ""))
1013
+ ok = await copy_middle_messages_to_target(target, middle_messages, final if final else None)
1014
+ if ok:
1015
+ db.increment_post_count(target)
1016
+ any_success = True
1017
+ await asyncio.sleep(0.5)
1018
+
1019
+ except Exception as e:
1020
+ logger.error(f"نشر الألبوم فاشل إلى {target}: {e}")
1021
+ await notify_admins(f"فشل نشر ألبوم إلى {target}: {e}")
1022
+
1023
+ return any_success
1024
+
1025
+
1026
+ async def user_message_handler(client, message):
1027
+ logger.info(f"🔥 user_client استلم تحديث | chat={getattr(message.chat, 'id', None)} | type={getattr(message.chat, 'type', None)}")
1028
+
1029
+ if not message.chat or message.chat.type not in ("channel", "supergroup"):
1030
+ return
1031
+
1032
+ await publish_source_message(message, int(message.chat.id), origin="updates")
1033
+
1034
+
1035
+ async def poll_public_sources_loop():
1036
+ """يفحص المصادر العامة دورياً، لأن Updates لا تصل أحياناً على Hugging Face."""
1037
+ await asyncio.sleep(8)
1038
+ logger.info("🔁 بدأ نظام الفحص الدوري للمصادر العامة Polling")
1039
+
1040
+ while True:
1041
+ try:
1042
+ public_sources = db.get_public_sources()
1043
+ if not public_sources:
1044
+ logger.info("🔁 لا توجد مصادر عامة للفحص.")
1045
+ await asyncio.sleep(25)
1046
+ continue
1047
+
1048
+ logger.info(f"🔁 فحص المصادر العامة: {public_sources}")
1049
+
1050
+ for source in public_sources:
1051
+ try:
1052
+ source_id = int(source)
1053
+ except Exception:
1054
+ logger.warning(f"مصدر غير رقمي تم تجاهله: {source}")
1055
+ continue
1056
+
1057
+ try:
1058
+ last_seen = db.get_last_source_message(source_id)
1059
+ messages = []
1060
+
1061
+ async for msg in user_client.get_chat_history(source_id, limit=8):
1062
+ if not msg or not getattr(msg, "id", None):
1063
+ continue
1064
+ messages.append(msg)
1065
+
1066
+ if not messages:
1067
+ logger.info(f"🔁 المصدر {source_id}: لا توجد رسائل مقروءة.")
1068
+ continue
1069
+
1070
+ newest_id = max(m.id for m in messages)
1071
+
1072
+ if last_seen is None:
1073
+ db.set_last_source_message(source_id, newest_id)
1074
+ logger.info(f"🔁 المصدر {source_id}: أول تشغيل، تم حفظ آخر رسالة {newest_id} بدون نشر القديم.")
1075
+ continue
1076
+
1077
+ new_messages = [m for m in messages if m.id > int(last_seen)]
1078
+ new_messages.sort(key=lambda m: m.id)
1079
+
1080
+ if not new_messages:
1081
+ logger.info(f"🔁 المصدر {source_id}: لا توجد منشورات جديدة. last_seen={last_seen}")
1082
+ continue
1083
+
1084
+ logger.info(f"🔁 المصدر {source_id}: تم العثور على {len(new_messages)} منشور جديد.")
1085
+
1086
+ processed_ids = set()
1087
+ i = 0
1088
+ while i < len(new_messages):
1089
+ msg = new_messages[i]
1090
+ if msg.id in processed_ids:
1091
+ i += 1
1092
+ continue
1093
+
1094
+ media_group_id = getattr(msg, "media_group_id", None)
1095
+ if media_group_id:
1096
+ group = [m for m in new_messages if getattr(m, "media_group_id", None) == media_group_id]
1097
+ group.sort(key=lambda m: m.id)
1098
+ ok = await publish_source_album(group, source_id, origin="polling")
1099
+ if ok:
1100
+ for gm in group:
1101
+ processed_ids.add(gm.id)
1102
+ db.set_last_source_message(source_id, max(gm.id for gm in group))
1103
+ else:
1104
+ logger.warning(f"⚠️ لم يتم تحديث last_seen للألبوم {media_group_id} حتى يعاد المحاولة لاحقاً")
1105
+ await asyncio.sleep(1)
1106
+ else:
1107
+ ok = await publish_source_message(msg, source_id, origin="polling")
1108
+ if ok:
1109
+ processed_ids.add(msg.id)
1110
+ db.set_last_source_message(source_id, msg.id)
1111
+ else:
1112
+ logger.warning(f"⚠️ لم يتم تحديث last_seen للرسالة {msg.id} حتى تعاد المحاولة لاحقاً")
1113
+ await asyncio.sleep(1)
1114
+ i += 1
1115
+
1116
+ except Exception as e:
1117
+ logger.exception(f"خطأ أثناء فحص المصدر {source}: {e}")
1118
+ await notify_admins(f"فشل فحص المصدر {source}: {e}")
1119
+
1120
+ await asyncio.sleep(25)
1121
+
1122
+ except Exception as e:
1123
+ logger.exception(f"خطأ عام في حلقة Polling: {e}")
1124
+ await asyncio.sleep(30)
1125
+
1126
+
1127
+ async def middle_channel_handler(client, message):
1128
+ if int(message.chat.id) != int(config.MIDDLE_CHANNEL):
1129
+ return
1130
+
1131
+ if is_middle_auto_forward_window_active():
1132
+ logger.info(f"🟡 تم تجاهل رسالة وسيطة تلقائية لمنع التكرار | message_id={message.id}")
1133
+ return
1134
+
1135
+ logger.info("📥 رسالة في الوسيطة، جارٍ النشر...")
1136
+
1137
+ all_channels = db.get_all_channels()
1138
+ raw_text = message.text or message.caption or ""
1139
+
1140
+ unsupported_reason = unsupported_media_reason(message)
1141
+ if unsupported_reason:
1142
+ logger.info(f"⛔ تم تجاهل رسالة الوسيطة لأنها تحتوي {unsupported_reason}")
1143
+ return
1144
+
1145
+ if raw_text and any(w in raw_text for w in db.get_blocked_words()):
1146
+ logger.info("⛔ كلمة محظورة - لم تُنشر")
1147
+ return
1148
+
1149
+ for ch in all_channels:
1150
+ if ch.get("paused"):
1151
+ continue
1152
+
1153
+ target = int(ch["id"])
1154
+
1155
+ try:
1156
+ cleaned = clean_text(raw_text) if raw_text else ""
1157
+ if cleaned is None:
1158
+ continue
1159
+
1160
+ final = apply_tail(cleaned, ch.get("tail", ""))
1161
+
1162
+ if message.media:
1163
+ await bot_client.copy_message(
1164
+ chat_id=target,
1165
+ from_chat_id=config.MIDDLE_CHANNEL,
1166
+ message_id=message.id,
1167
+ caption=final if final else None
1168
+ )
1169
+ else:
1170
+ await bot_client.send_message(target, final if final else ".")
1171
+
1172
+ db.increment_post_count(target)
1173
+ logger.info(f"✅ نُشر من الوسيطة إلى {target}")
1174
+ await asyncio.sleep(0.5)
1175
+
1176
+ except Exception as e:
1177
+ logger.error(f"نشر فاشل من الوسيطة إلى {target}: {e}")
1178
+ await notify_admins(f"فشل النشر من الوسيطة إلى {target}: {e}")
1179
+
1180
+ def register_bot_handlers(app: Client):
1181
+ app.add_handler(MessageHandler(start, filters.command("start")))
1182
+ app.add_handler(MessageHandler(handle_import, filters.document))
1183
+
1184
+ async def callback_dispatcher(client, callback):
1185
+ data = callback.data
1186
+
1187
+ if data == "main_menu":
1188
+ await safe_edit(callback, "القائمة الرئيسية:", main_keyboard)
1189
+ elif data == "menu_channels":
1190
+ await menu_channels(client, callback)
1191
+ elif data.startswith("ch_"):
1192
+ await channel_settings(client, callback)
1193
+ elif data == "add_channel":
1194
+ await add_channel_prompt(client, callback)
1195
+ elif data.startswith("toggle_"):
1196
+ await toggle_pause(client, callback)
1197
+ elif data.startswith("delchannel_"):
1198
+ await delete_channel_prompt(client, callback)
1199
+ elif data.startswith("confirm_del_"):
1200
+ await confirm_delete_channel(client, callback)
1201
+ elif data.startswith("tailmenu_"):
1202
+ await tail_menu(client, callback)
1203
+ elif data.startswith("edittail_"):
1204
+ await edit_tail_prompt(client, callback)
1205
+ elif data.startswith("deltail_"):
1206
+ await delete_tail(client, callback)
1207
+ elif data == "menu_public_src":
1208
+ await menu_public_sources(client, callback)
1209
+ elif data == "add_public_src":
1210
+ await add_public_src_prompt(client, callback)
1211
+ elif data == "del_public_src":
1212
+ await del_public_src_prompt(client, callback)
1213
+ elif data.startswith("del_pub_idx_"):
1214
+ await confirm_del_public_src(client, callback)
1215
+ elif data == "menu_blocked":
1216
+ await menu_blocked_words(client, callback)
1217
+ elif data == "add_blocked_word":
1218
+ await add_blocked_word_prompt(client, callback)
1219
+ elif data == "del_blocked_word":
1220
+ await del_blocked_word_prompt(client, callback)
1221
+ elif data.startswith("delword_idx_"):
1222
+ await confirm_del_blocked_word(client, callback)
1223
+ elif data.startswith("specsrc_"):
1224
+ await manage_special_sources(client, callback)
1225
+ elif data.startswith("addspecsrc_"):
1226
+ await add_special_source_prompt(client, callback)
1227
+ elif data.startswith("delspecsrc_"):
1228
+ await delete_special_source_prompt(client, callback)
1229
+ elif data.startswith("confdelspec_"):
1230
+ await confirm_delete_special_source(client, callback)
1231
+ elif data == "stats":
1232
+ await show_stats(client, callback)
1233
+ elif data == "export_data":
1234
+ await export_callback(client, callback)
1235
+ elif data == "import_data":
1236
+ await import_callback(client, callback)
1237
+ else:
1238
+ await callback.answer("غير معروف.")
1239
+
1240
+ app.add_handler(CallbackQueryHandler(callback_dispatcher))
1241
+ app.add_handler(MessageHandler(handle_text_input, filters.text & filters.private))
1242
+
1243
+ def register_user_handlers(app: Client):
1244
+ # نلتقط كل رسائل حساب المستخدم ثم نفلتر داخل user_message_handler
1245
+ # هذا يساعدنا نعرف هل SESSION_STRING يلتقط المصادر العامة أو لا
1246
+ app.add_handler(MessageHandler(user_message_handler))
1247
+
1248
+ def register_middle_handlers(app: Client):
1249
+ app.add_handler(MessageHandler(middle_channel_handler, filters.chat(config.MIDDLE_CHANNEL)))
1250
+
1251
+ async def run_clients():
1252
+ global bot_client, user_client
1253
+
1254
+ os.makedirs("/data/sessions", exist_ok=True)
1255
+
1256
+ bot_client = Client(
1257
+ "/data/sessions/bot_session",
1258
+ api_id=config.API_ID,
1259
+ api_hash=config.API_HASH,
1260
+ bot_token=config.BOT_TOKEN
1261
+ )
1262
+
1263
+ user_client = Client(
1264
+ "/data/sessions/user_session",
1265
+ api_id=config.API_ID,
1266
+ api_hash=config.API_HASH,
1267
+ session_string=config.SESSION_STRING
1268
+ )
1269
+
1270
+ register_bot_handlers(bot_client)
1271
+ register_user_handlers(user_client)
1272
+ register_middle_handlers(bot_client)
1273
+
1274
+ await bot_client.start()
1275
+ await user_client.start()
1276
+
1277
+ await warm_middle_peer()
1278
+
1279
+ logger.info("✅ البوتان شغّالان")
1280
+ asyncio.create_task(poll_public_sources_loop())
1281
+ logger.info("✅ تم تشغيل نظام Polling للمصادر العامة")
1282
+ await asyncio.Event().wait()
1283
+
1284
+ def run_bot():
1285
+ lock_file = "/tmp/telegram_bot_core_running.lock"
1286
+
1287
+ if os.path.exists(lock_file):
1288
+ logger.warning("⚠️ البوت يعمل مسبقاً، تم منع تشغيل نسخة ثانية.")
1289
+ return
1290
+
1291
+ with open(lock_file, "w") as f:
1292
+ f.write(str(os.getpid()))
1293
+
1294
+ loop = asyncio.new_event_loop()
1295
+ asyncio.set_event_loop(loop)
1296
+
1297
+ try:
1298
+ loop.run_until_complete(run_clients())
1299
+ except KeyboardInterrupt:
1300
+ pass
1301
+ except Exception as e:
1302
+ logger.exception(f"توقف البوت بسبب خطأ: {e}")
1303
+ finally:
1304
+ try:
1305
+ if bot_client:
1306
+ loop.run_until_complete(bot_client.stop())
1307
+ except Exception:
1308
+ pass
1309
+
1310
+ try:
1311
+ if user_client:
1312
+ loop.run_until_complete(user_client.stop())
1313
+ except Exception:
1314
+ pass
1315
+
1316
+ try:
1317
+ if os.path.exists(lock_file):
1318
+ os.remove(lock_file)
1319
+ except Exception:
1320
+ pass
1321
+
1322
+ loop.close()
config.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ API_ID = int(os.getenv("API_ID", "0"))
4
+ API_HASH = os.getenv("API_HASH", "")
5
+ BOT_TOKEN = os.getenv("BOT_TOKEN", "")
6
+ SESSION_STRING = os.getenv("SESSION_STRING", "")
7
+
8
+ # قراءة قائمة الأدمن من متغير ADMINS (أرقام مفصولة بفواصل)
9
+ admins_str = os.getenv("ADMINS", "")
10
+ ADMINS = [int(x.strip()) for x in admins_str.split(",") if x.strip()]
11
+
12
+ # إذا لم يُضبط ADMINS نحاول استخدام ADMIN_ID القديم (للتوافق)
13
+ if not ADMINS:
14
+ old_admin = os.getenv("ADMIN_ID", "")
15
+ if old_admin:
16
+ ADMINS = [int(old_admin)]
17
+
18
+ MIDDLE_CHANNEL = int(os.getenv("MIDDLE_CHANNEL", "0"))
19
+
20
+ if not all([API_ID, API_HASH, BOT_TOKEN, SESSION_STRING, MIDDLE_CHANNEL]):
21
+ raise ValueError("جميع المتغيرات الأساسية مطلوبة")
22
+ if not ADMINS:
23
+ raise ValueError("يجب تعيين ADMINS على الأقل معرف أدمن واحد")
database.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import time
4
+ from threading import Lock
5
+
6
+ DB_FILE = "/data/data.json"
7
+ BACKUP_DIR = "/data/backups"
8
+ SCHEMA_VERSION = 2
9
+ lock = Lock()
10
+
11
+ DEFAULT_BLOCKED_WORDS = [
12
+ "إعلان", "اعلان", "تبادل", "ممول", "تمويل", "للتواصل",
13
+ "اشتراك", "تابعونا", "اشترك", "قناتنا", "بوت", "عبر البوت",
14
+ "عرض خاص", "لفترة محدودة", "اضغط هنا", "لمشاهدة المزيد",
15
+ "حصرياً", "تم النشر بواسطة"
16
+ ]
17
+
18
+ DEFAULT_DATA = {
19
+ "schema_version": SCHEMA_VERSION,
20
+ "channels": {},
21
+ "public_sources": [],
22
+ "source_meta": {},
23
+ "blocked_words": DEFAULT_BLOCKED_WORDS,
24
+ "allowed_users": [],
25
+ "last_source_messages": {},
26
+ "settings": {},
27
+ }
28
+
29
+
30
+ def _now():
31
+ return int(time.time())
32
+
33
+
34
+ def _dedupe_int_list(values):
35
+ out = []
36
+ seen = set()
37
+ for value in values or []:
38
+ try:
39
+ item = int(value)
40
+ except Exception:
41
+ item = value
42
+ key = str(item)
43
+ if key not in seen:
44
+ seen.add(key)
45
+ out.append(item)
46
+ return out
47
+
48
+
49
+ def _normalize_channel(cid, value):
50
+ if not isinstance(value, dict):
51
+ value = {"name": str(value)}
52
+ value.setdefault("name", value.get("title") or str(cid))
53
+ value.setdefault("title", value.get("name") or str(cid))
54
+ value.setdefault("username", "")
55
+ value.setdefault("link", "")
56
+ value.setdefault("chat_type", "")
57
+ value.setdefault("tail", "")
58
+ value.setdefault("special_sources", [])
59
+ value.setdefault("paused", False)
60
+ value.setdefault("posts_count", 0)
61
+ value.setdefault("added_at", _now())
62
+ value["special_sources"] = _dedupe_int_list(value.get("special_sources", []))
63
+ return value
64
+
65
+
66
+ def _normalize_source_meta(source_id, value=None):
67
+ if not isinstance(value, dict):
68
+ value = {}
69
+ sid = str(source_id)
70
+ value.setdefault("id", int(source_id) if str(source_id).lstrip('-').isdigit() else source_id)
71
+ value.setdefault("name", value.get("title") or sid)
72
+ value.setdefault("title", value.get("name") or sid)
73
+ value.setdefault("username", "")
74
+ value.setdefault("link", "")
75
+ value.setdefault("chat_type", "")
76
+ value.setdefault("added_at", _now())
77
+ value.setdefault("paused", False)
78
+ return value
79
+
80
+
81
+ def _normalize_data(data):
82
+ if not isinstance(data, dict):
83
+ data = {}
84
+
85
+ for key, value in DEFAULT_DATA.items():
86
+ if key not in data:
87
+ data[key] = value.copy() if isinstance(value, (list, dict)) else value
88
+
89
+ if not isinstance(data.get("channels"), dict):
90
+ data["channels"] = {}
91
+ if not isinstance(data.get("public_sources"), list):
92
+ data["public_sources"] = []
93
+ if not isinstance(data.get("source_meta"), dict):
94
+ data["source_meta"] = {}
95
+ if not isinstance(data.get("blocked_words"), list):
96
+ data["blocked_words"] = DEFAULT_BLOCKED_WORDS.copy()
97
+ if not isinstance(data.get("allowed_users"), list):
98
+ data["allowed_users"] = []
99
+ if not isinstance(data.get("last_source_messages"), dict):
100
+ data["last_source_messages"] = {}
101
+ if not isinstance(data.get("settings"), dict):
102
+ data["settings"] = {}
103
+
104
+ data["schema_version"] = SCHEMA_VERSION
105
+ data["public_sources"] = _dedupe_int_list(data.get("public_sources", []))
106
+
107
+ channels = {}
108
+ for cid, ch in data.get("channels", {}).items():
109
+ channels[str(cid)] = _normalize_channel(cid, ch)
110
+ data["channels"] = channels
111
+
112
+ meta = {}
113
+ for source in data["public_sources"]:
114
+ sid = str(source)
115
+ meta[sid] = _normalize_source_meta(source, data.get("source_meta", {}).get(sid, {}))
116
+ for sid, value in data.get("source_meta", {}).items():
117
+ if sid not in meta:
118
+ meta[sid] = _normalize_source_meta(sid, value)
119
+ data["source_meta"] = meta
120
+
121
+ # normalize last source ids as strings
122
+ data["last_source_messages"] = {str(k): v for k, v in data.get("last_source_messages", {}).items()}
123
+ return data
124
+
125
+
126
+ def _read():
127
+ os.makedirs("/data", exist_ok=True)
128
+
129
+ if not os.path.exists(DB_FILE):
130
+ with open(DB_FILE, "w", encoding="utf-8") as f:
131
+ json.dump(DEFAULT_DATA, f, ensure_ascii=False, indent=2)
132
+
133
+ try:
134
+ with open(DB_FILE, "r", encoding="utf-8") as f:
135
+ data = json.load(f)
136
+ except Exception:
137
+ data = DEFAULT_DATA.copy()
138
+
139
+ return _normalize_data(data)
140
+
141
+
142
+ def _write(data):
143
+ os.makedirs("/data", exist_ok=True)
144
+ data = _normalize_data(data)
145
+
146
+ tmp_file = DB_FILE + ".tmp"
147
+ with open(tmp_file, "w", encoding="utf-8") as f:
148
+ json.dump(data, f, ensure_ascii=False, indent=2)
149
+ os.replace(tmp_file, DB_FILE)
150
+
151
+
152
+ def _write_backup(data):
153
+ try:
154
+ os.makedirs(BACKUP_DIR, exist_ok=True)
155
+ backup_file = os.path.join(BACKUP_DIR, f"backup_{int(time.time())}.json")
156
+ with open(backup_file, "w", encoding="utf-8") as f:
157
+ json.dump(_normalize_data(data), f, ensure_ascii=False, indent=2)
158
+ # keep last 5 backups only
159
+ files = sorted([os.path.join(BACKUP_DIR, x) for x in os.listdir(BACKUP_DIR) if x.endswith('.json')])
160
+ for old in files[:-5]:
161
+ try:
162
+ os.remove(old)
163
+ except Exception:
164
+ pass
165
+ except Exception:
166
+ pass
167
+
168
+
169
+ def get_all_channels():
170
+ with lock:
171
+ data = _read()
172
+ return [{"id": k, **v} for k, v in data["channels"].items()]
173
+
174
+
175
+ def add_channel(channel_id, name="", title="", username="", link="", chat_type=""):
176
+ cid = str(channel_id)
177
+ with lock:
178
+ data = _read()
179
+ created = cid not in data["channels"]
180
+ if created:
181
+ data["channels"][cid] = _normalize_channel(cid, {
182
+ "name": title or name or cid,
183
+ "title": title or name or cid,
184
+ "username": username or "",
185
+ "link": link or "",
186
+ "chat_type": chat_type or "",
187
+ "tail": "",
188
+ "special_sources": [],
189
+ "paused": False,
190
+ "posts_count": 0,
191
+ "added_at": _now(),
192
+ })
193
+ else:
194
+ ch = data["channels"][cid]
195
+ if title or name:
196
+ ch["name"] = title or name
197
+ ch["title"] = title or name
198
+ if username is not None:
199
+ ch["username"] = username or ch.get("username", "")
200
+ if link is not None:
201
+ ch["link"] = link or ch.get("link", "")
202
+ if chat_type is not None:
203
+ ch["chat_type"] = chat_type or ch.get("chat_type", "")
204
+ _write(data)
205
+ if created:
206
+ _write_backup(data)
207
+ return created
208
+
209
+
210
+ def delete_channel(channel_id):
211
+ cid = str(channel_id)
212
+ with lock:
213
+ data = _read()
214
+ if cid in data["channels"]:
215
+ del data["channels"][cid]
216
+ _write(data)
217
+ _write_backup(data)
218
+ return True
219
+ return False
220
+
221
+
222
+ def update_channel(channel_id, key, value):
223
+ cid = str(channel_id)
224
+ with lock:
225
+ data = _read()
226
+ if cid in data["channels"]:
227
+ data["channels"][cid][key] = value
228
+ _write(data)
229
+ _write_backup(data)
230
+ return True
231
+ return False
232
+
233
+
234
+ def increment_post_count(channel_id):
235
+ cid = str(channel_id)
236
+ with lock:
237
+ data = _read()
238
+ if cid in data["channels"]:
239
+ data["channels"][cid].setdefault("posts_count", 0)
240
+ data["channels"][cid]["posts_count"] += 1
241
+ _write(data)
242
+ return True
243
+ return False
244
+
245
+
246
+ def get_channel(channel_id):
247
+ cid = str(channel_id)
248
+ with lock:
249
+ data = _read()
250
+ return data["channels"].get(cid)
251
+
252
+
253
+ def get_public_sources():
254
+ with lock:
255
+ data = _read()
256
+ return data["public_sources"]
257
+
258
+
259
+ def get_source_meta(source_id):
260
+ sid = str(source_id)
261
+ with lock:
262
+ data = _read()
263
+ return data.get("source_meta", {}).get(sid, _normalize_source_meta(source_id))
264
+
265
+
266
+ def get_all_public_sources_with_meta():
267
+ with lock:
268
+ data = _read()
269
+ return [{"id": s, **data.get("source_meta", {}).get(str(s), _normalize_source_meta(s))} for s in data["public_sources"]]
270
+
271
+
272
+ def add_public_source(source_id, name="", title="", username="", link="", chat_type=""):
273
+ try:
274
+ source_id = int(source_id)
275
+ except Exception:
276
+ pass
277
+ sid = str(source_id)
278
+
279
+ with lock:
280
+ data = _read()
281
+ created = source_id not in data["public_sources"]
282
+ if created:
283
+ data["public_sources"].append(source_id)
284
+ old = data.setdefault("source_meta", {}).get(sid, {})
285
+ meta = _normalize_source_meta(source_id, old)
286
+ if title or name:
287
+ meta["name"] = title or name
288
+ meta["title"] = title or name
289
+ if username is not None:
290
+ meta["username"] = username or meta.get("username", "")
291
+ if link is not None:
292
+ meta["link"] = link or meta.get("link", "")
293
+ if chat_type is not None:
294
+ meta["chat_type"] = chat_type or meta.get("chat_type", "")
295
+ data["source_meta"][sid] = meta
296
+ _write(data)
297
+ if created:
298
+ _write_backup(data)
299
+ return created
300
+
301
+
302
+ def update_source_meta(source_id, **kwargs):
303
+ sid = str(source_id)
304
+ with lock:
305
+ data = _read()
306
+ meta = _normalize_source_meta(source_id, data.setdefault("source_meta", {}).get(sid, {}))
307
+ for key, value in kwargs.items():
308
+ if value is not None:
309
+ meta[key] = value
310
+ data["source_meta"][sid] = meta
311
+ _write(data)
312
+ return True
313
+
314
+
315
+ def remove_public_source(source_id):
316
+ try:
317
+ source_id = int(source_id)
318
+ except Exception:
319
+ pass
320
+ sid = str(source_id)
321
+
322
+ with lock:
323
+ data = _read()
324
+ if source_id in data["public_sources"]:
325
+ data["public_sources"].remove(source_id)
326
+ data["last_source_messages"].pop(sid, None)
327
+ data.get("source_meta", {}).pop(sid, None)
328
+ _write(data)
329
+ _write_backup(data)
330
+ return True
331
+ return False
332
+
333
+
334
+ def get_blocked_words():
335
+ with lock:
336
+ data = _read()
337
+ return data["blocked_words"]
338
+
339
+
340
+ def add_blocked_word(word):
341
+ word = str(word).strip()
342
+ if not word:
343
+ return False
344
+ with lock:
345
+ data = _read()
346
+ if word not in data["blocked_words"]:
347
+ data["blocked_words"].append(word)
348
+ _write(data)
349
+ _write_backup(data)
350
+ return True
351
+ return False
352
+
353
+
354
+ def remove_blocked_word(word):
355
+ word = str(word).strip()
356
+ with lock:
357
+ data = _read()
358
+ if word in data["blocked_words"]:
359
+ data["blocked_words"].remove(word)
360
+ _write(data)
361
+ _write_backup(data)
362
+ return True
363
+ return False
364
+
365
+
366
+ def get_last_source_message(source_id):
367
+ with lock:
368
+ data = _read()
369
+ value = data.get("last_source_messages", {}).get(str(source_id))
370
+ try:
371
+ return int(value) if value is not None else None
372
+ except Exception:
373
+ return None
374
+
375
+
376
+ def set_last_source_message(source_id, message_id):
377
+ with lock:
378
+ data = _read()
379
+ data.setdefault("last_source_messages", {})[str(source_id)] = int(message_id)
380
+ _write(data)
381
+ return True
382
+
383
+
384
+ def reset_last_source_message(source_id):
385
+ with lock:
386
+ data = _read()
387
+ if str(source_id) in data.get("last_source_messages", {}):
388
+ del data["last_source_messages"][str(source_id)]
389
+ _write(data)
390
+ _write_backup(data)
391
+ return True
392
+ return False
393
+
394
+
395
+ def export_data():
396
+ with lock:
397
+ data = _read()
398
+ return json.dumps(_normalize_data(data), ensure_ascii=False, indent=2)
399
+
400
+
401
+ def import_data(json_str):
402
+ with lock:
403
+ new_data = json.loads(json_str)
404
+ new_data = _normalize_data(new_data)
405
+ _write(new_data)
406
+ _write_backup(new_data)
407
+ return {
408
+ "channels": len(new_data.get("channels", {})),
409
+ "public_sources": len(new_data.get("public_sources", [])),
410
+ "blocked_words": len(new_data.get("blocked_words", [])),
411
+ "last_source_messages": len(new_data.get("last_source_messages", {})),
412
+ }
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ pyrogram>=2.0.0
2
+ tgcrypto
3
+ streamlit