HTML

    Select a Subtopic

    ๐ŸŒŸ Day 21: Instagram Bot - Advanced Automation & Database Integration ๐ŸŒŸ

    Welcome to Day 21! ๐ŸŽ‰ Today, weโ€™ll move beyond basic Instagram automation and integrate a database to store important data like login details, user interactions, and stories viewed. Youโ€™ll also learn how to use environment variables securely and run your bot more efficiently.


    โœ… What Youโ€™ll Learn Today:

    • Using SQLite for local storage in your bot.
    • Storing login credentials and stories viewed in a database.
    • Securing your bot using environment variables.
    • Making your bot more efficient by reducing redundant logins.

    ๐Ÿท๏ธ 1. Using SQLite for Local Storage

    Weโ€™ll use SQLite, a lightweight database, to store:

    • Login credentials
    • Profiles visited
    • Stories viewed

    โœ… Setting Up SQLite Database:

    
    import sqlite3
    
    # Connect to the SQLite database
    conn = sqlite3.connect('instagram_bot.db')
    cursor = conn.cursor()
    
    # Create a table for login credentials
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS credentials (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT NOT NULL,
        password TEXT NOT NULL
    )
    ''')
    
    # Create a table for viewed stories
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS viewed_stories (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        profile_name TEXT NOT NULL,
        story_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
    ''')
    
    # Commit and close
    conn.commit()
    conn.close()
              

    ๐Ÿ–ฅ๏ธ 2. Inserting Data into the Database

    After setting up the database, letโ€™s create a function to insert credentials and log viewed stories.

    โœ… Updating database.py to Insert Data:

    
    import sqlite3
    
    # Function to add login credentials
    def add_credentials(username, password):
        conn = sqlite3.connect('instagram_bot.db')
        cursor = conn.cursor()
        cursor.execute('INSERT INTO credentials (username, password) VALUES (?, ?)', (username, password))
        conn.commit()
        conn.close()
    
    # Function to log viewed stories
    def log_viewed_story(profile_name):
        conn = sqlite3.connect('instagram_bot.db')
        cursor = conn.cursor()
        cursor.execute('INSERT INTO viewed_stories (profile_name) VALUES (?)', (profile_name,))
        conn.commit()
        conn.close()
              

    ๐Ÿ—๏ธ 3. Securing Credentials with Environment Variables

    Instead of hardcoding login details, store them in environment variables using dotenv.

    โœ… Installing dotenv:

    pip install python-dotenv

    โœ… Using dotenv in Your Bot:

    
    import os
    from dotenv import load_dotenv
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    import time
    
    # Load environment variables
    load_dotenv()
    username = os.getenv('IG_USERNAME')
    password = os.getenv('IG_PASSWORD')
    
    # Function to view stories
    def view_stories(profile):
        driver = webdriver.Chrome(executable_path="path/to/chromedriver")
        driver.get("https://www.instagram.com/accounts/login/")
        time.sleep(5)
    
        # Log in
        driver.find_element(By.NAME, "username").send_keys(username)
        driver.find_element(By.NAME, "password").send_keys(password)
        driver.find_element(By.XPATH, '//*[@id="loginForm"]/div/div[3]/button').click()
        time.sleep(5)
    
        # Navigate to the profile
        driver.get(f"https://www.instagram.com/{profile}/")
        time.sleep(5)
    
        # Log the story viewed
        from database import log_viewed_story
        log_viewed_story(profile)
    
        driver.quit()
              

    ๐Ÿ“Š 4. Viewing the Database Contents

    You can view your database contents using SQLite CLI or a tool like DB Browser for SQLite.

    โœ… Viewing the Database via CLI:

    sqlite3 instagram_bot.db
    SELECT * FROM credentials;
    SELECT * FROM viewed_stories;

    ๐Ÿค– 5. Efficient Login Handling

    Instead of logging in every time, you can:

    1. Check if the bot is already logged in.
    2. Skip the login if already authenticated.

    โœ… Checking Login Status:

    
    # Function to check if the bot is already logged in
    def is_logged_in(driver):
        driver.get("https://www.instagram.com/")
        time.sleep(3)
        try:
            driver.find_element(By.XPATH, '//span[@aria-label="Profile"]')
            return True
        except:
            return False
              

    ๐Ÿ† Bonus: Full Code with Database Integration

    Hereโ€™s the full code with story viewing, environment variables, and database logging:

    
    import os
    import time
    from dotenv import load_dotenv
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from database import log_viewed_story
    
    # Load environment variables
    load_dotenv()
    username = os.getenv('IG_USERNAME')
    password = os.getenv('IG_PASSWORD')
    
    # Function to view stories
    def view_stories(profile):
        driver = webdriver.Chrome(executable_path="path/to/chromedriver")
        driver.get("https://www.instagram.com/accounts/login/")
        time.sleep(5)
    
        # Check if logged in
        if not is_logged_in(driver):
            driver.find_element(By.NAME, "username").send_keys(username)
            driver.find_element(By.NAME, "password").send_keys(password)
            driver.find_element(By.XPATH, '//*[@id="loginForm"]/div/div[3]/button').click()
            time.sleep(5)
    
        # Navigate to the profile
        driver.get(f"https://www.instagram.com/{profile}/")
        time.sleep(5)
    
        # Log the story viewed
        log_viewed_story(profile)
    
        driver.quit()
    
    # Function to check if the bot is already logged in
    def is_logged_in(driver):
        driver.get("https://www.instagram.com/")
        time.sleep(3)
        try:
            driver.find_element(By.XPATH, '//span[@aria-label="Profile"]')
            return True
        except:
            return False
    
    # Run the bot
    if __name__ == "__main__":
        profile = input("Enter the profile to view stories: ")
        view_stories(profile)
              

    ๐ŸŽฏ Day 21 Task:

    • Set up a SQLite database for your bot.
    • Store credentials and viewed stories in the database.
    • Use environment variables to secure your credentials.
    • Optimize the bot to skip login if already authenticated.