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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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"๐ ุตูุญุฉ ุงูููุณุจูู: {FACEBOOK_PAGE_ID}")
|
| 244 |
+
|
| 245 |
+
app.run()
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
if __name__ == "__main__":
|
| 249 |
+
main()
|