Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from selenium import webdriver
- from selenium.webdriver.common.keys import Keys
- from selenium.webdriver.common.by import By
- import time
- import os
- import pickle
- class TwitterBot:
- def __init__(self):
- self.driver = webdriver.Chrome() # You can use any browser driver you prefer
- self.base_url = "https://twitter.com"
- self.cookie_filename = "twitter_cookies.pkl"
- def login(self):
- self.driver.get(self.base_url)
- if os.path.exists(self.cookie_filename):
- self.load_cookies()
- else:
- input("Please log in manually and press Enter once you're on the home page...")
- self.save_cookies()
- def load_cookies(self):
- with open(self.cookie_filename, 'rb') as f:
- cookies = pickle.load(f)
- for cookie in cookies:
- self.driver.add_cookie(cookie)
- self.driver.get(self.base_url)
- def save_cookies(self):
- cookies = self.driver.get_cookies()
- with open(self.cookie_filename, 'wb') as f:
- pickle.dump(cookies, f)
- def post_tweet(self, text, media_paths=[]):
- self.driver.get(self.base_url)
- tweet_box = self.driver.find_element(By.XPATH, '//div[@role="textbox"]')
- tweet_box.send_keys(text)
- if media_paths:
- media_button = self.driver.find_element(By.XPATH, '//input[@data-testid="fileInput"]')
- for media_path in media_paths:
- media_path = os.path.abspath(media_path)
- media_button.send_keys(media_path)
- tweet_button = self.driver.find_element(By.XPATH, '//div[@data-testid="tweetButtonInline"]')
- tweet_button.click()
- def close(self):
- self.driver.quit()
- if __name__ == "__main__":
- bot = TwitterBot()
- try:
- bot.login()
- media_folder = "media_folder" # Replace with the actual folder containing media files
- media_files = [f for f in os.listdir(media_folder) if os.path.isfile(os.path.join(media_folder, f)) and not f.endswith("posted")]
- for media_file in media_files:
- media_path = os.path.join(media_folder, media_file)
- # Read tweet text from corresponding .txt file
- tweet_text_path = os.path.join(media_folder, f"{os.path.splitext(media_file)[0]}.txt")
- if os.path.exists(tweet_text_path):
- with open(tweet_text_path, "r") as tweet_file:
- tweet_text = tweet_file.read().strip()
- else:
- tweet_text = "Default tweet text" # Provide a default if no .txt file is found
- bot.post_tweet(tweet_text, [media_path])
- # Rename the file to indicate that it's been posted
- new_media_path = os.path.join(media_folder, media_file.replace(".","_posted."))
- os.rename(media_path, new_media_path)
- time.sleep(5) # Adjust as needed
- except Exception as e:
- print("An error occurred:", e)
- finally:
- bot.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement