allboot commited on
Commit
01c1595
·
verified ·
1 Parent(s): e2c91ce

Delete facebook_bridge.py

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