Sending Unlimited WhatsApp Messages Using Python and Selenium

Python Python Selenium

In this article, we will explore a Python script that utilizes the Selenium library to send unlimited messages on WhatsApp. This script automates the process of sending messages to multiple contacts by leveraging the WhatsApp Web interface. The script uses the Chrome WebDriver along with various Selenium options to mimic human-like interactions.

Why Automation Matters:

Contents

As our lives become increasingly digital, the need for efficient communication tools grows exponentially. WhatsApp, a widely used messaging platform, is no exception. Automation allows users to interact with these platforms in ways that were once thought impossible, providing new avenues for productivity and convenience.

The Power of Python and Selenium:

Python, a versatile and powerful programming language, is combined with Selenium, a popular web automation framework, to create a script that emulates human interactions on the WhatsApp Web interface. This combination offers a user-friendly and efficient solution for sending messages at scale.

Code Overview:

The provided Python script performs the following actions:

  1. Imports necessary modules from the Selenium library and others.
  2. Defines user-specific variables such as the sender’s WhatsApp name, a test message, country code, and a list of recipient numbers.
  3. Sets up Chrome WebDriver options, including headless mode and user data directory.
  4. Initializes the Chrome WebDriver and opens the WhatsApp Web interface.
  5. Scans the QR code for authentication.
  6. Waits for WhatsApp to load and locates the search box.
  7. Enters the recipient’s name in the search box and clicks on the corresponding contact.
  8. Enters a WhatsApp link in the message box and clicks on the send button.
  9. Iterates through a list of recipient numbers and sends a test message to each one.
  10. Handles invalid numbers and prints status messages.

Detailed Explanation:

  1. User Configuration:
    • The script begins by allowing the user to input their WhatsApp name, a test message, the country code, and a list of recipient numbers.
my_number_saved_name = "My Jio (You)"
my_message = "This is testing MessageBox"
country_code = "91"
number_list = ['0000000000', '8534867764', '8534867764', '853486776','8126790']

WebDriver Setup:

  • The script configures various options for the Chrome WebDriver, such as headless mode, user data directory, and window size.
options = Options()
# ... (other options)
driver = webdriver.Chrome(options=options)

WhatsApp Web Authentication:

  • The script opens the WhatsApp Web interface, waits for the user to scan the QR code, and maximizes the browser window.
driver.get('https://web.whatsapp.com/')
driver.maximize_window()

Searching and Sending Messages:

  • The script searches for the specified contact, enters a WhatsApp link, and sends a test message. It then iterates through the list of recipient numbers, handling invalid numbers along the way.
# Searching for contact
search_box = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,'//*[@title="Search input textbox"]')))
# ... (search and click on contact)

# Sending a test message
message_box = driver.find_elements(By.XPATH,'//div[@title="Type a message"]')
message_box[0].send_keys(f'wa.me/91123456890')
send_button = WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH,'//span[@data-icon="send"]')))
send_button.click()

Iterating Through Recipient Numbers:

After setting up the initial configurations and opening the WhatsApp Web interface, the script enters a for loop to iterate through the list of recipient numbers.

for number_index in range(len(number_list)):
    try:
        if number_list[number_index] == 0:
            continue
        
        last_link = driver.find_elements(By.XPATH, '//*[@id="main"]/div/div/div/div/div/div/div/div/div/div/div/div/div/span/span/a')[-1]

        # Execute JavaScript to set the href attribute
        new_link = f'https://wa.me/{country_code}{number_list[number_index]}'
        driver.execute_script(f'arguments[0].setAttribute("href", "{new_link}")', last_link)
        last_link.click()

        try:
            time.sleep(2)
            # Checking for Invalid POP
            driver.find_element(By.XPATH,'//*[@id="app"]/div/span[2]/div/span/div/div/div/div/div/div[2]/div/button/div/div').click()
            time.sleep(1)
            print(f"[-] Number is Invalid : {country_code}{number_list[number_index]}")
        except Exception as e:
          	message_box = driver.find_elements(By.XPATH,'//div[@title="Type a message"]')
            message_box[0].clear()
            message_box[0].send_keys(my_message)

            # Click on Send Button
            send_button = WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH,'//span[@data-icon="send"]')))
            send_button.click()
            
            # Click on Text Box
            time.sleep(1)
            search_box.send_keys(my_number_saved_name)

            # Click on Search input textbox
            time.sleep(1)
            search_number.click()

            print(f"[+] Message is Sent : {country_code}{number_list[number_index]}")
            # Click on the message box
            time.sleep(1)
            # ... (sending the message and handling success)
    except Exception as e:
        print("Something went wrong {e}")

