testsss / main.py
alptangall's picture
Update main.py
a0dfd57 verified
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import time,os,sys
import pickle
from random import randrange
import subprocess
from datetime import datetime,timedelta
import requests
import server
import gradio as gr
def greet(name):
return "Hello " + name + "!!"
VIDEO_OUTPUT_DIR = "output_videos"
MAIN_SCRIPT_PATH = "reddit.py"
profile_path = "./tiktok_profile"
cookie_file = "cookies.pkl"
def create_video():
print("Bắt đầu tạo video...")
folder_path = '/home/user/app'
# Lấy danh sách các tệp trong thư mục
files = os.listdir(folder_path)
# Lọc chỉ những tệp (không phải thư mục)
files = [f for f in files if os.path.isfile(os.path.join(folder_path, f))]
print(files)
with open("test.log", "wb") as f:
process = subprocess.Popen(['python','/home/user/app/reddit.py'], stdout=subprocess.PIPE)
for c in iter(lambda: process.stdout.read(1), b""):
sys.stdout.buffer.write(c)
try:
f.buffer.write(c)
except:
continue
'''result = subprocess.run(["python", MAIN_SCRIPT_PATH], capture_output=True, text=True)
if result.returncode != 0:
print(f"Lỗi khi tạo video: {result.stderr}")
return None'''
print("Video đã được tạo thành công.")
# Giả sử script của bạn tạo ra file "final_video.mp4"
if not os.path.exists("final_video.mp4"):
print("Không tìm thấy file final_video.mp4")
return None
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
new_video_name = f"video_{timestamp}.mp4"
new_video_path = os.path.join(VIDEO_OUTPUT_DIR, new_video_name)
try:
os.rename("final_video.mp4", new_video_path)
print(f"Đã đổi tên video thành: {new_video_name}")
return new_video_path
except Exception as e:
print(f"Lỗi khi đổi tên file: {e}")
return None
def save_cookies(driver, location):
with open(location, "wb") as filehandler:
pickle.dump(driver.get_cookies(), filehandler)
print(f"Cookie đã được lưu tại {location}")
# Nạp cookie đã lưu để tái sử dụng
def load_cookies(driver, location):
if os.path.exists(location):
with open(location, "rb") as cookiesfile:
cookies = pickle.load(cookiesfile)
for cookie in cookies:
driver.add_cookie(cookie)
print(f"Cookie đã được nạp từ {location}")
def swipe_to_next_video(driver):
# Lấy kích thước hiện tại của cửa sổ trình duyệt
window_height = driver.execute_script("return window.innerHeight")
# Sử dụng ActionChains để thực hiện thao tác vuốt từ dưới lên
actions = ActionChains(driver)
# Vuốt từ vị trí gần cuối màn hình lên vị trí đầu màn hình
actions.move_by_offset(0, window_height * 0.8).click_and_hold().move_by_offset(0, -window_height * 0.8).release().perform()
print("Đã chuyển sang video tiếp theo.")
def create_driver_with_emulation(is_mobile):
chrome_options = Options()
# Nếu is_mobile = True, bật chế độ giả lập smartphone
if is_mobile:
user_agent = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1"
mobile_emulation = {
"deviceMetrics": {"width": 375, "height": 812, "pixelRatio": 3.0},
"userAgent": user_agent
}
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
else:
# Không bật emulation - sử dụng trình duyệt thông thường
chrome_options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=chrome_options)
return driver
def main():
if not os.path.exists(VIDEO_OUTPUT_DIR):
os.makedirs(VIDEO_OUTPUT_DIR)
current_video = None
stream_process = None
while True:
print("Đang tạo video mới...")
new_video_path = create_video()
if new_video_path and os.path.exists(new_video_path):
print(f"Video mới đã được tạo: {new_video_path}")
# Bắt đầu phát trực tiếp video mới
# Cấu hình Chrome Options
chrome_options = Options()
# Bỏ qua các chứng chỉ SSL không hợp lệ
chrome_options.add_argument("--headless=new")
chrome_options.add_argument("--ignore-certificate-errors")
chrome_options.add_argument("--ignore-ssl-errors=yes")
chrome_options.add_argument("--allow-insecure-localhost")
# Thiết lập user agent cho iPhone 15, iOS 18
user_agent = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1"
chrome_options.add_argument(f"user-agent={user_agent}")
# Bật chế độ giả lập giao diện smartphone
mobile_emulation = {
"deviceMetrics": {"width": 375, "height": 812, "pixelRatio": 3.0},
"userAgent": user_agent
}
#chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
# Khởi tạo trình duyệt Chrome với cấu hình trên
driver = webdriver.Chrome(options=chrome_options)
# Truy cập TikTok
driver.get("https://www.tiktok.com/?lang=en") # Mở trang trước khi nạp cookie
try:
# Kiểm tra nếu tồn tại thẻ div với id = 'login-modal'
login_modal = driver.find_element(By.ID, "login-modal")
# Nếu tồn tại, tìm thẻ div với class = 'css-15c21yv-DivCloseWrapper' bên trong login-modal
close_button = login_modal.find_element(By.CLASS_NAME, "css-15c21yv-DivCloseWrapper")
# Click vào button đóng
close_button.click()
print("Đã click vào nút đóng.")
except NoSuchElementException:
print("Không tìm thấy thẻ 'login-modal' hoặc nút đóng.")
if os.path.exists(cookie_file):
# Nạp lại cookie đã lưu
load_cookies(driver, cookie_file)
driver.refresh() # Tải lại trang để áp dụng cookie
try:
# Kiểm tra nếu tồn tại thẻ div với id = 'login-modal'
login_modal = driver.find_element(By.ID, "login-modal")
# Nếu tồn tại, tìm thẻ div với class = 'css-15c21yv-DivCloseWrapper' bên trong login-modal
close_button = login_modal.find_element(By.CLASS_NAME, "css-15c21yv-DivCloseWrapper")
# Click vào button đóng
close_button.click()
print("Đã click vào nút đóng.")
except NoSuchElementException:
print("Không tìm thấy thẻ 'login-modal' hoặc nút đóng.")
else:
driver.get("https://www.tiktok.com/profile")
time.sleep(3)
try:
# Kiểm tra nếu tồn tại thẻ div với id = 'login-modal'
login_modal = driver.find_element(By.ID, "login-modal")
# Nếu tồn tại, tìm thẻ div với class = 'css-15c21yv-DivCloseWrapper' bên trong login-modal
close_button = login_modal.find_element(By.CLASS_NAME, "css-15c21yv-DivCloseWrapper")
# Click vào button đóng
close_button.click()
print("Đã click vào nút đóng.")
except NoSuchElementException:
print("Không tìm thấy thẻ 'login-modal' hoặc nút đóng.")
# Click vào button nằm trong div có id='user-page'
time.sleep(5)
try:
user_page_div = driver.find_element(By.ID, "user-page")
button = user_page_div.find_element(By.TAG_NAME, "button") # Tìm thẻ button bên trong div
button.click()
print("Đã click vào nút trong div có id='user-page'.")
except NoSuchElementException:
print("Không tìm thấy div có id='user-page' hoặc nút bên trong.")
# Click vào div đầu tiên trong div class='tiktok-7pnfyo-DivLoginOptionContainer exd0a434'
time.sleep(3)
try:
login_options = driver.find_element(By.CLASS_NAME, "tiktok-7pnfyo-DivLoginOptionContainer.exd0a434")
first_option = login_options.find_elements(By.TAG_NAME, "div")[1] # Lấy div đầu tiên
first_option.click()
print("Đã click vào tùy chọn đăng nhập đầu tiên.")
except NoSuchElementException:
print("Không tìm thấy div tùy chọn đăng nhập.")
# Click vào div có thuộc tính data-e2e="email-tab"
time.sleep(3)
try:
email_tab = driver.find_element(By.CSS_SELECTOR, 'div[data-e2e="email-tab"]')
email_tab.click()
print("Đã click vào tab email.")
except NoSuchElementException:
print("Không tìm thấy div có thuộc tính data-e2e='email-tab'.")
# Nhập giá trị vào input name='username'
time.sleep(3)
try:
username_input = driver.find_element(By.NAME, 'username')
username_input.send_keys('pdmega1@gmail.com')
print("Đã nhập username.")
except NoSuchElementException:
print("Không tìm thấy input với name='username'.")
# Nhập giá trị vào input type='password'
try:
password_input = driver.find_element(By.CSS_SELECTOR, 'input[type="password"]')
password_input.send_keys('123123_Qwe')
print("Đã nhập password.")
except NoSuchElementException:
print("Không tìm thấy input với type='password'.")
# Click button type='submit'
time.sleep(3)
try:
submit_button = driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]')
submit_button.click()
print("Đã click vào nút submit.")
except NoSuchElementException:
print("Không tìm thấy button với type='submit'.")
# Đợi một chút để kiểm tra kết quả (tuỳ chọn)
time.sleep(300)
driver.get('https://www.tiktok.com/?lang=en')
save_cookies(driver, cookie_file)
time.sleep(3)
driver.quit()
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://www.tiktok.com/tiktokstudio/upload?from=upload&lang=en")
load_cookies(driver, cookie_file)
driver.refresh() # Tải lại trang để áp dụng cookie
# Truy cập trang TikTok Studio Upload
time.sleep(15)
# Đường dẫn tới file mp4 trong thư mục gốc
file_path = os.path.abspath(new_video_path) # Thay 'your_video.mp4' bằng tên file MP4 của bạn
# Tìm phần tử input file và gửi đường dẫn file MP4
file_input = driver.find_element(By.CSS_SELECTOR,'input[type="file"]')
file_input.send_keys(file_path)
'''for _ in range(5): # Thực hiện 5 lần vuốt sang video mới (có thể thay đổi số lần)
swipe_to_next_video(driver)
time.sleep(randrange(3,8)) # Đợi vài giây để video mới tải xong trước khi vuốt tiếp
'''
time.sleep(3)
while True:
try:
# Replace 'uploadCompleteElement' with a selector that indicates upload completion
submit_button=driver.find_element(By.XPATH, "(//button[@class='TUXButton TUXButton--default TUXButton--large TUXButton--primary'])[1]")
if submit_button.is_enabled():
print("Nút Submit đã sẵn sàng.")
break
except Exception as e:
print(f"An error occurred: {e}")
time.sleep(5)
try:
wait = WebDriverWait(driver, 10)
radio_button = wait.until(EC.element_to_be_clickable((By.XPATH, "(//input[@type='radio'])[2]")))
radio_button.click()
except NoSuchElementException:
print('Khong tim thay element')
time.sleep(3)
try:
allowBtn=driver.find_element(By.CLASS_NAME,'TUXButton TUXButton--default TUXButton--medium TUXButton--primary')
allowBtn.click()
print('Click Allow btn success')
except NoSuchElementException:
print('Khong tim thay allowBtn')
time.sleep(3)
#inputDate.send_keys('2024-10-13')
#input_field = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, ":r35:")))
date=datetime.now()+ timedelta(hours=24)
driver.find_elements(By.CSS_SELECTOR,"input.TUXTextInputCore-input")[0].click()
time.sleep(3)
time_picker=driver.find_elements(By.CSS_SELECTOR,'div.tiktok-timepicker-time-scroll-container.tiktok-timepicker-disable-scrollbar')
for el in time_picker[0].find_elements(By.CSS_SELECTOR,'div.tiktok-timepicker-option-item'):
if f'{date.hour}' in el.text:
el.click()
for el in time_picker[1].find_elements(By.CSS_SELECTOR,'div.tiktok-timepicker-option-item'):
if f'{date.minute}' in el.text:
el.click()
driver.find_elements(By.CSS_SELECTOR,"input.TUXTextInputCore-input")[1].click()
time.sleep(3)
date_picker=driver.find_elements(By.CLASS_NAME,'calendar-wrapper')[0].find_elements(By.TAG_NAME,'span')
for el in date_picker:
if f'{date.day}' in el.text:
el.click()
break
try:
locationSelect=driver.find_element(By.ID,'poi')
if locationSelect:
driver.execute_script("document.getElementById('poi').value ='United States';")
time.sleep(3)
except NoSuchElementException:
print('khong tim thay element')
content =driver.find_element(By.CLASS_NAME, 'DraftEditor-editorContainer')
content.click()
actions = ActionChains(driver)
actions.key_down(Keys.CONTROL).send_keys('a').key_up(Keys.CONTROL).perform()
with open('titles.txt', 'r') as file:
lines = file.readlines()
hastags='''#HurricaneMilton
#HurricaneNadine
#Category5
#FloridaStorm
#ExtremeWeather
#StormPreparedness
#DisasterRelief
#FloridaEvacuation
#StormUpdate
#ViralHurricaneStory'''
actions.send_keys("What are you watching? #news #today #goodnews #good #goodnews.us "+hastags).perform()
actions.send_keys(Keys.SHIFT, Keys.ENTER)
actions.send_keys("Delicious menu :notepad_spiral:").perform()
actions.send_keys(Keys.SHIFT, Keys.ENTER)
for i,line in enumerate(lines,start=1):
actions.send_keys(f'#{i} - '+line).perform()
actions.send_keys(Keys.SHIFT, Keys.ENTER)
print("Đã nhấn tổ hợp phím 123.")
time.sleep(3)
try:
wait = WebDriverWait(driver, 30)
submitButton = wait.until(EC.element_to_be_clickable((By.XPATH, "(//button[@class='TUXButton TUXButton--default TUXButton--large TUXButton--primary'])[1]")))
submitButton.click()
print('Video submited')
'''while True:
try:
# Replace 'uploadCompleteElement' with a selector that indicates upload completion
submit_button=WebDriverWait(driver, 10).until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, "div.TUXButton-label"), "Manage posts"))
if submit_button:
print("Ready to quit")
break
except Exception as e:
print(f"An error occurred: {e}")
time.sleep(5)'''
except NoSuchElementException:
print('Khong tim thay element')
if __name__ == "__main__":
try:
req=requests.get('http://localhost:8888')
print(req.status_code)
print('Client closed')
exit()
except Exception as err:
print(err)
#server.b()
while True:
main()
time.sleep(randrange(120,360))
# Đóng trình duyệt sau khi hoàn thành
# driver.quit()
# Đóng trình duyệt sau khi hoàn thành
# driver.quit()