allboot commited on
Commit
be23b6f
·
verified ·
1 Parent(s): 8a6c267

Delete facebook_bridge.py

Browse files
Files changed (1) hide show
  1. facebook_bridge.py +0 -277
facebook_bridge.py DELETED
@@ -1,277 +0,0 @@
1
- """
2
- facebook_bridge.py
3
- ==================
4
- مراقبة قناة تيليجرام @CastleInfoiq ونشر المنشورات الجديدة على فيسبوك.
5
- مستقل 100% عن app.py — لا يلمسه ولا يتأثر به.
6
- """
7
-
8
- import os
9
- import json
10
- import asyncio
11
- import logging
12
- import tempfile
13
- import time
14
- import requests
15
- from datetime import datetime, timezone
16
-
17
- import pytz
18
- from pyrogram import Client, filters
19
- from pyrogram.types import Message
20
-
21
- # ─── إعداد التسجيل ───────────────────────────────────────────────────────────
22
-
23
- logging.basicConfig(
24
- level=logging.INFO,
25
- format="%(asctime)s [%(levelname)s] %(name)s — %(message)s",
26
- datefmt="%Y-%m-%d %H:%M:%S",
27
- )
28
- log = logging.getLogger("facebook_bridge")
29
-
30
- # ─── الإعدادات ────────────────────────────────────────────────────────────────
31
-
32
- API_ID = int(os.environ["API_ID"])
33
- API_HASH = os.environ["API_HASH"]
34
- SESSION_STRING = os.environ["SESSION_STRING"]
35
- TELEGRAM_CHANNEL = "@CastleInfoiq"
36
-
37
- FACEBOOK_PAGE_ID = os.environ.get("FACEBOOK_PAGE_ID", "1207551039107566")
38
- FB_TOKEN = os.environ["FACEBOOK_PAGE_ACCESS_TOKEN"]
39
- FB_API_BASE = "https://graph.facebook.com/v19.0"
40
-
41
- BAGHDAD_TZ = pytz.timezone("Asia/Baghdad")
42
- PUBLISH_HOUR_START = 9 # 09:00 صباحاً
43
- PUBLISH_HOUR_END = 23 # 23:00 مساءً
44
-
45
- # ملف تتبع المنشورات المنشورة مسبقاً
46
- POSTS_DB_FILE = "facebook_posts.json"
47
-
48
- # النص الذي يُحذف قبل النشر
49
- TEXT_TO_REMOVE = "اشتـــرك الآن :- https://t.me/CastleInfoiq"
50
-
51
- # ─── قاعدة بيانات المنشورات ───────────────────────────────────────────────────
52
-
53
- def load_published_ids() -> set:
54
- """تحميل معرّفات الرسائل المنشورة مسبقاً."""
55
- if not os.path.exists(POSTS_DB_FILE):
56
- return set()
57
- try:
58
- with open(POSTS_DB_FILE, "r", encoding="utf-8") as f:
59
- data = json.load(f)
60
- return set(data.get("published_ids", []))
61
- except Exception as e:
62
- log.warning(f"تعذّر تحميل {POSTS_DB_FILE}: {e}")
63
- return set()
64
-
65
-
66
- def save_published_id(msg_id: int, published_ids: set) -> None:
67
- """حفظ معرّف رسالة جديدة في قاعدة البيانات."""
68
- published_ids.add(msg_id)
69
- try:
70
- with open(POSTS_DB_FILE, "w", encoding="utf-8") as f:
71
- json.dump({"published_ids": list(published_ids)}, f, ensure_ascii=False, indent=2)
72
- except Exception as e:
73
- log.error(f"تعذّر حفظ {POSTS_DB_FILE}: {e}")
74
-
75
-
76
- # ─── التحقق من وقت النشر ─────────────────────────────────────────────────────
77
-
78
- def is_within_publish_hours() -> bool:
79
- """هل الوقت الحالي ضمن نافذة النشر المسموح بها؟"""
80
- now = datetime.now(BAGHDAD_TZ)
81
- return PUBLISH_HOUR_START <= now.hour < PUBLISH_HOUR_END
82
-
83
-
84
- # ─── تنظيف النص ──────────────────────────────────────────────────────────────
85
-
86
- def clean_text(text: str) -> str:
87
- """حذف سطر الاشتراك فقط والإبقاء على بقية النص."""
88
- if not text:
89
- return ""
90
- lines = text.splitlines()
91
- cleaned = [line for line in lines if TEXT_TO_REMOVE not in line]
92
- return "\n".join(cleaned).strip()
93
-
94
-
95
- # ─── النشر على فيسبوك ────────────────────────────────────────────────────────
96
-
97
- def _fb_post_text(text: str) -> bool:
98
- """نشر نص فقط على صفحة فيسبوك."""
99
- url = f"{FB_API_BASE}/{FACEBOOK_PAGE_ID}/feed"
100
- payload = {"message": text, "access_token": FB_TOKEN}
101
-
102
- for attempt in range(1, 4):
103
- try:
104
- resp = requests.post(url, data=payload, timeout=30)
105
- result = resp.json()
106
- if resp.ok and "id" in result:
107
- log.info(f"✅ Facebook publish success (text) — post_id={result['id']}")
108
- return True
109
- log.warning(f"⚠️ محاولة {attempt}/3 فشلت (نص): {result}")
110
- except Exception as e:
111
- log.warning(f"⚠️ محاولة {attempt}/3 استثناء (نص): {e}")
112
- time.sleep(5 * attempt)
113
-
114
- log.error("❌ Facebook publish failed (text) — استُنفدت جميع المحاولات")
115
- return False
116
-
117
-
118
- def _fb_post_photo(image_path: str, text: str) -> bool:
119
- """رفع صورة ونشرها مع النص على صفحة فيسبوك."""
120
- url = f"{FB_API_BASE}/{FACEBOOK_PAGE_ID}/photos"
121
-
122
- for attempt in range(1, 4):
123
- try:
124
- with open(image_path, "rb") as img_file:
125
- resp = requests.post(
126
- url,
127
- data={"message": text, "published": "true", "access_token": FB_TOKEN},
128
- files={"source": img_file},
129
- timeout=60,
130
- )
131
- result = resp.json()
132
- if resp.ok and ("id" in result or "post_id" in result):
133
- pid = result.get("post_id") or result.get("id")
134
- log.info(f"✅ Facebook publish success (photo) — post_id={pid}")
135
- return True
136
- log.warning(f"⚠️ محاولة {attempt}/3 فشلت (صورة): {result}")
137
- except Exception as e:
138
- log.warning(f"⚠️ محاولة {attempt}/3 استثناء (صورة): {e}")
139
- time.sleep(5 * attempt)
140
-
141
- log.error("❌ Facebook publish failed (photo) — استُنفدت جميع المحاولات")
142
- return False
143
-
144
-
145
- # ─── تنزيل الصورة ────────────────────────────────────────────────────────────
146
-
147
- async def download_photo_temp(client: Client, message: Message) -> str | None:
148
- """
149
- تنزيل صورة إلى ملف مؤقت وإعادة مساره.
150
- يعود None في حالة الفشل.
151
- """
152
- try:
153
- suffix = ".jpg"
154
- with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
155
- tmp_path = tmp.name
156
- path = await client.download_media(message, file_name=tmp_path)
157
- return path
158
- except Exception as e:
159
- log.error(f"تعذّر تنزيل الصورة: {e}")
160
- return None
161
-
162
-
163
- def delete_temp_file(path: str) -> None:
164
- """حذف الملف المؤقت بعد الرفع."""
165
- try:
166
- if path and os.path.exists(path):
167
- os.remove(path)
168
- except Exception as e:
169
- log.warning(f"تعذّر حذف الملف المؤقت {path}: {e}")
170
-
171
-
172
- # ─── معالجة الرسائل ──────────────────────────────────────────────────────────
173
-
174
- published_ids: set = load_published_ids()
175
-
176
- # نتتبع grouped_ids لتجنب معالجة ألبوم أكثر من مرة
177
- _handled_media_groups: set = set()
178
-
179
-
180
- async def process_message(client: Client, message: Message) -> None:
181
- """
182
- المعالج الرئيسي لكل رسالة واردة من القناة.
183
- """
184
- global published_ids, _handled_media_groups
185
-
186
- msg_id = message.id
187
- log.info(f"📩 Telegram post detected — id={msg_id}")
188
-
189
- # ── منع التكرار ──────────────────────────────────────────────────────────
190
- if msg_id in published_ids:
191
- log.info(f"⏭️ تجاهل — تم نشر id={msg_id} مسبقاً")
192
- return
193
-
194
- # ── فحص الوقت ────────────────────────────────────────────────────────────
195
- if not is_within_publish_hours():
196
- now_str = datetime.now(BAGHDAD_TZ).strftime("%H:%M")
197
- log.info(f"🕐 تجاهل — خارج نافذة النشر (الوقت الحالي: {now_str})")
198
- return
199
-
200
- # ── استخراج النص ─────────────────────────────────────────────────────────
201
- raw_text = message.text or message.caption or ""
202
- post_text = clean_text(raw_text)
203
-
204
- try:
205
- # ── ألبوم صور (media_group) ───────────────────────────────────────────
206
- if message.media_group_id:
207
- group_key = message.media_group_id
208
-
209
- if group_key in _handled_media_groups:
210
- # رسالة ثانية/ثالثة من نفس الألبوم — تُسجَّل كـ published لمنع إعادة المعالجة
211
- save_published_id(msg_id, published_ids)
212
- return
213
-
214
- _handled_media_groups.add(group_key)
215
- log.info(f"🖼️ ألبوم id={group_key} — سنأخذ أول صورة فقط")
216
-
217
- # نزّل صورة هذه الرسالة (أول رسالة في الألبوم)
218
- tmp_path = await download_photo_temp(client, message)
219
- if tmp_path:
220
- success = _fb_post_photo(tmp_path, post_text)
221
- delete_temp_file(tmp_path)
222
- else:
223
- # فشل التنزيل — نشر النص وحده
224
- success = _fb_post_text(post_text) if post_text else False
225
-
226
- # ── صورة منفردة ──────────────────────────────────────────────────────
227
- elif message.photo or message.document:
228
- log.info("🖼️ صورة منفردة")
229
- tmp_path = await download_photo_temp(client, message)
230
- if tmp_path:
231
- success = _fb_post_photo(tmp_path, post_text)
232
- delete_temp_file(tmp_path)
233
- else:
234
- success = _fb_post_text(post_text) if post_text else False
235
-
236
- # ── نص فقط ───────────────────────────────────────────────────────────
237
- elif post_text:
238
- log.info("📝 نص فقط")
239
- success = _fb_post_text(post_text)
240
-
241
- else:
242
- log.info("⏭️ رسالة بدون محتوى قابل للنشر — تجاهل")
243
- save_published_id(msg_id, published_ids)
244
- return
245
-
246
- if success:
247
- save_published_id(msg_id, published_ids)
248
-
249
- except Exception as e:
250
- log.error(f"❌ خطأ غير متوقع أثناء معالجة id={msg_id}: {e}", exc_info=True)
251
-
252
-
253
- # ─── تشغيل Pyrogram ──────────────────────────────────────────────────────────
254
-
255
- def main() -> None:
256
- log.info("🚀 بدء تشغيل facebook_bridge ...")
257
-
258
- app = Client(
259
- name="facebook_bridge_session",
260
- api_id=API_ID,
261
- api_hash=API_HASH,
262
- session_string=SESSION_STRING,
263
- )
264
-
265
- @app.on_message(filters.chat(TELEGRAM_CHANNEL) & ~filters.service)
266
- async def on_new_post(client: Client, message: Message):
267
- await process_message(client, message)
268
-
269
- log.info(f"👂 مراقبة القناة: {TELEGRAM_CHANNEL}")
270
- log.info(f"⏰ نافذة النشر: {PUBLISH_HOUR_START:02d}:00 – {PUBLISH_HOUR_END:02d}:00 (Baghdad)")
271
- log.info(f"📘 صفحة الفيسبوك: {FACEBOOK_PAGE_ID}")
272
-
273
- app.run()
274
-
275
-
276
- if __name__ == "__main__":
277
- main()