CoolFace
Apppublic

Kavin1/Facebook_automation

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
app.py1370 linesDownload Raw Back to root
1import os2import shutil3import streamlit as st4from selenium import webdriver5from selenium.webdriver.common.by import By6from selenium.webdriver.chrome.service import Service7from selenium.webdriver.support.ui import WebDriverWait8from selenium.webdriver.support import expected_conditions as EC9import time10from selenium.common.exceptions import TimeoutException11import openai12import facebook13from selenium.webdriver.chrome.options import Options14import requests15from openai import OpenAI16from monsterapi import client17import schedule18import threading19from datetime import datetime, timedelta20from selenium.webdriver.common.action_chains import ActionChains21from selenium.webdriver.common.keys import Keys22import pandas as pd23import pytz 24from datetime import datetime, timezone25import os26import streamlit as st27from selenium import webdriver28from selenium.webdriver.chrome.options import Options29from selenium.webdriver.chrome.service import Service30from selenium.webdriver.common.by import By31from selenium.webdriver.support.wait import WebDriverWait32import tempfile33from pymongo import MongoClient34from bs4 import BeautifulSoup35 36 37OPENAI_API_KEY = "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"38#MON_KEY = st.secrets['MON_KEY']39client1 = MongoClient("mongodb+srv://deepak:jLc4IM4dEdJLS7zc@cluster0.qfolmjg.mongodb.net/?retryWrites=true&w=majority")40db = client1["FBautomation"]41collection = db["Data"]42 43# write all the functions here and include @st.cache_resource(show_spinner=False) before def line44browsers=None45@st.cache_resource(show_spinner=False)        46def get_logpath():47    return os.path.join(os.getcwd(), 'selenium.log')48 49@st.cache_resource(show_spinner=False)50def get_chromedriver_path():51    return shutil.which('chromedriver')52 53@st.cache_resource(show_spinner=False)54def get_webdriver_options():55    options = Options()56    options.add_argument("--headless")57    options.add_argument("--no-sandbox")58    options.add_argument("--disable-dev-shm-usage")59    options.add_argument("--disable-gpu")60    options.add_argument("--disable-features=NetworkService")61    options.add_argument("--window-size=1920x1080")62    options.add_argument("--disable-features=VizDisplayCompositor")63    return options64 65 66def get_webdriver_service(logpath):67    service = Service(68        executable_path=get_chromedriver_path(),69        log_output=logpath,70    )71    return service72 73def delete_selenium_log(logpath):74    if os.path.exists(logpath):75        os.remove(logpath)76 77def show_selenium_log(logpath):78    if os.path.exists(logpath):79        with open(logpath) as f:80            content = f.read()81            st.code(body=content, language='log', line_numbers=True)82    else:83        st.warning('No log file found!')84 85def run_selenium(logpath):86    browsers=webdriver.Chrome(options=get_webdriver_options(), service=get_webdriver_service(logpath=logpath))87        88        89    return browsers90 91@st.cache_data(show_spinner=False)92def validate_user_credentials(username, password):93    # Replace this with your validation logic94    return username == "Skepitglobal" and password == "Skepitglobal"95 96@st.cache_data(show_spinner=False, experimental_allow_widgets=True)97#function that generates text content for facebook post using Chat GPT98def content_generator(restuarant_name, location, nature_of_cuisine, occasion, offer):99    prompt = f"You are a prompt engineering assistant. Create a Facebook post for resturant {restuarant_name} at location {location} and my nature of cuisine is {nature_of_cuisine} for the {occasion} occasion and we are giving flat {offer} discount  and add relevant tags. Generate content without user involvement and limit to 50 words"100    #Generate content for the Facebook post using GPT-3.5 Turbo101    clientopenai = OpenAI(api_key=OPENAI_API_KEY)102    response = clientopenai.chat.completions.create(103            model="gpt-3.5-turbo",104            messages=[105                {"role": "system", "content": "You are a prompt engineering assistant."},106                {"role": "user", "content": prompt},107            ]108        )109            #content=response['choices'][0]['message']['content']110    content= response.choices[0].message.content111    112    return content113 114    #modified_content=st.text_area("Generated Facebook Post Content", content)115 116 117 118#function that generates images using monster API    119 120@st.cache_data(show_spinner=False, experimental_allow_widgets=True)121def image_generator(other_keywords):122    max_wait_time=300123    api_key = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6IjMyYTZhMmFkZDhlMWIyODdjODI1NGM4MmU0OTVjM2UzIiwiY3JlYXRlZF9hdCI6IjIwMjQtMDEtMDRUMDY6MTg6NTQuNjMxODM4In0.LYY0PAaj4F0dj25V2elQaErz8u7pZJITnhL9qAc2lx8'  # Your API key here124    125    monster_client = client(api_key)126    model = 'sdxl-base'127    input_data = {128        'prompt': other_keywords,129        'negprompt': 'unreal, fake, meme, joke, disfigured, poor quality, bad, ugly, text, letters, numbers, humans',130        'samples': 2,131        'steps': 50,132        'aspect_ratio': 'square',133        'guidance_scale': 7.5,134        'seed': 2414,135        }136    result = monster_client.generate(model, input_data)137    138    139 140    image_urls = result['output']141    #image_urls = ["https://www.simplilearn.com/ice9/free_resources_article_thumb/Coca_Cola_Marketing_Strategy_2022.jpg"]142    return image_urls143 144 145@st.cache_resource(show_spinner=False, experimental_allow_widgets=True)146def save_uploaded_file(uploaded_file):147    temp_dir = tempfile.gettempdir()148    file_path = os.path.join(temp_dir, uploaded_file.name)149    with open(file_path, "wb") as f:150        f.write(uploaded_file.getvalue())151    return file_path152 153@st.cache_resource(show_spinner=False, experimental_allow_widgets=True)154def insert_data(username, password, access_token, page_id, App_name):155    user_data = {"username": username, "password": password, "access token": access_token, "page id": page_id,"App name": App_name}156    collection.insert_one(user_data)157    st.success("Data saved successfully.")158 159#function that displays content and defines the UI (Main)160def login_to_facebook(App_name,restuarant_name,location,nature_of_cuisine,occasion,offer,other_keywords):161    global browsers162 163    #facebook content generation164    st.subheader("Facebook Post Content Generation")165    content=content_generator(restuarant_name,location,nature_of_cuisine,occasion,offer)166    modified_content=st.text_area("Generated Facebook Post Content",content)167 168 169    #image generation170    image_urls= image_generator(other_keywords)171 172 173    # Display all images with buttons174    for i, image_url in enumerate(image_urls):175        st.image(image_url, caption=f'Image {i + 1}', use_column_width=True, width=200)176    selected_image_index = st.text_input("Enter the image you want to choose (e.g., 1)",key="selected image")177    #upload image178    uploaded_file = st.file_uploader("Choose an image", type=["jpg", "jpeg", "png"])179 180    selected_profile = None  # Assign a default value181 182    if st.toggle("Post to Facebook"):183        if selected_image_index:184            st.write("Posting images")185            if 1 <= int(selected_image_index) <= len(image_urls):186                st.session_state.selected_image_index = int(selected_image_index) - 1187                st.session_state.selected_image_url = image_urls[int(selected_image_index) - 1]188                image_path= image_urls[int(selected_image_index) - 1]189                st.text(f"Selected Image {selected_image_index}")  190                191                192                facebook_username = st.text_input("Enter your Facebook username")193                facebook_password = st.text_input("Enter your Facebook password", type="password")194                if st.checkbox("Login to facebook"):195                    username=facebook_username196                    password=facebook_password197                    if facebook_username and facebook_password:198                        st.info("Logging in to Facebook...")199                        #login_to_facebook(App_name,restuarant_name,location,nature_of_cuisine,occasion,offer,other_keywords)200                        page_id,permanant_access_token = app_creation(username, password, App_name)201                                #image_path = 'image.jpeg'202                        #st.write(f"Retrieved permanant_access_token in login : {permanant_access_token}")203                        access_token = permanant_access_token  # Your Facebook access token here204                                #page_id = '179897971873271'  # Your Facebook page ID here205                                206                        #new_entry_user(username,password,page_id,access_token)207                        #user_data = {"username": username, "password": password, "access token": access_token, "page id": page_id,"App name": App_name}208                        #collection.insert_one(user_data)209                        #st.success("Data saved successfully.")210                        insert_data(username, password, access_token, page_id, App_name)211                        212                        213                        message = str(modified_content)214 215                        if st.checkbox("Schedule Post" ):216                            image_url = image_path217                            image_response = requests.get(image_url)218                           # graph = facebook.GraphAPI(access_token)219                            print(page_id)220 221                            image_path = image_response.content222                            223                            caption = modified_content224                        225                            226                            227 228                            # Replace with your User Access Token, Page ID, and desired API version229                            user_access_token = permanant_access_token230                            231 232                            api_version = "v13.0"233 234                            # Make a request to get the Page Access Token235                            url = f"https://graph.facebook.com/{api_version}/{page_id}?fields=access_token&access_token={user_access_token}"236                            response = requests.get(url)237                            data = response.json()238 239                            # Extract the Page Access Token240                            page_access_token = data.get("access_token")241                            print(f"Page Access Token: {page_access_token}")242                            st.header("Scheduling posts on Facebook")243                            message = modified_content244                            scheduled_date = st.date_input("Select date:")245                            scheduled_time = st.time_input("Select time:")246 247                            # Combine date and time to create a datetime object248                            scheduled_datetime = datetime.combine(scheduled_date, scheduled_time)249 250                            # Step 8: Display all timezones in a dropdown251                            timezones = pytz.all_timezones252                            selected_timezone = st.selectbox("Select timezone:", timezones)253 254                            # Step 9: Store the selected timezone255                            st.write(f"Selected Timezone: {selected_timezone}")256 257                            # Step 9 & 10: Post the Facebook post according to the date, time, and timezone258                            if st.button("Schedule Post"):259                                if  message and scheduled_datetime:260                                    try:261                                        # Save the uploaded file and get the file path262                                        #image_path = save_uploaded_file(uploaded_file)263                                        post_to_facebook_demo_schedule_image_url(access_token, page_id, message, image_path, scheduled_datetime, selected_timezone)264                                        st.success("Post scheduled successfully!")265                                    except Exception as e:266                                        st.error(f"Error scheduling post: {e}")267                                else:268                                    st.warning("Please fill in all the required fields.")                                269                        if st.checkbox("Post Now"):270                            post_to_facebook_demo(access_token, page_id, message, image_path)271                            st.success("Post published successfully.")272                        273                    else:274                        st.warning("Please enter both Facebook username and password.")275            else:276                st.warning(f"Invalid image index. Please enter a number between 1 and {len(image_urls)}.")277        if uploaded_file:278            facebook_username = st.text_input("Enter your Facebook username")279            facebook_password = st.text_input("Enter your Facebook password", type="password")280            image_path = save_uploaded_file(uploaded_file)281            if st.checkbox("Login to facebook"):282                username=facebook_username283                password=facebook_password284                if facebook_username and facebook_password:285                    st.info("Logging in to Facebook...")286                    #login_to_facebook(App_name,restuarant_name,location,nature_of_cuisine,occasion,offer,other_keywords)287                    page_id,permanant_access_token = app_creation(username, password, App_name)288                            #image_path = 'image.jpeg'289                    access_token = permanant_access_token  # Your Facebook access token here290                                #page_id = '179897971873271'  # Your Facebook page ID here291                    user_data = {"username": username, "password": password, "access token": access_token, "page id": page_id,"App name": App_name}292                    collection.insert_one(user_data)293                    st.success("Data saved successfully.")294                    message = str(modified_content)295 296                    if st.checkbox("Schedule Post" ):297                        #image_url = image_path298                        #image_response = requests.get(image_url)299                        graph = facebook.GraphAPI(access_token)300                        print(page_id)301 302                        caption = modified_content303                        #new_entry_user(username,password,page_id,access_token)304                        305                        306                            307                            308 309                            # Replace with your User Access Token, Page ID, and desired API version310                        user_access_token = permanant_access_token311                            312 313                        api_version = "v13.0"314 315                            # Make a request to get the Page Access Token316                        url = f"https://graph.facebook.com/{api_version}/{page_id}?fields=access_token&access_token={user_access_token}"317                        response = requests.get(url)318                        data = response.json()319 320                            # Extract the Page Access Token321                        page_access_token = data.get("access_token")322 323                        print(f"Page Access Token: {page_access_token}")324                        325 326                        st.header("Scheduling posts on Facebook")327                        #uploaded_file = st.file_uploader("Choose an image", type=["jpg", "jpeg", "png"])328 329                        message = modified_content330 331                        scheduled_date = st.date_input("Select date:")332                        scheduled_time = st.time_input("Select time:")333 334                            # Combine date and time to create a datetime object335                        scheduled_datetime = datetime.combine(scheduled_date, scheduled_time)336 337                            # Step 8: Display all timezones in a dropdown338                        timezones = pytz.all_timezones339                        selected_timezone = st.selectbox("Select timezone:", timezones)340 341                            # Step 9: Store the selected timezone342                        st.write(f"Selected Timezone: {selected_timezone}")343 344                            # Step 9 & 10: Post the Facebook post according to the date, time, and timezone345                        if st.button("Schedule Post"):346                            if uploaded_file and message and scheduled_datetime:347                                try:348                                    # Save the uploaded file and get the file path349                                    image_path = save_uploaded_file(uploaded_file)350                                    post_to_facebook_demo_schedule_file_upload(access_token, page_id, message, image_path, scheduled_datetime, selected_timezone)351                                    st.success("Post scheduled successfully!")352                                except Exception as e:353                                    st.error(f"Error scheduling post: {e}")354                            else:355                                st.warning("Please fill in all the required fields.")356 357 358                        359                                # Set default values for scheduled date and time360                                361                                #st.success("Post scheduled. You can close this window, and the post will be posted at the scheduled time.")362 363                    if st.checkbox("Post Now"):364                        post_to_facebook_demo_file_upload(access_token, page_id, message, image_path)365                        st.success("Post published successfully.")366                    367                else:368                    st.warning("Please enter both Facebook username and password.")369                    370                    371    return browsers, selected_profile372 373@st.cache_data374def new_entry_user(username,password,page_id,access_token):375    user_data = initialize_user_data()376    new_entry = pd.DataFrame([[username, password, page_id, access_token]],377                columns=['Username', 'Password', 'PageID', 'AccessToken'])378    user_data = pd.concat([user_data, new_entry], ignore_index=True)379    user_data.to_excel("user_data.xlsx", index=False)380@st.cache_data                          381def initialize_user_data2():382    try:383        user_data = pd.read_excel("user_data.xlsx")384    except FileNotFoundError:385        columns = ['Username', 'Password', 'PageID', 'AccessToken']386        user_data = pd.DataFrame(columns=columns)387        user_data.to_excel("user_data.xlsx", index=False)388    return user_data 389 390 391 392 393 394 395 396 397@st.cache_data(show_spinner=False, experimental_allow_widgets=True)398#function for app automation399def app_creation(username, password, App_name):400    #facebook login401    selected_profile = None  # Assign a default value402    #facebook login403    browsers.get("http://www.facebook.com")404   405 406    username_elem = browsers.find_element(By.ID, "email")407    password_elem = browsers.find_element(By.ID, "pass")408    button = browsers.find_element(By.CSS_SELECTOR, 'button[data-testid="royal_login_button"]')409    browsers.maximize_window()410    username_elem.send_keys(username)411    password_elem.send_keys(password)412    button.click()413    time.sleep(4)  # Waiting for the page to load414    time.sleep(4)415# facebook login416    outer_profile_element = WebDriverWait(browsers, 40).until(417        EC.element_to_be_clickable((By.CSS_SELECTOR, ".x14yjl9h.xudhj91.x18nykt9.xww2gxu.x10l6tqk.xhtitgo"))418    )419    outer_profile_element.click()420    time.sleep(4)421    inner_profile_element = WebDriverWait(browsers, 40).until(422        EC.element_to_be_clickable((By.CSS_SELECTOR, '.x1i10hfl.xjbqb8w.x6umtig.x1b1mbwd.xaqea5y.xav7gou.x1ypdohk.xe8uvvx.xdj266r.x11i5rnm.xat24cr.x1mh8g0r.xexx8yu.x4uap5.x18d9i69.xkhd6sd.x16tdsg8.x1hl2dhg.xggy1nq.x1o1ewxj.x3x9cwd.x1e5q0jg.x13rtm0m.x87ps6o.x1lku1pv.x1a2a7pz.x9f619.x3nfvp2.xdt5ytf.xl56j7k.x1n2onr6.xh8yej3'))423    )424    inner_profile_element.click()425    time.sleep(4)426    profile_containers = WebDriverWait(browsers, 40).until(427        EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.x1i10hfl.x1qjc9v5.xjbqb8w.xjqpnuy.xa49m3k.xqeqjp1.x2hbi6w.x13fuv20.xu3j5b3.x1q0q8m5.x26u7qi.x972fbf.xcfux6l.x1qhh985.xm0m39n.x9f619.x1ypdohk.xdl72j9.x2lah0s.xe8uvvx.xdj266r.x11i5rnm.xat24cr.x1mh8g0r.x2lwn1j.xeuugli.xexx8yu.x4uap5.x18d9i69.xkhd6sd.x1n2onr6.x16tdsg8.x1hl2dhg.xggy1nq.x1ja2u2z.x1t137rt.x1q0g3np.x87ps6o.x1lku1pv.x1a2a7pz.x1lq5wgf.xgqcy7u.x30kzoy.x9jhf4c.x1lliihq[role="radio"]'))428    )429    st.write("Profiles and Business pages")430    profile_names = []431    for container in profile_containers:432        profile_name = container.find_element(By.CSS_SELECTOR, '.x1yc453h').text433        profile_names.append(profile_name)434    selected_profile = st.selectbox("Select a profile", profile_names)435    for container in profile_containers:436        profile_name = container.find_element(By.CSS_SELECTOR, '.x1yc453h').text437        if profile_name == selected_profile:438            container.click()439            time.sleep(3)440            time.sleep(4)441            try:442                #time.sleep(3)443                time.sleep(4)444                not_now_button = WebDriverWait(browsers, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="facebook"]/body/div[6]/div[1]/div/div[2]/div/div/div/div[2]/div[3]/div/div[1]/div[2]')))445                not_now_button.click()446                447                business_page_button = WebDriverWait(browsers, 10).until(448                EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div/div[1]/div/div[3]/div/div/div[1]/div[1]/div/div[1]/div/div/div[1]/div/div/div[1]/ul/li/div/a')))449                business_page_button.click()450            except:451                print("no button")452                business_page_name = selected_profile453           454            455                business_page_element = WebDriverWait(browsers, 10).until(456                    EC.element_to_be_clickable((By.XPATH, f'//span[text()="{business_page_name}"]'))457                )458                business_page_element.click()459                time.sleep(4)460            #business_page_name = selected_profile461           462            463            #business_page_element = WebDriverWait(browsers, 10).until(464            #    EC.element_to_be_clickable((By.XPATH, f'//span[text()="{business_page_name}"]'))465            #)466            #business_page_element.click()467            #time.sleep(4)468        469            about_element = WebDriverWait(browsers, 10).until(470                    EC.element_to_be_clickable((By.XPATH, '//span[text()="About"]'))471                )472            about_element.click()473            page_transparency_element = WebDriverWait(browsers, 10).until(474                EC.element_to_be_clickable((By.XPATH, '//span[text()="Page transparency"]'))475            )476            page_transparency_element.click()477            time.sleep(8) 478            xpath = '/html/body/div[1]/div/div[1]/div/div[3]/div/div/div[1]/div[1]/div[2]/div/div/div/div/div[4]/div/div/div/div[1]/div/div/div/div/div[2]/div/div/div/div/div[2]/div/div/div[2]/div[1]/span'479            page_id_element = WebDriverWait(browsers, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))480            page_id = page_id_element.text481            print("Page ID:", page_id)482            time.sleep(4) 483            #st.write(f"Retrieved Page ID: {page_id}")484            st.success(f"Clicked on {selected_profile}")485            time.sleep(4)486            browsers.get("https://business.facebook.com/login/?next=https%3A%2F%2Fdevelopers.facebook.com%2F%3Fbiz_login_source%3Dbizweb_unified_login_fb_login_button")487            browsers.maximize_window() 488            489            490            #myapps button491            element_to_click = browsers.find_element(By.XPATH, "/html/body/div[1]/div[5]/div[1]/div[2]/div/div[2]/ul/li[5]/a/div[1]")492            element_to_click.click()493            print("clicked get started button")494            #st.write("clicked get started button")495            496            time.sleep(2)497            498            499            #new registration500        501            502            503            try:504                element_locator = (By.CSS_SELECTOR, 'body > div > div:nth-child(11) > div._li._4xit > div > div > div > div > div.x1qjc9v5.x78zum5.x1iyjqo2.xeuugli.xdt5ytf.xs83m0k.xozqiw3.x169t7cy.x2lwn1j > div > div:nth-child(2) > div > div > div > div > div > div > div.xeuugli.x2lwn1j.x6s0dn4.x78zum5.x1q0g3np.xozqiw3.x19lwn94.x1y1aw1k.x1pi30zi.xwib8y2.x1swvt13.x1c4vz4f.x2lah0s > div > div:nth-child(2) > div')505 506                # Wait for the element to be clickable507                WebDriverWait(browsers, 10).until(EC.element_to_be_clickable(element_locator))508 509                # Find and click the element510                continue_button = browsers.find_element(*element_locator)511                continue_button.click() 512                print("clicked register button")513                time.sleep(2)514                515                #confirm email button516                confirm_email_button = browsers.find_element(By.XPATH, "/html/body/div/div[5]/div[2]/div/div/div/div/div[3]/div/div[2]/div/div/div/div/div/div/div[3]/div/div[2]")517                confirm_email_button.click()518                print("clicked confirm email button")519                #st.write("clicked confirm email button")520                time.sleep(2)521                522                #developer radio button523                radio_button_locator = (By.CLASS_NAME, 'x1i10hfl')  # Replace with the actual class name524                WebDriverWait(browsers, 10).until(EC.element_to_be_clickable(radio_button_locator))525                526                #radio_button = browsers.find_element(*radio_button_locator)527                #radio_button.click()528                try:529                    element = browsers.find_element(By.CSS_SELECTOR, 'body > div > div:nth-child(11) > div._li._4xit > div > div > div > div > div.x1qjc9v5.x78zum5.x1iyjqo2.xeuugli.xdt5ytf.xs83m0k.xozqiw3.x169t7cy.x2lwn1j > div > div:nth-child(2) > div > div > div > div > div > div > div.x9f619.x78zum5.x1iyjqo2.x5yr21d.x2lwn1j.x1n2onr6.xh8yej3 > div.xw2csxc.x1odjw0f.xwib8y2.xh8yej3 > div.x1iyjqo2.xs83m0k.xdl72j9.x3igimt.xedcshv.x1t2pt76.x1swvt13.x1pi30zi.xexx8yu.x18d9i69 > div._6g3g.xh8yej3 > div > div._6g3g.x1wsuqlk.x5sxuk9 > div > div > div:nth-child(1)')530                    element.click() 531                    print("clicked dev button 1")532                    #st.write("clicked dev button 1")533                except:534                    element = browsers.find_element(By.CSS_SELECTOR, '.x1gzqxud.x1lq5wgf.xgqcy7u.x30kzoy.x9jhf4c.x1bdj1k2.x1y1aw1k.xwib8y2.xurb0ha.x1sxyh0.x78zum5.xdl72j9.xdt5ytf.x2lah0s.x2lwn1j.xeuugli.x1n2onr6.x1afcbsf.x13faqbe.x3oybdh.x13fuv20.xu3j5b3.x1q0q8m5.x26u7qi.x178xt8z.xm81vs4.xso031l.xy80clv.xb9moi8.xfth1om.x21b0me.xmls85d')535                    element.click()536                    print("clicked dev button 2")537                    #st.write("clicked dev button 2")538                539                540                #complete registration button541                complete_registration_button = browsers.find_element(By.XPATH, "/html/body/div/div[5]/div[2]/div/div/div/div/div[3]/div/div[2]/div/div/div/div/div/div/div[3]/div/div")542                complete_registration_button.click()543                print("clicked complete registration button")544                545                #close mark546                try:547                    close_button = browsers.find_element(By.XPATH, "/html/body/div[3]/div[1]/div[1]/div/div/div/div/div/div[1]/div[2]/div[2]/div/div/div[1]/div[2]/span/div/span/div/div[2]")548                    close_button.click()549                    print("clicked c button")550                    #st.write("clicked c button")551                except:552                    #close_button = browsers.find_element(By.XPATH, "/html/body/div[3]/div[1]/div[1]/div/div/div/div/div/div[1]/div[2]/div[2]/div/div/div[1]/div[2]/span/div/span/div/div[2]")553                    #close_button.click()554                    #print("clicked c button 2")555                    #st.write("clicked c button")556                    print("passed")557                time.sleep(2)558                    559                #create new app button560                create_newapp = browsers.find_element(By.XPATH, "/html/body/div[1]/div[5]/div[2]/div/div/div/div/div/div[1]/div[3]/div[2]/div")561     562                # Click the element563                create_newapp.click()564                #st.write("clicked create_newapp")565                time.sleep(2)566                567                close_button = browsers.find_element(By.XPATH, '//*[@id="facebook"]/body/div[2]/div[1]/div[1]/div/div/div/div/div/div[1]/div[2]/div[2]/div/div/div[3]/div/div')568     569                # Click the element570                close_button.click()571                #st.write("clicked close_button")572                573                574                575            except:576                create_newapp = browsers.find_element(By.XPATH, "/html/body/div[1]/div[5]/div[2]/div/div/div/div/div/div[1]/div[3]/div[2]/div/div")577     578                # Click the element579                create_newapp.click()580                #st.write("clicked create_newapp 2 ")581                time.sleep(2)582                583                try:584                    close_button = browsers.find_element(By.XPATH, '//*[@id="facebook"]/body/div[2]/div[1]/div[1]/div/div/div/div/div/div[1]/div[2]/div[2]/div/div/div[3]/div/div')585     586                # Click the element587                    close_button.click()588                    #st.write("clicked close_button 2")589                except:590                    print("check1")591                    592            593            594            #time.sleep(4)595            #create_newapp = browsers.find_element(By.XPATH, "/html/body/div[1]/div[5]/div[2]/div/div/div/div/div/div[1]/div[3]/div[2]/div/div")596     597        # Click the element598            #create_newapp.click()599            #time.sleep(4)600            usecase_button = browsers.find_element(By.XPATH, "/html/body/div[1]/div[5]/div[2]/div/div/div/div/div[3]/div/div[2]/div/div/div/div[1]/div[1]/div[2]/div[2]/div[2]/div[4]/div/div/div/div/div")601              # Click the element602            usecase_button.click()603            #time.sleep(4)604     605     606            #click next button607            next_button = browsers.find_element(By.XPATH, "/html/body/div[1]/div[5]/div[2]/div/div/div/div/div[3]/div/div[2]/div/div/div/div[2]/div/div/div")608            next_button.click()609            #time.sleep(4)610     611            #select app type612            apptype_button = browsers.find_element(By.XPATH, "/html/body/div[1]/div[5]/div[2]/div/div/div/div/div[3]/div/div[2]/div/div/div/div/div[1]/div[2]/div/div[2]/div/div[2]/div[1]/div")613            apptype_button.click()614            #time.sleep(4)615     616            #close notification617            notification_button = browsers.find_element(By.XPATH, "/html/body/div[1]/div[5]/div[3]/div/div/div/div/form/div/div/button")618            notification_button.click()619            time.sleep(4)620 621            #next button622            next_button = browsers.find_element(By.XPATH, "/html/body/div[1]/div[5]/div[2]/div/div/div/div/div[3]/div/div[2]/div/div/div/div/div[1]/div[2]/div/div[3]/div/div")623            next_button.click()624            time.sleep(4)625     626            #type app name627            appname=browsers.find_element("xpath", "/html/body/div[1]/div[5]/div[2]/div/div/div/div/div[3]/div/div[2]/div/div/div/div/div[1]/div[2]/div/div[1]/div/div/div[2]/div/div/div/div[1]/div[2]/div[1]/div/input")628            appname.send_keys(App_name)629     630            #create app button631            create_app_button = browsers.find_element(By.XPATH, "/html/body/div[1]/div[5]/div[2]/div/div/div/div/div[3]/div/div[2]/div/div/div/div/div[1]/div[2]/div/div[4]/div[2]/div[2]/div")632            create_app_button.click()633            time.sleep(10)634    635            #app_event = browsers.find_element(By.CSS_SELECTOR, 'a._271k._271m._1qjd._1gwm[href*="/async/products/add/?product_route=analytics"]')636            #app_event.click()637            #time.sleep(6)638     639     640            #link_element = browser.find_element(By.CSS_SELECTOR, 'a.x1i10hfl')641     642            # Click the link643            #link_element.click()644            #time.sleep(4)645     646            #instagram647            #instagram_graph_api_button =  browser.find_element(By.CSS_SELECTOR, 'a._271k._271m._1qjd._1gwm[href*="/async/products/add/?product_route=instagram"]')648     649            #instagram_graph_api_button.click()650            #time.sleep(3)651            #back to product page652            #link_element = browser.find_element(By.CSS_SELECTOR, 'a.x1i10hfl')653 654 655            #link_element.click()656 657            #whatsapp button658            #button_whatsapp = browser.find_element(By.CSS_SELECTOR, 'a._271k._271m._1qjd._1gwm[href*="/async/products/add/?product_route=whatsapp-business"]')659            #button_whatsapp.click()660            #time.sleep(4)661 662            #back to product page663            #link_element = browser.find_element(By.CSS_SELECTOR, 'a.x1i10hfl')664 665            #link_element.click()666            #time.sleep(4)667            #business login668            #button_business_login = browser.find_element(By.CSS_SELECTOR, 'a._271k._271m._1qjd._1gwm[href*="/async/products/add/?product_route=business-login"]')669            #button_business_login.click()670            #time.sleep(4)671 672            #back to product page673            #link_element = browser.find_element(By.CSS_SELECTOR, 'a.x1i10hfl')674            #link_element.click()'675 676            #tools677            tools_button= browsers.find_element(By.XPATH, "/html/body/div[1]/div[5]/div[1]/div/div[1]/div/div/div/div/div/div[2]/a[2]")678            tools_button.click()679            time.sleep(4)680 681            #graph api explorer682            graph_api_button = browsers.find_element(By.XPATH, '/html/body/div[1]/div[5]/div[2]/div/div/div[2]/div[1]/div[1]')683            graph_api_button.click()684 685 686 687            # Wait for the menu to be present688            button_xpath = '//*[@id="facebook"]/body/div[1]/div[5]/div[2]/div/div[2]/span/div/div[2]/div/div[5]/div[5]/div/div/div/div/div/div[5]/div/button'689            button_element = WebDriverWait(browsers, 10).until(690            EC.element_to_be_clickable((By.XPATH, button_xpath))691            )   692            button_element.click()693            print("app button clicked")694            time.sleep(6)695 696 697 698            item_xpath = f'//div[contains(., "{App_name}")]/span[@class="_5xzx"]'699            time.sleep(4)700 701            item_element = WebDriverWait(browsers, 40).until(702            EC.element_to_be_clickable((By.XPATH, item_xpath))703            )704            705            item_element.click()706            707            #css_selector = f'div._5xzw[role="menuitem"] span[data-tooltip-content="{App_name}"]'708 709            # Find the element using the constructed CSS selector710            #element = browser.find_element('css selector', css_selector)711 712            # Perform any actions you want with the selected element713            #print(f"Element with text '{App_name}_' found!")714            # For example, click on the element715            #element.click()716            #time.sleep(2)717 718            719            time.sleep(6)720 721 722            #permissions button723            permissions = browsers.find_element(By.XPATH, '/html/body/div[1]/div[5]/div[2]/div/div[2]/span/div/div[2]/div/div[5]/div[5]/div/div/div/div/div/div[9]/div[4]')724            permissions.click()725 726 727                    728 729 730            # Wait for the menu items to be present731            menu_items = WebDriverWait(browsers, 10).until(732            EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'div.uiContextualLayer ul[role="menu"] li a[role="menuitem"]')))733            time.sleep(6)734 735            # Click on each permissions ans sub permissions736            for item in menu_items:737                item.click()738            time.sleep(6)739 740            elements = WebDriverWait(browsers, 10).until(741                EC.presence_of_all_elements_located((By.CLASS_NAME, "_2wpb._3v8w"))742            )743 744            # Click on each element745            for element in elements:746                element.click()747            permissions.click()748 749 750            time.sleep(4)751            #scroll up teh window752            element = browsers.find_element(By.XPATH,'/html/body/div[1]/div[5]/div[2]/div/div[2]/span/div/div[2]/div/div[5]/div[5]')753            # Scroll the element into view754            browsers.execute_script("window.scrollTo(0, -document.body.scrollHeight);")755 756 757            original_window_handle = browsers.current_window_handle758 759 760 761            #clicking the generate button762            generate_token_button = WebDriverWait(browsers, 10).until(763            EC.presence_of_element_located((By.XPATH, '//*[@id="facebook"]/body/div[1]/div[5]/div[2]/div/div[2]/span/div/div[2]/div/div[5]/div[5]/div/div/div/div/div/div[2]/div/button'))764            )765 766            # Click on the element767            generate_token_button.click() 768 769            #storing the state of teh original window770 771 772            #window_after = browser.window_handles[1]773            #browser.switch_to.window(window_after)774 775 776            new_window_handle = WebDriverWait(browsers, 10).until(EC.number_of_windows_to_be(2))777 778            # Switch to the new window779            all_window_handles = browsers.window_handles780            new_window_handle = [handle for handle in all_window_handles if handle != browsers.current_window_handle][0]781            browsers.switch_to.window(new_window_handle)782 783            button0 = WebDriverWait(browsers, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[1]/div[2]/div[1]/form/div/div[3]/div/div[1]")))784            button0.click()785            time.sleep(10)786         787            button1 = WebDriverWait(browsers, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div/div/div/form/div/div/div/div/div/div[2]/div/div/div[2]/div/div[2]/div[2]")))788            button1.click()   789            time.sleep(10)790 791            try:792                button2 = WebDriverWait(browsers, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div/div/div/form/div/div/div/div/div/div[2]/div/div[3]/div/label/div/div/div[1]/div")))793                button2.click()794                time.sleep(10)795            except:796                button2 = WebDriverWait(browsers, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div/div/div/form/div/div/div/div/div/div[2]/div/div[3]/div/div/div[2]/div[2]/div")))797                button2.click()798                time.sleep(10)799                800 801            button3 = WebDriverWait(browsers, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div/div/div/form/div/div/div/div/div/div[2]/div/div[4]/div/div/div[2]/div[2]/div")))802            button3.click()803            time.sleep(10)804 805            button4 = WebDriverWait(browsers, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div/div/div/form/div/div/div/div/div/div[2]/div/div[3]/div/label/div/div/div[1]/div")))806            button4.click()807            time.sleep(10)808 809            button5 = WebDriverWait(browsers, 10).until(EC.element_to_be_clickable((By.XPATH, "//html/body/div/div/div/form/div/div/div/div/div/div[2]/div/div[4]/div/div/div[2]/div[2]/div")))810            button5.click()811            time.sleep(10)812 813            button6 = WebDriverWait(browsers, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div/div/div/form/div/div/div/div/div/div[2]/div/div[3]/div/div/div[2]/div[2]/div")))814            button6.click()815            time.sleep(10)816 817            try:818                button7 = WebDriverWait(browsers, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div/div/div/form/div/div/div/div/div/div[2]/div/div[3]/div/label/div/div/div[1]/div")))819                button7.click()820                time.sleep(10)821            except:822                button7 = WebDriverWait(browsers, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div/div/div/form/div/div/div/div/div/div[2]/div/div[3]/div/div/div[2]/div[2]/div")))823                button7.click()824                time.sleep(10)825 826            try:827                button8 = WebDriverWait(browsers, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div/div/div/form/div/div/div/div/div/div[2]/div/div[4]/div/div/div[2]/div[2]/div")))828                button8.click()829                time.sleep(10)830            except:831                button8 = WebDriverWait(browsers, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div/div/div/form/div/div/div/div/div/div[2]/div/div[4]/div/div/div[2]/div[2]/div")))832                button8.click()833                time.sleep(10)834                835         836            try:837                button9 = WebDriverWait(browsers, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div/div/div/form/div/div/div/div/div/div[2]/div/div[4]/div/div/div[2]/div[2]/div")))838                button9.click()839                time.sleep(10)840            except:841                button9 = WebDriverWait(browsers, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div/div/div/form/div/div/div/div/div/div[2]/div/div[2]/div/div/div[2]/div/div")))842                button9.click()843                time.sleep(10)844                845         846            try:847                button10 = WebDriverWait(browsers, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div/div/div/form/div/div/div/div/div/div[2]/div/div[2]/div/div/div[2]/div/div")))848                button10.click()849                time.sleep(10)850            except:851                browsers.switch_to.window(original_window_handle)852                print("original window")853                854 855            browsers.switch_to.window(original_window_handle)856            print("original window")857 858 859            access_token = browsers.find_element(By.XPATH,"/html/body/div[1]/div[5]/div[2]/div/div[2]/span/div/div[2]/div/div[5]/div[5]/div/div/div/div/div/div[2]/div/div/div[1]/label/input")860            #access token861            value = access_token.get_attribute("value")862            #value="EAAKfwS1Vv6cBOwLlyyhgbTcsoXO2fPdqAEXUQ9O6UgPWRj1bkoZCkNy8wGCPsZADyX6fPQOZAb8gR1T9G8zIPyz9fsNJrGughQtSd4IZBg9L1WbI0ZBAv8ZB15aWnZBvu3tU6B1heTYUuf1R9w52DuL43mozw4HsMb9NaR3ruiP9nGcZCEaqx3k883NjtiAeCt55kCOQLtfuIMSf9gLh434Ru2SGuSJndqUKd2MZD"863            #st.write(f"Retrieved temporary access token : {value}")864            865            #tools button866            tools_button = browsers.find_element(By.XPATH, '/html/body/div[1]/div[5]/div[1]/div[2]/div/div/div/div/div/div/div[2]/a[2]')867            tools_button.click()868            869            # access_token_tool_button870            access_token_tool_button = browsers.find_element(By.XPATH, '/html/body/div[1]/div[5]/div[2]/div/div/div[2]/div[2]/div[1]/a[1]')871            access_token_tool_button.click()872            873            time.sleep(4)874            875            html_content = browsers.page_source876            print(html_content)877            soup = BeautifulSoup(html_content, 'html.parser')878 879            # Find the div containing the specified text880            desired_div = soup.find('div', class_='_5k-5 _c24 _2iem _50f7', text=App_name)881 882            if desired_div:883                # Extract the access token from the corresponding <a> tag884                paccess_token = desired_div.find_next('a')['href'].split('=')[-1]885                print(f"Access Token: {paccess_token}")886                #st.write("permanatn acces stoken : "+ str(paccess_token))887 888            889 890         891            #fetching app scoped id892            app_scoped_user_id=""893     894 895         896             # Construct the URL for the /me endpoint897            url = "https://graph.facebook.com/v12.0/me"898 899             # Prepare parameters900            params = {901                "access_token": str(value)902            }903 904            try:905             # Make the request using the requests library906                response = requests.get(url, params=params)907                response.raise_for_status()  # Raise an HTTPError for bad responses908 909                # Parse the JSON response910                data = response.json()911 912                 # Check for errors913                if "id" in data:914                    app_scoped_user_id = data["id"]915                #return app_scoped_user_id916                else:917                    print("Error: User ID not found in the response.")918            except requests.exceptions.RequestException as e:919                print(f"Error: {e}")920 921         922            # Replace this with a valid user access token923 924             # Get the App-Scoped User ID925            print(app_scoped_user_id)926            927            928            #st.write(f"Retrieved app_scoped_user_id: {app_scoped_user_id}")929            930            permanant_access_token =""931            url = f"https://graph.facebook.com/v12.0/{app_scoped_user_id}/accounts"932 933             # Prepare parameters934            params = {935                    "access_token": paccess_token936                }937 938            try:939                    # Make the GET request using the requests library940                response = requests.get(url, params=params)941                response.raise_for_status()  # Raise an HTTPError for bad responses942 943                 # Parse the JSON response944                data = response.json()945 946                    # Check for errors947                if "data" in data and data["data"]:948                    permanant_access_token = data["data"][0]["access_token"]949                    print(data["data"][0]["access_token"])950                else:951                    print("No accounts found for the given user.")952            except requests.exceptions.RequestException as e:953                print(f"Error: {e}")954 955  956 957 958            #st.write(f"Retrieved  permanant Access token : {permanant_access_token}")959         960            pageid = page_id961            access_token = permanant_access_token962            #browser.close()963            #st.write(f"Retrieved permanant Access token ID: {access_token}")964            browsers.quit()965        966        967    968 969    970            return page_id, access_token971        972        973#function for post a scheduled post containing user uploaded image 974@st.cache_data(show_spinner=False)975def post_to_facebook_demo_schedule_file_upload(access_token, page_id, message, image_path, scheduled_datetime, selected_timezone):976    graph = facebook.GraphAPI(access_token)977 978    # Convert scheduled_datetime to the selected timezone979    scheduled_datetime = pytz.timezone(selected_timezone).localize(scheduled_datetime)980 981    # Convert scheduled_datetime to Unix timestamp (number)982    scheduled_timestamp = int(scheduled_datetime.timestamp())983 984    # Schedule the post985    986    graph.put_photo(parent_object=page_id, image=open(image_path, 'rb'), message=message, published=False, scheduled_publish_time=scheduled_timestamp)987    988 989#function to post scheduled post of a generated image   1                                 990@st.cache_resource(show_spinner=False)991def post_to_facebook_demo_schedule_image_url(access_token, page_id, message, image_path, scheduled_datetime, selected_timezone):992    graph = facebook.GraphAPI(access_token)993 994    # Convert scheduled_datetime to the selected timezone995    scheduled_datetime = pytz.timezone(selected_timezone).localize(scheduled_datetime)996 997    # Convert scheduled_datetime to Unix timestamp (number)998    scheduled_timestamp = int(scheduled_datetime.timestamp())999 1000    # Schedule the post1001    1002    graph.put_photo(parent_object=page_id, image=image_path, message=message, published=False, scheduled_publish_time=scheduled_timestamp)1003    1004    1005    #open(image_path, 'rb')1006    1007    1008    1009#function to post scheduled post of a user uploaded image 2    1010@st.cache_data(show_spinner=False)1011def post_to_facebook_demo_schedule(access_token, page_id, message, image_path, scheduled_datetime, selected_timezone):1012    graph = facebook.GraphAPI(access_token)1013 1014    # Convert scheduled_datetime to the selected timezone1015    scheduled_datetime = pytz.timezone(selected_timezone).localize(scheduled_datetime)1016 1017    # Convert scheduled_datetime to Unix timestamp (number)1018    scheduled_timestamp = int(scheduled_datetime.timestamp())1019 1020    # Schedule the post1021    1022    graph.put_photo(parent_object=page_id, image=open(image_path, 'rb'), message=message, published=False, scheduled_publish_time=scheduled_timestamp)1023 1024 1025 1026#function for existing user    1027#@st.cache_data(show_spinner=False,experimental_allow_widgets=True)1028def login_to_facebook_existing_user(restuarant_name,location,nature_of_cuisine,occasion,offer,other_keywords):1029    #global browser1030 1031    #facebook content generation1032    st.subheader("Facebook Post Content Generation")1033    content=content_generator(restuarant_name,location,nature_of_cuisine,occasion,offer)1034    modified_content=st.text_area("Generated Facebook Post Content", content,key="modified_content_existing_user")1035        #image generation1036    image_urls= image_generator(other_keywords)1037 1038 1039        # Display all images with buttons1040    for i, image_url in enumerate(image_urls):1041        st.image(image_url, caption=f'Image {i + 1}', use_column_width=True, width=200)1042    selected_image_index = st.text_input("Enter the image you want to choose (choose integers)")1043        #upload image1044    uploaded_file = st.file_uploader("Choose an image file to upload", type=["jpg", "jpeg", "png"],key="uploaded_file_existing_user")1045    if st.toggle("Post to Facebook account"):1046        #fbusername = st.text_input("Enter restaurant name to which you want to post:",key="fb_username")1047        #print(fbusername)1048        if st.checkbox("Click here to post to fb account"):1049 1050            #user_data = initialize_user_data2()1051            #user_row = user_data[user_data['Username'] == fbusername]1052            #retrieve_data(fbusername)1053            user_data = collection.find_one({"App name": restuarant_name})1054           1055 1056            1057 1058            print("button3 is working")1059            if user_data:1060                #password = user_row.iloc[0]['Password']1061                #page_id = user_row.iloc[0]['PageID']1062                #access_token = user_row.iloc[0]['AccessToken']1063                page_id = user_data['page id']1064                access_token = user_data['access token']1065                #st.write(f"Retrieved access_token ID: {access_token}")1066                print("got all info")1067                if selected_image_index:1068                    st.write("Posting images")1069                    if 1 <= int(selected_image_index) <= len(image_urls):1070                        st.session_state.selected_image_index = int(selected_image_index) - 11071                        st.session_state.selected_image_url = image_urls[int(selected_image_index) - 1]1072                        image_path= image_urls[int(selected_image_index) - 1]1073                        st.text(f"Selected Image {selected_image_index}")  1074                                1075                        message = str(modified_content)1076 1077                        if st.checkbox("Schedule the facebook Post",key="Schedule_Post_existing user"):1078                            image_url = image_path1079                            image_response = requests.get(image_url)1080                        # graph = facebook.GraphAPI(access_token)1081                            print(page_id)1082                            image_path = image_response.content1083                                            1084                            caption = modified_content1085                                            # Replace with your User Access Token, Page ID, and desired API version1086                            user_access_token = access_token1087                                            1088 1089                            api_version = "v13.0"1090 1091                                            # Make a request to get the Page Access Token1092                            url = f"https://graph.facebook.com/{api_version}/{page_id}?fields=access_token&access_token={user_access_token}"1093                            response = requests.get(url)1094                            data = response.json()1095 1096                                            # Extract the Page Access Token1097                            page_access_token = data.get("access_token")1098                            print(f"Page Access Token: {page_access_token}")1099                            st.header("Scheduling posts on Facebook")1100                            message = modified_content1101                            scheduled_date = st.date_input("Select date:",key="date_existing user")1102                            scheduled_time = st.time_input("Select time:",key="time_existing user")1103 1104                                            # Combine date and time to create a datetime object1105                            scheduled_datetime = datetime.combine(scheduled_date, scheduled_time)1106 1107                                            # Step 8: Display all timezones in a dropdown1108                            timezones = pytz.all_timezones1109                            selected_timezone = st.selectbox("Select timezone:", timezones,key="timezone_existing user")1110 1111                                            # Step 9: Store the selected timezone1112                            st.write(f"Selected Timezone: {selected_timezone}")1113 1114                                            # Step 9 & 10: Post the Facebook post according to the date, time, and timezone1115                            if st.button("Schedule Post confirm",key="Postexisting user"):1116                                if  message and scheduled_datetime:1117                                    try:1118                                                        # Save the uploaded file and get the file path1119                                                        #image_path = save_uploaded_file(uploaded_file)1120                                        post_to_facebook_demo_schedule_image_url(access_token, page_id, message, image_path, scheduled_datetime, selected_timezone)1121                                        st.success("Post scheduled successfully!")1122                                    except Exception as e:1123                                            st.error(f"Error scheduling post: {e}")1124                                    #post_to_facebook_demo_schedule_image_url(access_token, page_id, message, image_path, scheduled_datetime, selected_timezone)1125                                    #st.success("Post scheduled successfully!")1126                                else:1127                                    st.warning("Please fill in all the required fields.")                                1128                        if st.checkbox("Post to facebook account Now"):1129                            post_to_facebook_demo(access_token, page_id, message, image_path)1130                            st.success("Post published successfully.")1131                                    # Button to close the browser1132                                1133                    else:1134                        st.warning(f"Invalid image index. Please enter a number between 1 and {len(image_urls)}.")1135                if uploaded_file:1136                    #facebook_username = st.text_input("Enter your Facebook username")1137                    #facebook_password = st.text_input("Enter your Facebook password", type="password")1138                    image_path = save_uploaded_file(uploaded_file)1139                    if st.checkbox("Login to facebook",key="uploaded_file_Login_existing user"):1140                        #username=facebook_username1141                        #password=facebook_password1142                        st.info("Logging in to Facebook...")1143                        #login_to_facebook(App_name,restuarant_name,location,nature_of_cuisine,occasion,offer,other_keywords)1144                        #page_id,permanant_access_token = app_creation(username, password, App_name)1145                        #image_path = 'image.jpeg'1146                        #access_token = permanant_access_token  # Your Facebook access token here1147                        #page_id = '179897971873271'  # Your Facebook page ID here1148                        message = str(modified_content)1149 1150                        if st.checkbox("Schedule post",key="uploaded_file_post_existing user"):1151                                    #image_url = image_path1152                                        #image_response = requests.get(image_url)1153                            graph = facebook.GraphAPI(access_token)1154                            print(page_id)1155                            caption = modified_content1156                            user_access_token = access_token1157                                            1158 1159                            api_version = "v13.0"1160 1161                            # Make a request to get the Page Access Token1162                            url = f"https://graph.facebook.com/{api_version}/{page_id}?fields=access_token&access_token={user_access_token}"1163                            response = requests.get(url)1164                            data = response.json()1165 1166                            # Extract the Page Access Token1167                            page_access_token = data.get("access_token")1168 1169                            print(f"Page Access Token: {page_access_token}")1170                                        1171 1172                            st.header("Scheduling posts on Facebook")1173                                        #uploaded_file = st.file_uploader("Choose an image", type=["jpg", "jpeg", "png"])1174 1175                            message = modified_content1176 1177                            scheduled_date = st.date_input("Select date to publish post:")1178                            scheduled_time = st.time_input("Select time to publish post:")1179 1180                                            # Combine date and time to create a datetime object1181                            scheduled_datetime = datetime.combine(scheduled_date, scheduled_time)1182 1183                                            # Step 8: Display all timezones in a dropdown1184                            timezones = pytz.all_timezones1185                            selected_timezone = st.selectbox("Select the timezone :", timezones)1186 1187                                            # Step 9: Store the selected timezone1188                            st.write(f"Selected Timezone: {selected_timezone}")1189 1190                                            # Step 9 & 10: Post the Facebook post according to the date, time, and timezone1191                            if st.button("Schedule the Post"):1192                                if uploaded_file and message and scheduled_datetime:1193                                    try:1194                                                    # Save the uploaded file and get the file path1195                                        image_path = save_uploaded_file(uploaded_file)1196                                        post_to_facebook_demo_schedule_file_upload(access_token, page_id, message, image_path, scheduled_datetime, selected_timezone)1197                                        st.success("Post scheduled successfully!")1198                                    except Exception as e:1199                                        st.error(f"Error scheduling post: {e}")1200                                else:

Showing the first 1,200 of 1370 lines. Download the file for the rest.