allboot commited on
Commit
aafbe08
·
verified ·
1 Parent(s): cd76803

Delete facebook_bridge.py

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