allboot commited on
Commit
25dfa6f
ยท
verified ยท
1 Parent(s): 7dfca9a

Upload facebook_bridge .py

Browse files
Files changed (1) hide show
  1. facebook_bridge .py +249 -0
facebook_bridge .py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()