Automate Whatsapp Web Using Python

insecurecoders
5 min readAug 4, 2020

--

Photo by Mika Baumeister on Unsplash

So, you have a list of contacts who you need to send Whatsapp messages to and the number of contacts is about 50–100. To top it all of you have to send them a message which specifically addresses them.

Really becomes difficult when you can’t even use the broadcast feature doesn’t it?

Well, the good news is there is a way to automate this using python.

Want to know how?

All you need is a laptop, an internet connection, an IDE to run python on and a cup of coffee :)

Prerequisites

You will need selenium and pandas installed. You will also need chrome webdriver downloaded. Download the one relevant for your OS.

Now you have all of them installed. The next bit is to import using our IDE.

I personally use Pycharm

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

If the above portion is a bit confusing. Don’t worry as we go along in the code you will understand it with ease.

The process

Now then let's get on to adding certain useful options to chrome. What the below piece of code does is basically add an option to store your session details. This is done so that you don’t necessarily have to log in to Web Whats-app every-time. It can also store details for other accounts such as Google or Facebook as well.

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=user-data")

Now we need to initialize chrome. For that, we add the below lines that specify the path to the “chromedriver.exe” and to add the above option as we initialize chrome. We also can add an option to allow maximum wait time for an element to load on a webpage. So that it doesn’t throw an error at us all the time.

Usually, because python runs the next line of code faster than an element on the webpage can load. This depends on your Web browser, Internet connection, and system configuration.

So to avoid the hassle we add a 60 second wait time for the element to load. Don’t worry if the element loads sooner the code will perform the action before 60 seconds. For the advanced coders out there. I’m gonna go on a limb and say it’s similar to the async method.

driver = webdriver.Chrome(options=chrome_options, executable_path="C:/path/to/chromedriver")wait = WebDriverWait(driver, 60)
print("Chrome opened successfully!")

Once chrome is initialized let's go ahead and access the Whats-app web URL.

Web_whatsapp = 'https://web.whatsapp.com/'  # To go to whatsapp web
driver.get(Web_whatsapp)
print("Accessing Whatsapp web")

Now comes the interesting part before the loop.

We need an excel file to be able to read the data from in order to address the contact, concatenate our message, and search for the contact using their phone number.

In order to do that we can use pandas to create a data frame

df = pd.read_excel("C:\\Path\\to\\Excel\\file.xlsx")
Number = df['Column name for phone number exactly '].tolist()
Name = df['Column name for the name of the contact'].tolist()
Variable = df['Column name for the variable to send to the contact which is going to be contacted to the body of the message'].tolist()

Now, why do we use pandas?

Honestly, I found that reading data from an excel file and then converting it into a list helped me maintain them as strings. Obviously, if you have a better way to derive a list. Please feel free to do so. The objective is to have a separate list of all the values for a column.

We enter the column names for the relevant variables inside the single quotes.

The excel format would look something like this

So now my code would look something like this

df = pd.read_excel("C:\\Path\\to\\Excel\\file.xlsx")
Number = df['Number'].tolist()
Name = df['Name'].tolist()
Variable = df['Something variable'].tolist()

Great now that we have the data read from a file. Let's proceed to make a loop that iterates through all the columns in a row-wise manner.

Basically it iterates through multiple lists at the same time.

Here we need “itertools”

for i, j, k in zip(Number, Name, Variable):
Search = wait.until(EC.element_to_be_clickable((By.XPATH,"//div[@class='_3FRCZ copyable-text selectable-text']")))
time.sleep(2)

Search.send_keys(i)
time.sleep(1)
Search.send_keys(Keys.ENTER)
time.sleep(3)

Message = driver.find_elements_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')[0]
time.sleep(2)

Message.send_keys('Hello ' + str(j) + ',')
time.sleep(1)
Message.send_keys(Keys.SHIFT, Keys.ENTER)
Message.send_keys(Keys.SHIFT, Keys.ENTER)
Message.send_keys('This is just a test to see if you got a variable message ' + str(k))
time.sleep(1)
Message.send_keys(Keys.ENTER)
print('Sent to ' + str(j))

So this is a loop that goes through each and every item in the lists and then adds them to the places we specify. So as per the excel screenshot, I’ve attached. The code will iterate something like

for i, j, k in zip(Number, Name, Variable):
Search = wait.until(EC.element_to_be_clickable((By.XPATH,"//div[@class='_3FRCZ copyable-text selectable-text']")))
time.sleep(2)

Search.send_keys('9973189122')
time.sleep(1)
Search.send_keys(Keys.ENTER)
time.sleep(3)

Message = driver.find_elements_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')[0]
time.sleep(2)

Message.send_keys('Hello Mr. Insecure coder')
time.sleep(1)
Message.send_keys(Keys.SHIFT, Keys.ENTER)
Message.send_keys(Keys.SHIFT, Keys.ENTER)
Message.send_keys('This is just a test to see if you got a variable message Websitelink.com')
time.sleep(1)
Message.send_keys(Keys.ENTER)
print('Sent to Mr. Insecure coder')

To help understand a little better. “Search ”variable is the path to the search box in Web Whatsapp.

While the “Message” variable is the path to the chat box in Web Whatsapp.

“Keys.Shift, Keys.ENTER” is to go to a new line in the chatbox.

“Keys.ENTER ” is to send the message in the chatbox or Enter a chat in the search element.

Well, I hope this has helped make your lives a little easier or even better. Helped you free up some time to go pursue your hobby for the day.

So once you have the code set. Kick back and relax.

Photo by Simon Migaj on Unsplash

Feel free to suggest any kind of edits or improvements to the code.

The limitation of this code is even if the number is not present on whatsapp it may send the next message to the person that was sent the previous message. You may have to run the code and log in twice in order to ensure chrome records the session details/ user login details for whatsapp. You can use more than three variables as well. But make sure you make the relevant changes in the code by setting more variables and more columns in excel.

End result sent on WhatsApp.

Hi Mr. Insecure coder

This is just a test to see if you got a variable message Websitelink.com

Cheers guys.
Photo by Ian Schneider on Unsplash

--

--

insecurecoders

In search of a secure job with our insecure coding skills