print("Thanks for using WhatsApp Number Verification Service.")
driver.quit()

Finally, the loop continues to execute, sending messages to the specified recipients, handling invalid numbers, and providing feedback to the user. The script concludes with a thank-you message and quits the WebDriver.

I hope this explanation clarifies the role of the for loop in the script.

This is the Final Code:

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


# Enter Your Current WhatsApp Number Name or Number
my_number_saved_name = "My Jio (You)"
my_message = "This is testing MessageBox"
country_code = "91"
number_list = ['0000000000', '8534867764', '8534867764', '853486776','8126790']

# ALL Selenium Required Options for WebDriver
options = Options()
options.headless = True
options.add_argument(f"--user-data-dir=C:/Users/{getpass.getuser()}/AppData/Local/Google/Chrome/User Data/Default")
options.add_argument("--profile-directory=Default")
options.add_argument("--window-size=1920,1080")
options.add_argument('--ignore-certificate-errors')
options.add_argument('--allow-running-insecure-content')
options.add_argument("--disable-extensions")
options.add_argument("--proxy-server='direct://'")
options.add_argument("--proxy-bypass-list=*")
options.add_argument("--start-maximized")
options.add_argument('--disable-gpu/')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--no-sandbox')
options.add_argument("--log-level=3")
options.add_argument('--hide-scrollbars')
options.add_argument("--disable-popup-blocking")
options.add_experimental_option("excludeSwitches",["enable-automation"])
options.add_experimental_option("useAutomationExtension",False)

# Setup the Chrome Driver Object
driver = webdriver.Chrome(options=options)
user_agent = driver.execute_script("return navigator.userAgent;")

# Opening the browser window
driver.get('https://web.whatsapp.com/')
options.add_argument('--user-agent={}'.format(user_agent))

# Scan the QR Code
print(f"Scan Your QR Code Or Wait Until Logged In " + '\n')
driver.maximize_window()

# Wait until whatsapp logged In
wait = WebDriverWait(driver, 1200)
reset = wait.until(EC.visibility_of_element_located((By.XPATH,'//*[@id="pane-side"]')))

# Click on Text Box
search_box = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,'//*[@title="Search input textbox"]')))
search_box.send_keys(my_number_saved_name)
time.sleep(3)

# Click on Search input textbox
search_number = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,'//span[text()="(You)"]/parent::div')))
search_number.click()

message_box = driver.find_elements(By.XPATH,'//div[@title="Type a message"]')
message_box[0].send_keys(f'wa.me/91123456890')

# Click on Send Button
send_button = WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH,'//span[@data-icon="send"]')))
send_button.click()


for number_index in range(len(number_list)):
    try:
        if number_list[number_index] == 0:
            continue
        
        last_link = driver.find_elements(By.XPATH, '//*[@id="main"]/div/div/div/div/div/div/div/div/div/div/div/div/div/span/span/a')[-1]

        # Execute JavaScript to set the href attribute
        new_link = f'https://wa.me/{country_code}{number_list[number_index]}'
        driver.execute_script(f'arguments[0].setAttribute("href", "{new_link}")', last_link)
        last_link.click()

        try:
            time.sleep(2)
            # Checking for Invalid POP
            driver.find_element(By.XPATH,'//*[@id="app"]/div/span[2]/div/span/div/div/div/div/div/div[2]/div/button/div/div').click()
            time.sleep(1)
            print(f"[-] Number is Invalid : {country_code}{number_list[number_index]}")
        except Exception as e:
            message_box = driver.find_elements(By.XPATH,'//div[@title="Type a message"]')
            message_box[0].clear()
            message_box[0].send_keys(my_message)

            # Click on Send Button
            send_button = WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH,'//span[@data-icon="send"]')))
            send_button.click()
            
            # Click on Text Box
            time.sleep(1)
            search_box.send_keys(my_number_saved_name)

            # Click on Search input textbox
            time.sleep(1)
            search_number.click()

            print(f"[+] Message is Sent : {country_code}{number_list[number_index]}")
            # Click on the message box
            time.sleep(1)
    except Exception as e:
        print("Something went wrong {e}")

print("Thanks for using WhatsApp Number Verification Service.")
driver.quit()

Leave a Reply

Your email address will not be published. Required fields are marked *