Here’s how you can communicate using Python! (Part — 2)

DSP
Techloop
Published in
10 min readJul 1, 2020

Well, hello everyone! Welcome back to the second part of communicating using Python!

In the first part, you successfully sent emails using Python. In this part, we will go on yet another journey and we’ll see how we can use Python for more interesting purposes!

SENDING TEXT MESSAGES WITH PYTHON

Let’s try to send text messages using Python!

People in the 21' st century are more likely to be closer to their phones than to their PCs. This is the reason why many companies are shifting from traditional email to modern SMS.

Sending text messages or SMS (Short Message Service) utilizes GSM (Global System for Mobile Communication) to send strings of alphanumeric characters from one mobile device to another. To send an SMS using software such as Python, you need a GSM modem connected to your PC which, to be frank, is a pain to set-up and work with.

So, to work around the problem, many companies provide APIs (Application Programming Interface) to send SMS from a virtual phone number. In this tutorial, we’ll be using one such wonderful API, which is Twilio’s REST API.

Twilio is a leading communications API provider. It provides a suite of APIs designed to give applications customizable communications services such as SMS, voice calls and video calls as well!

So, for this purpose, all that we as developers need to do is to just go to www.twilio.com and sign up for a free account. After that, we need to register for a trial virtual number. This is the number that we will have to use in our program to send messages! Setting everything up is a piece of cake and you’ll surely be able to do that without facing any issues.

NOTE: During signing up for an account make sure you provide your phone number. This is an important step because the trial version of Twilio that we will be using allows sending messages from your virtual number to your registered phone number.

A trial virtual number is almost like an internet presence of yourself but with a separate number and location. In the case of Twilio, this number is also known as your Twilio sandbox number. So, in the upcoming code-along session, I might use the two words interchangeably, so, just giving you all a heads up before I begin.

NOTE: Oh, and another small thing! Before we begin typing the code, don’t forget to execute “pip install twilio” in your command line to download the module which will make our work seamless.

Also, I think it’s best if you open your browser and log in to Twilio and keep your dashboard open. We will need a few details from that page. Your dashboard should look like this if you set everything up properly.

Twilio dashboard page

After the Twilio module has been downloaded, head over to your IDE of choice and get ready for the code-along session!

Sending your first text message using Python

from twilio.rest import Client""" The account SSID and auth_token are used to sign in to your twilio account """accSSID = 'Account SSID from your Twilio Dashboard'
authtoken = 'Auth_token from your Dashboard'
client = Client(accSSID,authtoken)MyTwilioNumber = 'virtual country code + your twilio number'
myCellNumber = 'your country code + your phone number'
message=client.messages.create(body='Hello, this is a trial message'
,from_=MyTwilioNumber,to=myCellNumber)

Now let us analyze the code.

First, we import the Client class from the twilio module to initialize a client session.

Next, open your dashboard for your Twilio account on your browser and you should see something called account SSID and authorisation token (auth token). Copy those two into your Python program.

After that, we create an instance of the client class and sign-in to our Twilio account from Python by calling the Client() method.

And finally, add the numbers into your code and send your message using the create() method. This command creates and sends the text message from your Twilio sandbox number to your cell number.

So, what are you waiting for? Execute the program and you should see a message pop up in your cell phone.

Congratulations! You’ve successfully sent a text message using Python!

NOTE: The trial version of Twilio that we are using also has a limit on the number of text messages sent, but this is enough for development purposes and small projects.

Whew! That’s another popular communication mode covered using Python! But, hold up… There is another very popular communication medium as well right? You might use it everyday…. Can you guess it?

Yes! It’s Whatsapp! Approximately 2 billion people in the world use Whatsapp. With 65 billion messages per day and 29 million Whatsapp messages sent per minute, it’s appropriate to call it one of the most popular communication modes in the 21’ st century.

And yes, we’re gonna send a Whatsapp message using Python. So buckle up, let’s get this final section done right as rain!

Sending Whatsapp messages using Python

Sending Whatsapp messages using Python is a bit tricky. There are no APIs available for doing so for regular users, so we could work-around our problem in two ways. The first one is by utilising ADB (Android Debug Bridge) which allows you to communicate with an android device with ease and execute different commands through Python, to perform tasks. The second one utilises a Python framework and the web-based app of Whatsapp to send messages. The first one is pretty labour intensive and honestly speaking, it requires you to have a strong foundation of android. The latter is a bit more…. chill? Which is why for this section, we’ll be using the second approach to send Whatsapp messages.

For our task we’ll be using Whatsapp web, so, if you think about it, we’ll need a way to navigate through the web page. Now how can we do that? Hmmm. That’s a nice question to ponder about.

If you’ve ever faced advertisements or surveys while browsing, you might’ve tried to remove it from your way by using the inspect element feature of Chrome. Try it on any particular website right now. As soon as you open the inspect element window, you might see a lot of stuff like “Class”, “Style” and other stuff that is bound to zoom right over your head if you aren’t a full-fledged web developer.

Let me simplify it for you.

See, every web page consists of a ton of elements and every element has a kind of identification tag of its own. So, if there was a way we can get something like a unique address for each element, we would be able to describe any element on the page just by that address. Makes sense?

