from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from features.login.login_insta import login
from features.send.send_message import send_message
from utils.constants import DRIVER_PATH


class AatmanAmigo:
    def __init__(self):
        self.driver = webdriver.Chrome(DRIVER_PATH)

    def login(self, username, password):
        
        login(self.driver, username, password)
    
    def send_message(self, recipient, message):
        send_message(self.driver, recipient, message)


    def close(self):
        self.driver.quit()

api/insta_api.py
anupammaurya6767/aatman-amigo
#login_insta.py 

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time

# options = Options()
# options.add_argument("--headless=new")

# driver = webdriver.Chrome(options=options)

def login(driver, username, password):
    driver.get("https://www.instagram.com/")
    time.sleep(10)

    # 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, '//button[@type="submit"]').click()
    time.sleep(10)

    # Accept cookies
    # driver.find_element(By.XPATH, '//button[text()="Accept"]').click()
    # time.sleep(2)
    
    # saving login info
    driver.find_element(By.CLASS_NAME, "_acan").click()
    time.sleep(10)
    
    # notifications
    driver.find_element(By.CLASS_NAME, '_a9_1').click()
    time.sleep(3)
features/login/login_insta.py
anupammaurya6767/aatman-amigo
import time
import json
import requests

def receive_messages(self):
        url = "https://i.instagram.com/api/v1/direct_v2/inbox/"

        headers = {
            "user-agent": "Instagram 126.0.0.25.122 Android (24/7.0; 640dpi; 144.0 L; samsung; SM-G935F; herolte; samsungexynos8890) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.116 Mobile Safari/537.36",
            "accept-language": "en-US",
            "accept-encoding": "gzip, deflate, br",
            "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
            "cookie": f"sessionid={self.username}",
        }

        data = {
            "password": self.password,
            "username": self.username,
        }

        response = requests.post(url, headers=headers, data=data)

        if response.status_code == 200:
            json_response = json.loads(response.text)
            inbox = json_response["inbox"]
            threads = inbox["threads"]

            for thread in threads:
                items = thread["items"]

                for item in items:
                    if "text" in item:
                        print(f"{thread['users'][0]['username']}: {item['text']}")

features/receive/receive_message.py
anupammaurya6767/aatman-amigo
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time

def send_image(driver, recipient, image_path):
        try:
            driver.get(f'https://www.instagram.com/direct/t/{recipient}/')
            time.sleep(2)
            input_element = driver.find_element_by_xpath('//input[@accept="image/*"]')
            input_element.send_keys(image_path)
            time.sleep(2)
            submit_button = driver.find_element_by_xpath('//button[@type="submit"]')
            submit_button.click()
            return "Image sent successfully."
        except Exception as e:
            return f"Error sending image: {str(e)}"

features/send/send_image.py
anupammaurya6767/aatman-amigo
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time

def send_message(driver, recipient, message):
    try:
        driver.get(f"https://www.instagram.com/{recipient}/")
        time.sleep(10)
        driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div/div/div[1]/div[1]/div[2]/div[2]/section/main/div/header/section/div[1]/div[1]/div/div[2]').click()
        time.sleep(7)
        textarea_element = driver.find_element(By.CSS_SELECTOR, '[aria-label="Message"]').send_keys(message)
        submit_button = driver.find_element(By.XPATH, "/html/body/div[2]/div/div/div[2]/div/div/div/div[1]/div[1]/div[2]/section/div/div/div/div[1]/div/div[2]/div/div/div/div/div/div[2]/div/div/div[2]/div/div/div[3]")
        submit_button.click()
        return "Message sent successfully."
    except Exception as e:
        return f"Error sending message: {str(e)}"

features/send/send_message.py
anupammaurya6767/aatman-amigo
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time

 def send_sticker(driver, recipient, sticker_url):
        try:
            driver.get(f'https://www.instagram.com/direct/t/{recipient}/')
            time.sleep(2)
            driver.execute_script(f'window.open("{sticker_url}", "_blank");')
            time.sleep(2)
            self.driver.switch_to.window(self.driver.window_handles[1])
            time.sleep(2)
            submit_button = driver.find_element_by_xpath('//button[@type="submit"]')
            submit_button.click()
            driver.close()
            self.driver.switch_to.window(self.driver.window_handles[0])
            return "Sticker sent successfully."
        except Exception as e:
            return f"Error sending sticker: {str(e)}"

