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