-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAutoPostFB.py
More file actions
2056 lines (1800 loc) · 106 KB
/
AutoPostFB.py
File metadata and controls
2056 lines (1800 loc) · 106 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import requests
from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QGridLayout, QGroupBox,
QLabel, QLineEdit, QPushButton, QCheckBox, QComboBox, QListWidget, QTextEdit,
QTabWidget, QFileDialog, QMessageBox, QInputDialog)
from PySide6.QtCore import Qt, QThread, Signal
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from openai import OpenAI
from mistralai import Mistral
import groq
import google.generativeai as genai
import json
import os
import random
import time
import threading
import psutil
import sys
import pickle
import re
import csv
import glob
import hashlib
import platform
import subprocess
import zipfile
import io
import stat
# Biến toàn cục để kiểm soát luồng và Selenium
stop_event = threading.Event()
driver = None
COOKIE_FILE = "facebook_cookies.pkl"
version = "2.0.1"
released_date = "08/10/2025"
# Định nghĩa các định dạng file cần kiểm tra
image_extensions = [
'*.jpg', '*.jpeg', # image/jpeg
'*.png', # image/png
'*.gif', # image/gif
'*.bmp', # image/bmp
'*.webp', # image/webp
'*.tiff', '*.tif', # image/tiff
'*.heif', # image/heif
'*.heic', # image/heic
'*.svg', # image/svg+xml
'*.ico', # image/x-icon
'*.psd', # image/vnd.adobe.photoshop
'*.raw', # image/x-raw
'*.cr2', # Canon RAW
'*.nef', # Nikon RAW
'*.dng', # Digital Negative
'*.ai', # Adobe Illustrator
'*.eps', # image/eps
'*.pcx', # image/x-pcx
'*.ppm', # image/x-portable-pixmap
'*.xcf' # GIMP image file
]
audio_extensions = [
'*.mp3', # audio/mpeg
'*.wav', # audio/wav
'*.aac', # audio/aac
'*.ogg', # audio/ogg
'*.flac', # audio/flac
'*.m4a', # audio/mp4
'*.wma', # audio/x-ms-wma
'*.opus', # audio/opus
'*.amr', # audio/amr
'*.aiff', '*.aif', # audio/aiff
'*.mid', '*.midi', # audio/midi
'*.ac3', # audio/ac3
'*.ra', '*.rm', # audio/x-pn-realaudio
'*.ape', # audio/ape
'*.au', # audio/basic
'*.voc', # audio/x-voc
'*.weba', # audio/webm
'*.dsd', # audio/dsd
'*.mka', # audio/x-matroska
'*.qcp' # audio/qcelp
]
video_extensions = [
'*.mp4', # video/mp4
'*.avi', # video/x-msvideo
'*.mov', # video/quicktime
'*.mkv', # video/x-matroska
'*.flv', # video/x-flv
'*.wmv', # video/x-ms-wmv
'*.webm', # video/webm
'*.m4v', # video/x-m4v
'*.3gp', # video/3gpp
'*.vob', # video/dvd
'*.ogv', # video/ogg
'*.ts', # video/mp2t
'*.mpeg', '*.mpg', # video/mpeg
'*.rm', '*.rmvb', # video/vnd.rn-realvideo
'*.asf', # video/x-ms-asf
'*.divx', # video/divx
'*.m2ts', # video/m2ts
'*.f4v', # video/x-f4v
'*.mxf', # video/mxf
'*.swf' # application/x-shockwave-flash
]
key_map = {
"Nhóm": "groups",
"Gửi tin nhắn tới thành viên nhóm": "members",
"Trang": "pages",
"Marketplace": "marketplace",
"Groups": "groups",
"Send message to group members": "members",
"Pages": "pages"
}
def resource_path(relative_path):
""" Lấy đường dẫn tuyệt đối đến tài nguyên, hoạt động cả khi chạy từ EXE và script """
if getattr(sys, 'frozen', False):
# Trường hợp chạy từ EXE: PyInstaller tạo thư mục tạm '_MEIXXXXXX'
base_path = sys._MEIPASS
else:
# Trường hợp chạy từ script: Lấy đường dẫn thư mục hiện tại
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
class ChromeDriverThread(QThread):
driver_ready = Signal(object)
driver_error = Signal(str)
def __init__(self, window, parent=None):
super().__init__(parent)
self.window = window
self.driver_path = None
def _get_compatible_chromedriver(self, browser_version):
"""
Tự động tìm và tải ChromeDriver tương thích cho phiên bản trình duyệt đã cho trên Linux.
Sử dụng JSON endpoints chính thức từ Google.
"""
self.window.update_status(f"Đang tìm ChromeDriver tương thích cho trình duyệt phiên bản {browser_version}...")
try:
# Lấy phiên bản chính (major version)
major_version = browser_version.split('.')[0]
# Lấy danh sách các phiên bản ChromeDriver có sẵn
api_url = "https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json"
response = requests.get(api_url)
response.raise_for_status()
data = response.json()
# Tìm URL tải về cho phiên bản và kiến trúc phù hợp (linux-arm64)
download_url = None
# Ưu tiên tìm phiên bản khớp hoàn toàn hoặc gần nhất
target_version_info = None
for version_info in reversed(data['versions']):
if version_info['version'].startswith(major_version):
target_version_info = version_info
break
if not target_version_info:
self.driver_error.emit(f"Không tìm thấy ChromeDriver nào cho phiên bản major {major_version}.")
return None
# Xác định đúng platform
machine_arch = platform.machine()
if machine_arch == "aarch64": # ARM64
platform_name = "linux-arm64"
elif machine_arch == "x86_64": # x64
platform_name = "linux-x64"
else:
self.driver_error.emit(f"Kiến trúc không được hỗ trợ: {machine_arch}")
return None
for download in target_version_info['downloads'].get('chromedriver', []):
if download['platform'] == platform_name:
download_url = download['url']
break
if not download_url:
self.driver_error.emit(f"Không tìm thấy link tải ChromeDriver cho platform '{platform_name}' phiên bản {target_version_info['version']}.")
return None
self.window.update_status(f"Đang tải ChromeDriver từ: {download_url}")
# Tải file zip
zip_response = requests.get(download_url, stream=True)
zip_response.raise_for_status()
# Giải nén và lưu file
with zipfile.ZipFile(io.BytesIO(zip_response.content)) as z:
# Tìm file chromedriver trong zip
chromedriver_filename = None
for name in z.namelist():
if 'chromedriver' in name and not name.endswith('/'):
chromedriver_filename = name
break
if not chromedriver_filename:
self.driver_error.emit("Không tìm thấy file chromedriver trong file zip đã tải.")
return None
# Tạo đường dẫn lưu file
output_path = os.path.join(os.path.abspath("."), "chromedriver")
with z.open(chromedriver_filename) as source, open(output_path, "wb") as target:
target.write(source.read())
# Cấp quyền thực thi cho file chromedriver trên Linux/Mac
st = os.stat(output_path)
os.chmod(output_path, st.st_mode | stat.S_IEXEC)
self.window.update_status(f"Tải và cài đặt ChromeDriver thành công tại: {output_path}")
return output_path
except Exception as e:
self.driver_error.emit(f"Lỗi khi tự động tải ChromeDriver: {e}")
return None
def run(self):
try:
options = webdriver.ChromeOptions()
options.add_argument("--disable-notifications")
desktop_user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
options.add_argument(f"user-agent={desktop_user_agent}")
options.add_experimental_option("detach", True)
if self.window.headless_check.isChecked():
options.add_argument("--headless=new")
options.add_argument("--disable-gpu")
if self.window.profile_check.isChecked():
profile_path = self.window.profile_path if hasattr(self.window, 'profile_path') else None
if profile_path:
options.add_argument(f"user-data-dir={profile_path}")
options.add_argument("--profile-directory=Default")
# --- Cấu hình riêng cho Linux ---
if platform.system() == "Linux":
self.window.update_status("Phát hiện hệ điều hành Linux. Áp dụng cấu hình riêng...")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--disable-setuid-sandbox")
browser_locations = ["/usr/bin/google-chrome-stable", "/usr/bin/chromium-browser", "/snap/bin/chromium"]
browser_path = None
for loc in browser_locations:
if os.path.exists(loc):
browser_path = loc
options.binary_location = browser_path
self.window.update_status(f"Tìm thấy trình duyệt tại: {browser_path}")
break
if not browser_path:
self.driver_error.emit("Không tìm thấy trình duyệt Chrome/Chromium trên hệ thống.")
return
try:
version_output = subprocess.check_output([browser_path, "--version"], text=True).strip()
match = re.search(r'(\d+\.\d+\.\d+\.\d+)', version_output)
if not match:
self.driver_error.emit(f"Không thể xác định phiên bản từ chuỗi: '{version_output}'")
return
browser_version = match.group(1)
self.window.update_status(f"Phiên bản trình duyệt: {browser_version}")
except Exception as e:
self.driver_error.emit(f"Không thể lấy phiên bản trình duyệt: {e}")
return
machine_arch = platform.machine()
# Nếu là kiến trúc ARM, bỏ qua webdriver-manager và dùng phương pháp tải thủ công
if machine_arch == "aarch64" or machine_arch == "arm64":
self.window.update_status(f"Phát hiện kiến trúc ARM ({machine_arch}). Sử dụng phương pháp tải driver tùy chỉnh.")
self.driver_path = self._get_compatible_chromedriver(browser_version)
if not self.driver_path:
return
service = Service(executable_path=self.driver_path)
# Với các kiến trúc Linux khác (x86_64), thử webdriver-manager trước
else:
try:
self.window.update_status("Thử sử dụng webdriver-manager để tải chromedriver...")
service = Service(ChromeDriverManager().install())
self.driver_path = service.path
except Exception as e:
self.window.update_status(f"webdriver-manager thất bại ({e}). Chuyển sang phương pháp tải thủ công.")
self.driver_path = self._get_compatible_chromedriver(browser_version)
if not self.driver_path:
return
service = Service(executable_path=self.driver_path)
# Cấu hình cho Windows và các hệ điều hành khác
else:
self.window.update_status("Đang sử dụng webdriver-manager để quản lý chromedriver...")
service = Service(ChromeDriverManager().install())
self.window.update_status("Đang khởi tạo Chrome Driver...")
driver_instance = webdriver.Chrome(service=service, options=options)
self.driver_ready.emit(driver_instance)
except Exception as e:
import traceback
error_msg = f"Không thể khởi tạo Chrome Driver: {e}\n{traceback.format_exc()}"
self.driver_error.emit(error_msg)
class ChromeMonitorThread(QThread):
chrome_closed = Signal()
def run(self):
while True:
if not self.is_chrome_running():
self.chrome_closed.emit()
break
time.sleep(5)
@staticmethod
def is_chrome_running():
for process in psutil.process_iter(attrs=['name']):
if "chrome" in process.info['name'].lower():
return True
return False
class LoginThread(QThread):
login_success = Signal()
status_updated = Signal(str)
def __init__(self, window, parent=None):
super().__init__(parent)
self.window = window
self.email = window.email_entry.text()
self.password = window.password_entry.text()
self.driver = self.window.driver
def run(self):
if self.driver is None:
self.status_updated.emit(self.window.translate("LoginThread_driver_is_not_initialized"))
return
self.driver.get("https://facebook.com")
time.sleep(2)
# Thử tải cookie trước
if self.load_cookies(self.driver):
self.driver.get("https://facebook.com")
time.sleep(2)
if self.is_logged_in(self.driver):
self.status_updated.emit(self.window.translate("LoginThread_logged_in_by_cookie"))
if self.window.sub_account_check.isChecked():
self.switch_to_sub_account(self.driver)
self.login_success.emit()
return
# Đăng nhập thủ công
try:
email_input = self.driver.find_element(By.ID, "email")
email_input.send_keys(self.email)
password_input = self.driver.find_element(By.ID, "pass")
password_input.send_keys(self.password)
self.driver.find_element(By.XPATH, "//button[@name='login' and @data-testid='royal-login-button' and @type='submit']").click()
time.sleep(5)
except NoSuchElementException:
self.status_updated.emit(self.window.translate("LoginThread_not_found_login_input"))
self.status_updated.emit(self.window.translate("LoginThread_waitting_for_login"))
while not self.is_logged_in(self.driver) and not stop_event.is_set():
time.sleep(5)
if stop_event.is_set():
return
self.status_updated.emit(self.window.translate("LoginThread_logged_in_successful"))
self.save_cookies(self.driver)
if self.window.sub_account_check.isChecked():
self.switch_to_sub_account(self.driver)
self.login_success.emit()
def is_logged_in(self, driver):
try:
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "//form[starts-with(@action, '/logout.php') and contains(@action, 'logout')]"))
)
return True
except Exception:
return False
def save_cookies(self, driver):
cookies = driver.get_cookies()
with open(COOKIE_FILE, "wb") as file:
pickle.dump(cookies, file)
self.status_updated.emit(self.window.translate("LoginThread_saved_cookie_to_file"))
def load_cookies(self, driver):
if os.path.exists(COOKIE_FILE):
with open(COOKIE_FILE, "rb") as file:
cookies = pickle.load(file)
for cookie in cookies:
driver.add_cookie(cookie)
self.status_updated.emit(self.window.translate("LoginThread_loaded_cookie_from_file"))
return True
return False
def switch_to_sub_account(self, driver):
sub_account_name = self.window.sub_account_entry.text().strip()
try:
account_menu = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "//span[@class]//div[@aria-expanded and @aria-label and @role='button' and @tabindex='0']//div[@aria-hidden='true' and @style]"))
)
account_menu.click()
time.sleep(2)
try:
# Kiểm tra account đã active chưa (nếu có thì không cần click)
WebDriverWait(driver, 3).until(
EC.presence_of_element_located((By.XPATH, f"//a[contains(@href, '/me/') and @role='link' and @tabindex='0']//span[text()='{sub_account_name}' and @dir='auto']"))
)
except TimeoutException:
# Nếu không tìm thấy account active -> click switch
switch_btn = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, f"//div[contains(@aria-label, '{sub_account_name}')]//span[text()='{sub_account_name}' and @dir='auto']"))
)
switch_btn.click()
time.sleep(5)
self.status_updated.emit(self.window.translate("LoginThread_switched_to_sub_account",sub_account_name=sub_account_name))
self.save_cookies(driver) # Lưu lại cookie sau khi chuyển tài khoản
except TimeoutException as e:
self.status_updated.emit(self.window.translate("LoginThread_could_not_switch_to_sub_account", sub_account_name=sub_account_name, e="Timeout waiting for element"))
except NoSuchElementException as e:
self.status_updated.emit(self.window.translate("LoginThread_could_not_switch_to_sub_account", sub_account_name=sub_account_name, e="Element not found"))
except Exception as e:
self.status_updated.emit(self.window.translate("LoginThread_could_not_switch_to_sub_account", sub_account_name=sub_account_name, e=str(e)))
class FetchDataThread(QThread):
fetch_completed = Signal()
fetch_failed = Signal(str)
status_updated = Signal(str)
def __init__(self, window, data_type, url=None, parent=None):
super().__init__(parent)
self.window = window
self.data_type = data_type
self.url = url
self.driver = self.window.driver
self.items = []
def run(self):
if self.driver is None:
self.status_updated.emit(self.window.translate("LoginThread_driver_is_not_initialized"))
return
try:
self.items = self.fetch_data(self.driver, self.data_type, self.url)
if stop_event.is_set():
self.status_updated.emit(self.window.translate("FetchDataThread_stopped_to_get_data_by_request"))
return
if self.items: # Chỉ tiếp tục nếu có dữ liệu
self.window.url_items_list.clear()
for item in self.items:
self.window.url_items_list.addItem(item)
self.window.save_settings()
self.fetch_completed.emit()
else:
tmp_data_type = self.data_type
self.status_updated.emit(self.window.translate("FetchDataThread_could_not_get_data"))
except Exception as e:
self.status_updated.emit(self.window.translate("FetchDataThread_error_during_fetching_data", e=str(e)))
def fetch_data(self, driver, data_type, url=None):
if driver is None:
self.status_updated.emit(self.window.translate("LoginThread_driver_is_not_initialized"))
return []
self.status_updated.emit(self.window.translate("FetchDataThread_start_fetching_data", data_type=data_type, url=url))
"""Lấy danh sách nhóm hoặc danh sách thành viên tùy thuộc vào data_type."""
if data_type == "groups":
driver.get("https://www.facebook.com/groups/joins/?nav_source=tab")
elif data_type == "members":
if not url:
self.status_updated.emit(self.window.translate("FetchDataThread_provide_group_url"))
return []
driver.get(url.rstrip('/') + "/members")
time.sleep(5)
items = set()
last_count = 0
no_new_items_count = 0
max_no_new_items = 10 # Số lần cuộn không có nhóm mới trước khi dừng
scroll_attempts = 0
save_interval = 10 # Lưu sau mỗi 10 liên kết mới
new_items_count = 0
while no_new_items_count < max_no_new_items and not stop_event.is_set():
# Lấy vị trí hiện tại trước khi cuộn
current_position = driver.execute_script("return window.pageYOffset;")
window_height = driver.execute_script("return window.innerHeight;")
# Cuộn xuống dưới cùng
self.smooth_scroll_to_position(driver, current_position + window_height)
for _ in range(20):
if stop_event.is_set():
break
time.sleep(0.1)
# Kiểm tra xem có cuộn được không
new_position = driver.execute_script("return window.pageYOffset;")
if new_position == current_position:
# Nếu không cuộn được xuống nữa, thử cuộn lên đầu rồi xuống lại
self.smooth_scroll_to_position(driver, 0)
for _ in range(20):
if stop_event.is_set():
break
time.sleep(0.1)
self.smooth_scroll_to_position(driver, new_position)
for _ in range(20):
if stop_event.is_set():
break
time.sleep(0.1)
scroll_attempts += 1
if scroll_attempts > 3: # Nếu đã thử nhiều lần mà không cuộn được
break
# Lấy danh sách nhóm mới
try:
if data_type == "groups":
elements = driver.find_elements(
By.XPATH, "//div[@role='listitem' and @style]//span[@dir='auto']//a[contains(@href, '/groups/') and not(contains(@href, 'category')) and @role='link' and @tabindex='0']"
)
elif data_type == "members":
elements = driver.find_elements(
By.XPATH, "//div[@role='list']//div[@data-visualcompletion='ignore-dynamic' and @role='listitem']//div[@aria-disabled='false']//a[contains(@href, '/groups/') and contains(@href, '/user/') and @tabindex='0' and @role='link']" # XPath cho liên kết tin nhắn của thành viên
)
current_items_count = len(items)
for element in elements:
if stop_event.is_set(): # Kiểm tra lại trước khi thêm item
break
item_url = element.get_attribute("href")
if item_url:
clean_url = item_url.split("?")[0]
if data_type == "members":
user_id = clean_url.rstrip("/").split("/")[-1] # Lấy phần cuối của URL
clean_url = f"https://www.facebook.com/messages/t/{user_id}" # Tạo URL mới
if clean_url not in items:
items.add(clean_url)
new_items_count += 1
current_urls = [self.window.url_items_list.item(i).text() for i in range(self.window.url_items_list.count())]
if clean_url not in current_urls:
self.window.url_items_list.addItem(clean_url)
# Lưu mỗi 10 item cho cả "groups" và "members"
if new_items_count >= save_interval:
if data_type == "groups":
self.window.settings["groups"] = list(items)
elif data_type == "members":
self.window.settings["members"] = list(items)
self.window.save_settings()
count_items = len(items)
self.status_updated.emit(self.window.translate("FetchDataThread_saved_items_to_settings", count_items=count_items, data_type=data_type))
new_items_count = 0
# Kiểm tra dữ liệu mới
if len(items) == current_items_count:
no_new_items_count += 1
else:
no_new_items_count = 0
count_items = len(items)
self.status_updated.emit(self.window.translate("FetchDataThread_fetched_items", count_items=count_items, data_type=data_type))
except Exception as e:
self.status_updated.emit(self.window.translate("FetchDataThread_fetching_failed", data_type=data_type, e=str(e)))
break # Thoát nếu có lỗi
# Cập nhật giao diện hoặc lưu dữ liệu
if data_type == "groups":
self.window.settings["groups"] = list(items)
elif data_type == "members":
self.window.settings["members"] = list(items)
self.window.save_settings()
count_items = len(items)
self.status_updated.emit(self.window.translate("FetchDataThread_fetch_completed", data_type=data_type, count_items=count_items))
self.items = list(items)
return list(items)
def smooth_scroll_to_position(self, driver, target_y, duration=2):
# Giữ nguyên hàm smooth_scroll_to_position từ PostingThread
current_y = driver.execute_script("return window.pageYOffset;")
distance = target_y - current_y
if distance == 0 or stop_event.is_set():
return
step = 100 if distance > 0 else -100
steps_count = abs(distance) // abs(step)
if steps_count == 0:
steps_count = 1
sleep_time = duration / steps_count
while (distance > 0 and current_y < target_y) or (distance < 0 and current_y > target_y):
if stop_event.is_set():
break
current_y += step
if (distance > 0 and current_y > target_y) or (distance < 0 and current_y < target_y):
current_y = target_y
driver.execute_script(f"window.scrollTo(0, {current_y});")
time.sleep(sleep_time)
driver.execute_script(f"window.scrollTo(0, {target_y});")
class PostingThread(QThread):
status_updated = Signal(str)
content_updated = Signal(str)
stop_requested = Signal()
def __init__(self, window, location, valid_urls, parent=None):
super().__init__(parent)
self.window = window
self.location = location
self.valid_urls = valid_urls
self.driver = self.window.driver
def run(self):
if self.driver is None:
self.status_updated.emit(self.window.translate("LoginThread_driver_is_not_initialized"))
return
self.post_to_location(self.driver, self.location, self.valid_urls)
# Hàm đọc danh sách ID đã gửi từ file CSV
def is_id_sent(self, user_id):
"""Kiểm tra xem user_id đã được gửi tin nhắn chưa"""
if os.path.exists("sent_ids.csv"):
with open("sent_ids.csv", "r", encoding="utf-8") as file:
sent_ids = {line.strip() for line in file}
return user_id in sent_ids
return False
# Hàm lưu ID đã gửi vào file CSV
def save_sent_id(self, user_id):
"""Lưu user_id vào tệp sent_ids.csv"""
with open("sent_ids.csv", "a", encoding="utf-8") as file:
file.write(f"{user_id}\n")
def upload_images(self, driver, image_folder):
if stop_event.is_set():
return
image_paths = [os.path.join(image_folder, filename) for filename in os.listdir(image_folder)
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp'))]
if self.window.random_image_check.isChecked():
# Chọn ngẫu nhiên từ 1 đến số lượng hình ảnh có sẵn
num_images = random.randint(1, len(image_paths))
image_paths = random.sample(image_paths, num_images)
for image_path in image_paths:
upload_input = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "//div[@aria-labelledby and @role='dialog']//form[@method='POST']//input[contains(@accept, 'image/*,image/heif,image/heic,video') and @class='x1s85apg' and @multiple and @type='file']"))
)
upload_input.send_keys(image_path)
time.sleep(1)
def post_to_location(self, driver, location, urls):
failed_urls = []
image_folder = self.window.image_folder_entry.text().strip()
encrypt_code = self.window.encrypt_message_code_input.text().strip()
prompt = self.window.prompt_entry.toPlainText().strip()
content = None # Khởi tạo content
failed_times = 0
# Kiểm tra từng loại file
has_images = any(glob.glob(os.path.join(image_folder, ext)) for ext in image_extensions)
has_audio = any(glob.glob(os.path.join(image_folder, ext)) for ext in audio_extensions)
has_video = any(glob.glob(os.path.join(image_folder, ext)) for ext in video_extensions)
for url in urls:
if stop_event.is_set():
self.status_updated.emit(self.window.translate("PostingThread_stopping"))
return
driver.get(url)
time.sleep(5)
# Tạo nội dung mới nếu bật tự động
if self.window.auto_generate_check.isChecked():
try:
content = self.window.generate_content_ai(self.window.server_combo.currentText(),
self.window.model_combo.currentText(),
prompt)
# Kiểm tra nội dung có hợp lệ hay không
if any(err in content.lower() for err in ["balance", "error", "api key is not set", "máy chủ không hỗ trợ"]):
raise ValueError(self.status_updated.emit(self.window.translate("PostingThread_generated_content_error")))
# Cập nhật ô xem trước với nội dung hợp lệ
self.content_updated.emit(content)
except Exception as e:
self.status_updated.emit(self.window.translate("PostingThread_error_during_generate_content", e=str(e)))
content = self.window.get_random_content_from_json()
if not content:
self.status_updated.emit(self.window.translate("PostingThread_not_found_backup_content"))
# self.window.stop_posting()
self.stop_requested.emit()
return
self.content_updated.emit(content)
else:
# Nếu không tự động tạo, lấy nội dung từ ô nhập tay (nếu có)
content = self.window.content_preview.toPlainText().strip()
if not content: # Kiểm tra nếu nội dung rỗng
content = self.window.get_random_content_from_json()
if not content:
self.status_updated.emit(self.window.translate("PostingThread_content_is_empty"))
# self.window.stop_posting()
self.stop_requested.emit()
return
self.content_updated.emit(content)
try:
if location == self.window.translate("group_location_position_option"):
group_id = url.rstrip("/").split("/")[-1]
#Tìm tên nhóm
try:
group_title_element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "//h2[@dir='auto']//span[@dir='auto']//a[@tabindex='0' and @role='link' and contains(@href, 'https://')]"))
)
group_title = group_title_element.text
except:
group_title = url
try:
# Nhấn vào nút đăng bài
post_box_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, r"//div[contains(@style, 'border-radius')]//div[@role='button' and @tabindex='0']//span[@class and @style]")) # Tìm ô đăng bài để nhấp vào ngay trên trang chủ của nhóm
)
except TimeoutException:
self.status_updated.emit(self.window.translate("PostingThread_posting_dialog_button_not_found", group_title=group_title, group_id=group_id))
failed_urls.append(url)
continue
post_box_button.click()
try:
# Xác định ô đăng bài
post_box = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, r"//div[@aria-labelledby and @role='dialog']//form[@method='POST']//div[@class and @contenteditable='true' and @role='textbox' and @spellcheck='true' and @tabindex='0' and @data-lexical-editor='true' and @aria-placeholder]"))
)
except TimeoutException:
self.status_updated.emit(self.window.translate("PostingThread_posting_dialog_not_found", group_title=group_title, group_id=group_id))
failed_urls.append(url)
continue
post_box.send_keys(content)
# Chờ đến khi toàn bộ nội dung được nhập
timeout = 10 # Giới hạn thời gian chờ (10 giây)
start_time = time.time()
while time.time() - start_time < timeout:
entered_text = post_box.get_attribute("innerText") # Lấy nội dung đã nhập
if entered_text.strip() == content.strip(): # So sánh nội dung đã nhập với nội dung gốc
break
time.sleep(0.5) # Đợi thêm một chút rồi kiểm tra lại
if (has_images or has_audio or has_video) and not stop_event.is_set():
# Xác định nút đính kèm hình ảnh và click vào đó
immages_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, r"//div[@aria-labelledby and @role='dialog']//form[@method='POST']//div[contains(@aria-label, '/video') and @role='button' and @tabindex='0']//img[contains(@src, '.png') and @alt and @style]"))
)
immages_button.click()
if image_folder:
self.upload_images(driver, image_folder)
try:
# Nút đăng
post_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//div[@aria-labelledby and @role='dialog']//form[@method='POST']//div[@aria-label]//div[@role='none']//span[@dir='auto']"))
)
except TimeoutException:
self.status_updated.emit(self.window.translate("PostingThread_posting_button_not_found", group_title=group_title, group_id=group_id))
failed_urls.append(url)
continue
post_button.click()
# Facebook không cho phép đăng bài
try:
WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((
By.XPATH,
"//div[@data-visualcompletion='ignore-dynamic' and @style]//div[@aria-disabled='false' and @class='x1lq5wgf xgqcy7u x30kzoy x9jhf4c x1lliihq']//span[@dir='auto' and contains(@class, 'x193iq5w xeuugli x13faqbe x1vvkbs x1xmvt09 x1lliihq') and @id]//div[contains(@class, 'x1i10hfl xjbqb8w x1ejq31n xd10rxx x1sy0etr x17r0tee x972fbf') and @role='button' and @tabindex='0']"
))
)
self.status_updated.emit(self.window.translate("PostingThread_failed_to_post", group_title=group_title, group_id=group_id))
failed_urls.append(url)
continue
except TimeoutException:
pass
try:
#Chờ đăng bài thành công và ô đăng bài biến mất
WebDriverWait(driver, 60).until(
EC.invisibility_of_element_located((By.XPATH, r"//div[@aria-labelledby and @role='dialog']//form[@method='POST']//div[contains(@aria-label, '/video') and @role='button' and @tabindex='0']"))
)
except TimeoutException:
self.status_updated.emit(self.window.translate("PostingThread_posting_dialog_not_disappear", group_title=group_title, group_id=group_id))
failed_urls.append(url)
continue
self.status_updated.emit(self.window.translate("PostingThread_post_successful", group_title=group_title, group_id=group_id))
# Xóa URL khỏi url_items_list và lưu settings
self.window.remove_url_from_list(url)
self.window.save_settings()
elif location == "Marketplace":
listing_type = self.window.listing_type_combo.currentText()
for _ in range(self.window.marketplace_post_count): # Dự phòng cho số lần đăng
self.post_marketplace_item(driver, f"https://facebook.com/marketplace/create/{listing_type}")
elif location == self.window.translate("pages_location_position_option") or location == "Pages":
post_box = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "//div[@role='textbox']"))
)
post_box.click()
post_box.send_keys(content)
if image_folder:
self.upload_images(driver, image_folder)
post_button = driver.find_element(By.XPATH, "//button[@type='submit']")
post_button.click()
elif location == self.window.translate("members_location_position_option") or location == "Send message to group members":
if failed_times >= 3:
self.status_updated.emit(self.window.translate("PostingThread_blocked_posting"))
break
# Kiểm tra xem ID đã gửi chưa
user_id = url.split("/")[-1] # Lấy user_id từ url (ví dụ: 132013598798057)
if self.is_id_sent(user_id):
self.status_updated.emit(self.window.translate("PostingThread_skip_member", url=url))
continue # Bỏ qua nếu đã gửi
#Tìm tên người dùng
try:
user_name_element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "//div[contains(@class, 'x9f619 x1n2onr6 x1ja2u2z x78zum5 xdt5ytf x193iq5w')]//h2[@dir='auto' and contains(@class, 'html-h2 xdj266r x11i5rnm xat24cr x1mh8g0r xexx8yu')]//span[contains(@class, 'html-span xdj266r x11i5rnm xat24cr x1mh8g0r xexx8yu x4uap5')]"))
)
user_name = user_name_element.text
except:
user_name = url
#Kiểm tra xem có xuất hiện yêu cầu nhập mã hóa tin nhắn đầu cuối hay không
try:
encrypt_dialog_input = driver.find_element(By.XPATH, r"//input[@class and @dir='ltr' and @autocomplete='one-time-code' and @id='mw-numeric-code-input-prevent-composer-focus-steal' and @maxlength='6' and @type='text' and @value and @tabindex='0']")
if encrypt_dialog_input:
encrypt_dialog_input.send_keys(encrypt_code)
WebDriverWait(driver, 30).until_not(
EC.presence_of_element_located((By.XPATH, r"//input[@class and @dir='ltr' and @autocomplete='one-time-code' and @id='mw-numeric-code-input-prevent-composer-focus-steal' and @maxlength='6' and @type='text' and @value and @tabindex='0']"))
)
except:
pass
# Nút tiếp tục mã hoá tin nhắn đầu cuối
try:
continue_encrypt_button = driver.find_element(By.XPATH, r"//div[@aria-label and @role='button' and @tabindex='0']//div[@role='none']//span[@dir='auto']")
if continue_encrypt_button:
continue_encrypt_button.click()
except:
pass
try:
# Xác định ô tin nhắn
message_box = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, r"//div[@aria-placeholder and @role='textbox' and @spellcheck='true' and @contenteditable='true' and @aria-label and @aria-describedby and @data-lexical-editor='true']"))
)
message_box.send_keys(content)
except:
self.status_updated.emit(self.window.translate("PostingThread_not_found_input_message_box", user_name=user_name, user_id=user_id))
failed_urls.append(url)
continue
# Chờ đến khi toàn bộ nội dung được nhập
timeout = 30 # Giới hạn thời gian chờ (30 giây)
start_time = time.time()
while time.time() - start_time < timeout:
entered_text = message_box.get_attribute("innerText") # Lấy nội dung đã nhập
if entered_text.strip() == content.strip(): # So sánh nội dung đã nhập với nội dung gốc
break
time.sleep(0.5) # Đợi thêm một chút rồi kiểm tra lại
try:
# Xác định nút gửi tin nhắn và click vào đó
send_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, r"//div[@role='button' and @tabindex='0' and contains(@aria-label, 'Enter')]"))
)
except:
self.status_updated.emit(self.window.translate("PostingThread_not_found_send_button", user_name=user_name, user_id=user_id))
failed_urls.append(url)
continue
send_button.click()
# Chờ đến khi toàn bộ nội dung được nhập
timeout = 30 # Giới hạn thời gian chờ (30 giây)
start_time = time.time()
while time.time() - start_time < timeout:
entered_text = message_box.get_attribute("innerText") # Lấy nội dung đã nhập
if entered_text.strip() == "": # Kiểm tra xem nội dung đã được gửi hết chưa
break
time.sleep(2) # Đợi thêm một chút rồi kiểm tra lại
# Facebook không cho gửi tin nhắn
WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((
By.XPATH,
"//div[contains(@class, 'html-div xdj266r x11i5rnm xat24cr x1mh8g0r xexx8yu')]//span[@role='presentation' and contains(@class, 'html-span x1mh8g0r x1hl2dhg x16tdsg8 x1vvkbs x1eb86dx')]//span[contains(@class, 'html-span xdj266r x11i5rnm xat24cr x1mh8g0r xexx8yu')]"
))
)
sending_status_elements = driver.find_elements(By.XPATH, "//div[contains(@class, 'html-div xdj266r x11i5rnm xat24cr x1mh8g0r xexx8yu')]//span[@role='presentation' and contains(@class, 'html-span x1mh8g0r x1hl2dhg x16tdsg8 x1vvkbs x1eb86dx')]//span[contains(@class, 'html-span xdj266r x11i5rnm xat24cr x1mh8g0r xexx8yu')]")
last_sending_status = sending_status_elements[-1]
if last_sending_status.text in ["không thể", "unable", "can not", "can't"]:
self.status_updated.emit(self.window.translate("PostingThread_failed_to_send_message", user_name=user_name, user_id=user_id))
failed_urls.append(url)
failed_times += 1
continue
# Chờ cho nút gửi biến mất
WebDriverWait(driver, 60).until(
EC.invisibility_of_element_located((By.XPATH, r"//div[@role='button' and @tabindex='0' and contains(@aria-label, 'Enter')]"))
)
try:
#Chờ gửi tin nhắn thành công và nút gửi tin nhắn biến mất
WebDriverWait(driver, 60).until(
EC.invisibility_of_element_located((By.XPATH, r"//div[@role='button' and @tabindex='0' and contains(@aria-label, 'Enter')]"))
)
except TimeoutException:
self.status_updated.emit(self.window.translate("PostingThread_send_button_not_disappear", user_name=user_name, user_id=user_id))
failed_urls.append(url)
continue
time.sleep(3)
self.status_updated.emit(self.window.translate("PostingThread_send_successful", user_name=user_name, user_id=user_id))
# Xóa URL khỏi url_items_list và lưu settings
self.window.remove_url_from_list(url)
self.window.save_settings()
# Lưu user_id vào tệp CSV
self.save_sent_id(user_id)
self.status_updated.emit(self.window.translate("PostingThread_saved_id_to_file", user_id=user_id))
time.sleep(5)
except Exception as e:
self.status_updated.emit(self.window.translate("PostingThread_failed_to_post_location", url=url, e=str(e)))
failed_urls.append(url)
# self.window.stop_posting() # Dừng đăng bài
self.stop_requested.emit()
if failed_urls:
self.status_updated.emit(self.window.translate("PostingThread_all_locations_posted_fail"))
for failed_url in failed_urls:
self.status_updated.emit(f"- {failed_url}")
else:
self.status_updated.emit(self.window.translate("PostingThread_all_locations_posted_successful"))
return
def post_marketplace_item(self, driver, url):
driver.get(url)
time.sleep(5)
if 'additional_profile/dialog/marketplace_mitigation' in driver.current_url():
try:
switch_primary_account_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//div[@aria-label and @role='button' and @tabindex='0']//div[@role='none' and contains(@class, 'x9f619 x1n2onr6 x1ja2u2z x193iq5w xeuugli x6s0dn4 x78zum5')]//span[contains(@class, 'x193iq5w xeuugli x13faqbe x1vvkbs x1xmvt09 x1lliihq x1s928wv') and @dir='auto']"))
)
switch_primary_account_button.click()
self.status_updated.emit(self.window.translate("PostingThread_switched_to_primary_account"))
time.sleep(5)
driver.get(url)
except Exception as e:
self.status_updated.emit(self.window.translate("PostingThread_error_while_pressing_button",e=str(e)))
title_box = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "//input[@placeholder='What are you selling?']"))
)
title_box.send_keys(content[:50])
price_box = driver.find_element(By.XPATH, "//input[@placeholder='Price']")
price_box.send_keys("0")
if image_folder:
self.upload_images(driver, image_folder)
publish_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Publish')]"))
)
publish_button.click()
# Thêm logic đăng bài Marketplace ở đây
# Hiện tại chỉ đăng 1 bài nhưng có thể mở rộng bằng vòng lặp
class UpdateChecker(QThread):
update_status = Signal(str)
def __init__(self, window, parent=None):
super().__init__(parent)
self.window = window
self.current_version = version
def run(self):
try:
response = requests.get("https://api.github.com/repos/tekdt/AutoPostFacebookGroupSimple/releases/latest")
latest_version = response.json()["name"].lstrip("v")
if latest_version > self.current_version:
self.update_status.emit(self.window.translate("UpdateChecker_new_version", latest_version=latest_version))
else:
self.update_status.emit(self.window.translate("UpdateChecker_last_version"))
except Exception as e:
self.update_status.emit(self.window.translate("UpdateChecker_error_checking", e=str(e)))
class MainWindow(QMainWindow):
ai_servers = {