Untitled
unknown
python
2 years ago
3.3 kB
11
Indexable
import os
import requests
import time
# Replace the following with your own Facebook access token and page ID
ACCESS_TOKEN = "EAAzZBurE5LlABOZBo1OmOWOA5ENde9w9M9g0ZBT91PZBYSB4FSt8JTmNZA2eEjfNcokuOTRDAuXfgch0NWaAbAQDGWQOb5bDStGQZADBlW6ShQoZBMKa6ra88qAtlp7gX81LpFkPhbMeqDqrxVnTlFF8B9ZCqPbH7pAl8wnSuOAhfCzLJeYUns9YZAJuyfjhedw4D66ciSEtrFi5s17LrCnqhNKM92W6x"
PAGE_ID = "100000962091037"
# Get the absolute path to the images folder
IMAGES_FOLDER_PATH = os.path.abspath("images")
# Print the path to the images folder
print("Images folder path:", IMAGES_FOLDER_PATH)
# Get a list of all the files in the images folder
files = os.listdir(IMAGES_FOLDER_PATH)
# Print the number of images in the folder
print("Number of images:", len(files))
# Get the drive letter and path to the images folder
drive_letter, images_folder_path = os.path.splitdrive(IMAGES_FOLDER_PATH)
# Print the drive letter and path to the images folder
print("Drive letter:", drive_letter)
print("Path to images folder:", images_folder_path)
# Create a set to store the filenames of the images that have already been posted
posted_image_filenames = set()
def post_picture_to_facebook(file_path):
"""Posts a picture to Facebook.
Args:
file_path: The path to the picture file.
"""
files = {
"filename": open(file_path, "rb")
}
payload = {
"access_token": ACCESS_TOKEN,
"source": files["filename"]
}
url = "https://graph.facebook.com/{}/photos".format(PAGE_ID)
response = requests.post(url, data=payload, files=files)
print("Path to image file:", file_path)
print("Response from Facebook API:", response.content)
if response.status_code == 200:
print("Picture posted successfully!")
# Add the filename of the posted image to the set
posted_image_filenames.add(file_path)
else:
print("Error posting picture:", response.content)
def watch_folder_for_new_files():
"""Watches the specified folder for new files and posts them to Facebook.
"""
last_checked = time.time()
while True:
# Get a list of all the files in the folder
files = os.listdir(IMAGES_FOLDER_PATH)
# Iterate over the files and post the ones that are new and have not been posted yet
for file in files:
# Get the absolute path to the file
file_path = os.path.abspath(os.path.join(IMAGES_FOLDER_PATH, file))
# Skip the file if it has already been posted
if file_path in posted_image_filenames:
continue
# Get the last modified time of the file
last_modified_time = os.path.getmtime(file_path)
# If the file is new or has been modified since the last check, post it to Facebook
if last_modified_time > last_checked:
print("New file added to folder:", file_path)
try:
post_picture_to_facebook(file_path)
except Exception as e:
print("Error posting picture:", e)
last_checked = time.time()
# Wait for 1 second before checking for new files again
time.sleep(1)
if __name__ == "__main__":
watch_folder_for_new_files()Editor is loading...