So, if you saw something called “Class” in the inspect element window, you might be thinking that it’s a possible way to use it to navigate the web page. Like a class might be “header” or “footer” or “navbar container”. So by saying “header”, I would know that you are referring to the top of the page. If this is what you are thinking, well done! You’re on the right track.

I would like to tell you that this is the solution but unfortunately, it’s not. Consider a class like a real-life class. A real-life class has plenty of students, right? Similarly, a class on a web page might be used for different elements on the same page.

Let’s consider the Whatsapp web page itself.

We aim to type a message in the message box, right? So, let’s go ahead and see what class this element falls under.

You can see that the class of that input field is _2S1VP copyable-text selectable-text.

Also, if you look carefully, you might notice another input field on the same page and this is where the problem starts. It’s of the same class as the input field as above!

Check this out.

So, I think we’ve justified the fact that we cannot identify elements by their class.

So what do we do??

There is another unique id that we can exploit. That is the XPath of the element.

XPath is short for XML Path. It is used to locate elements in an XML document. XML stands for Extensible Markup Language and it is a markup language similar to HTML (Hypertext Markup Language). It is used to describe elements of data, while HTML displays that data. That is why XML and HTML go hand in hand for most responsive web sites.

So, XML kind of puts an identification tag called the XPath on each element. It is unique for every element on a web page and that is why we are going to use it to find our desired elements on a website.

NOTE: We will be using the web version of Whatsapp, so, we need to use the selenium module which is used for browser automation. So go to your command line and execute “pip install selenium”.

We will need just one more thing for our task.

See, we will use Chrome for our task, but the issue with the official chrome is that it sometimes throws some really bad errors, since it is kind of configured to stop bots from accessing the browser. If you use Chrome, I would suggest you uninstall it for the time being, because it might interfere with our program.

We will need Chromium, the open-source version of Chrome to do our task. You can download it from here. Also, we cannot tell Python to click a particular software icon, so, we need something that allows us to access Chromium without having to manually access it. That something is called a Chrome driver. You can download it from here. Extract and save the chromedriver file in a suitable location. We will need this location in our program, so you better save it in a common location such as your Downloads folder or your Documents folder.

Now we are all set for our code! Head over to your IDE of choice and get ready for the code-along session!

Sending your first Whatsapp message using Python

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
location = 'The_full_file_path_where_your_Chromedriver_is_stored'driver = webdriver.Chrome(location)
driver.get('https://web.whatsapp.com/')

Firstly, as usual, we need to import the modules we will be using into our program.

Next, we need to direct the selenium web driver to the Chrome web driver location. So, let’s initialize a new variable called location which specifies the directory of the Chrome web driver.

After that, we create an instance of the webdriver Class so that we can access all the methods of that class and let’s use that to open up Whatsapp Web on your browser by using the get() method.

Coming back to the editor…

name = input('Enter the name of the target person/group : ')
msg = input('Enter your message : ')
input('Enter something after scanning QR Code....')user = driver.find_element_by_xpath('//span[@title = " {}"]'.format(name))user.click()

We have to specify the target and format a suitable message. To do that we initialize the variables “name” and “msg” and fill in the details accordingly.

Now, another issue is that even if you are signed into Whatsapp web beforehand, you’ll still need to sign in and do that QR code thing all over again. So to prevent problems with signing in let’s halt the program for some time until we sign in properly. For that, we can call the input function and wait for a keypress from the user.

Now to find that particular element in the web page, we need the XPath of the element. You can find the Xpath of any element in Chrome by following this tutorial. But for your code, you may use the XPath that I have provided in the code snippet.

Next, we need to find the name of the person we are trying to send the message to by searching for the appropriate X_Path. The user.click() is used to, you guessed it, click the element.

Again, head back to your editor and type in the next code snippet.

inp_xpath = '//*[@id="main"]/footer/div[1]/div[2]/div/div[2]'
input_box = driver.find_element_by_xpath(inp_xpath)
input_box.click()
input_box.send_keys(msg + Keys.ENTER)
time.sleep(1)

The next thing to do is to click on the “Type your message here” element. So that we can type in our message. That is exactly what we do when we execute input_box.click()

And finally, to send the message, we use the send_keys() method. The send_keys() method sends the message by automatically typing in the message body and pressing the ENTER key by Keys.ENTER. The time.sleep(1) is used to halt the program for 1 second. This is not required for our code which is used to send just one Whatsapp message. But if you are sending multiple messages, say by using a loop, then this statement is a must.

Now execute the program! Type in your message and choose your target and wait for the message to be sent!

Congratulations! You’ve successfully sent your first Whatsapp message using Python!

THE SAD NEWS: Whenever a web app is updated, the XPath of every element changes. This code given above will work for this version of Whatsapp Web but might not work if it is updated. So, if the code above is not working, I suggest you follow the tutorial given to get the new XPath of the element and then use it in your code.

Well, that brings us to the end of this article. Hope I could explain everything clearly. Leave your thoughts and comments and do leave a clap if you think I deserve it.

Ciao!

--

--

DSP
Techloop

An avid adventurer, wandering the magical land of Python!