features/send/send_stickers.py
anupammaurya6767/aatman-amigo
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time

def send_video(driver, recipient, video_path):
        try:
            driver.get(f'https://www.instagram.com/direct/t/{recipient}/')
            time.sleep(2)
            video_input = driver.find_element_by_xpath('//input[@accept="video/mp4,video/x-m4v,video/*"]')
            video_input.send_keys(video_path)
            time.sleep(2)
            submit_button = driver.find_element_by_xpath('//button[@type="submit"]')
            submit_button.click()
            return "Video sent successfully."
        except Exception as e:
            return f"Error sending video: {str(e)}"

features/send/send_video.py
anupammaurya6767/aatman-amigo
from api.insta_api import AatmanAmigo
from utils.constants import username, password

# Initialize the AatmanAmigo API
insta_api = AatmanAmigo()

try:
    # Login to Instagram
    insta_api.login(username=username, password=password)

    # Send a message
    recipient = "your recipient"
    message = "Hello, Instagram!"
    insta_api.send_message(recipient, message)

    # Send an image
    recipient = "tanjiro_0_3"
    image_path = "/Users/aditya/Downloads/d.png"
    insta_api.send_image(recipient, image_path)


except Exception as e:
    print(f"Error: {str(e)}")

finally:
    # Close the API
    insta_api.close()

main.py
anupammaurya6767/aatman-amigo
# constants.py

# URL for WhatsApp Web
INSTA_WEB_URL = "https://www.instagram.com/"

# File paths for WebDriver executables
DRIVER_PATH = "drivers/chromedriver.exe"
GECKO_DRIVER_PATH = "drivers/geckodriver.exe"

# Timeout settings
LOGIN_TIMEOUT_SECONDS = 10
SEND_MESSAGE_TIMEOUT_SECONDS = 5

# API keys and tokens (if applicable)
API_KEY = "your_api_key_here"
API_SECRET = "your_api_secret_here"

# Instagram credentials
username = "your_username"
password = "your password"

utils/constants.py
anupammaurya6767/aatman-amigo
# In your WhatsApp API project, a `helpers.py` file typically contains utility functions and helper methods that can be used across various modules and features within your project. These helper functions are meant to simplify common tasks, promote code reuse, and enhance the overall organization of your codebase.

# Here's an example of what a `helpers.py` file might look like:

# ```python
# helpers.py

from selenium.common.exceptions import NoSuchElementException
import time

def find_element_with_retry(driver, xpath, max_attempts=3):
    """
    Helper function to find an element by XPath with retry.
    
    :param driver: WebDriver instance
    :param xpath: XPath expression to locate the element
    :param max_attempts: Maximum number of attempts to find the element
    :return: WebElement if found, None if not found after max_attempts
    """
    attempts = 0
    while attempts < max_attempts:
        try:
            element = driver.find_element_by_xpath(xpath)
            return element
        except NoSuchElementException:
            attempts += 1
            time.sleep(2)  # Wait for 2 seconds before retrying
    return None

def send_message_with_retry(driver, contact_name, message, max_attempts=3):
    """
    Helper function to send a message with retry.
    
    :param driver: WebDriver instance
    :param contact_name: Name of the contact to send the message to
    :param message: Message text to send
    :param max_attempts: Maximum number of attempts to send the message
    :return: True if message sent successfully, False if not sent after max_attempts
    """
    contact_element = find_element_with_retry(driver, f"//span[@title='{contact_name}']")
    if contact_element:
        contact_element.click()
        message_box = find_element_with_retry(driver, "//div[@class='_2S1VP copyable-text selectable-text']")
        if message_box:
            message_box.click()
            message_box.send_keys(message)
            message_box.send_keys(Keys.RETURN)
            return True
    return False

# In this example, `helpers.py` defines two utility functions:

# 1. `find_element_with_retry`: This function is used to find an element on a web page by XPath expression with a retry mechanism. It retries a specified number of times (default is 3) before giving up if the element is not found.

# 2. `send_message_with_retry`: This function simplifies the process of sending a message to a contact with a retry mechanism. It attempts to find the contact, click on it, and send the message. If the contact or message box cannot be found or if sending the message fails, it retries a specified number of times.

# These helper functions can be imported and used in various modules of your WhatsApp API project, reducing code duplication and enhancing readability.
utils/helpers.py
anupammaurya6767/aatman-amigo