You've successfully subscribed to Better Data Science
Great! Next, complete checkout for full access to Better Data Science
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.

PyWhatKit: How to Automate Whatsapp Messages with Python

PyWhatKit: How to Automate Whatsapp Messages with Python

Have a Whatsapp account? Know how to call Python functions? That's all you need to automate Whatsapp messages.

Did you ever want to automate your Whatsapp messages? Well, now you can, assuming you have at least one week of Python programming under your belt. The pywhatkit library allows you to send individual Whatsapp messages, send messages to groups, and even send images - all from Python! There are also options for playing YouTube videos and browsing the Internet, but these will be covered in the upcoming articles.

Today you'll learn how to send Whatsapp messages to yourself or anyone else through pywhatkit and Python. These are the areas we'll focus on:

  • How to Install PyWhatKit
  • How to Send Whatsapp Messages Instantly
  • Schedule Whatsapp Messages for Later
  • Send Whatsapp Messages Through a Python Script
  • Advanced Usage: Groups and Images

How to Install PyWhatKit

The package is available on PyPI, meaning you can install it through pip. Before we do that, let's create a new virtual environment based on Python 3.10. Once created, we can issue a pip command to install pywhatkit:

conda create --name pywhatkit_env python=3.10 -y
conda activate pywhatkit_env

pip install pywhatkit

In addition, I've also installed Jupyter and JupyterLab because that's the development environment I'll use for the first part of the article. You can do the same, but you're free to use a text editor instead.

To install and launch Jupyter:

pip install jupyter jupyter lab

jupyter lab

That's all we need to start playing around with pywhatkit.

How to Send Whatsapp Messages Instantly

Assuming you have Jupyter (or a text editor) running, proceed by importing the library:

import pywhatkit

The sendwhatmsg_instantly() function will send a Whatsapp message as soon as you run the code, hence the "instantly" in the name. Two parameters are required:

  • phone_no - A phone number to which you want to send the message. Don't forget to include the country code.
  • message - The actual message you want to send.

Let's see it in action:

pywhatkit.sendwhatmsg_instantly(
    phone_no="<phone-number>", 
    message="Howdy! This message will be sent instantly!",
)

If you aren't logged in to Whatsapp Web, you'll see this screen prompting you to scan a QR code with your phone:

Image 1 - Whatsapp Web login prompt (image by author)
Image 1 - Whatsapp Web login prompt (image by author)

Once scanned, you'll land on a new chat screen with your message populated in the input area. For some reason, the message isn't sent automatically, and you have to manually click on the send button. It's a bug in the library that will probably get fixed in future releases.

I'll show you later how to work around this bug, but for now, just hit the Send button.

You'll see the following, both on Whatsapp Web and Mobile:

Image 2 - Sending the first message through PyWhatKit (image by author)
Image 2 - Sending the first message through PyWhatKit (image by author)

And that's your first Whatsapp message sent!

But what if you want to schedule messages for a specific time? Let's cover that option next.

Schedule Whatsapp Messages for Later

Sometimes you want to send messages at a specific point in time. The pywhatkit package has a dedicated function for that called sendwhatmsg(). In addition to phone_no and message, it requires two additional parameters:

  • time_hour - Integer, represents the hour (24h format) in which you want to send the message.
  • time_min - Integer, represents the minute in which you want to send the message.

It works almost identically to our previous example:

pywhatkit.sendwhatmsg(
    phone_no="<phone-number>", 
    message="This is a scheduled message.",
    time_hour=9,
    time_min=47
)

But unlike the previous example, this function will output the time remaining until the message is sent:

Image 3 - Message scheduling with PyWhatKit (image by author)
Image 3 - Message scheduling with PyWhatKit (image by author)

After these 53 seconds, a Whatsapp Web browser window will open and you'll see the message text populated in the input field. As before, the message doesn't get sent automatically, and you have to manually click on the Send button.

Once sent, you'll see the message in the chat both on the Web and Mobile:

Image 4 - Sending a scheduled message through PyWhatKit (image by author)
Image 4 - Sending a scheduled message through PyWhatKit (image by author)

Now you know how to send messages instantly and how to schedule them. It would be nice if we didn't have to manually click on the button every time to send the message.

While the developers work on fixing this bug, let's take a look at how you can work around it.

Send Whatsapp Messages Through a Python Script

You'll need two additional Python libraries to automatically trigger the Send button. These are pyautogui and pynput.

The send_whatsapp_message() function does the following:

  1. Opens Whatsapp Web and populates the input field with the specified message.
  2. Sleeps for 10 seconds to ensure everything has loaded properly.
  3. Clicks on the screen to ensure the correct window/tab is selected.
  4. Presses and releases the Enter key on the keyboard to send the message.

If any of the steps fail, the exception is printed to the console.

Here's the entire code snippet for the function with a usage example:

import time 
import pywhatkit
import pyautogui
from pynput.keyboard import Key, Controller

keyboard = Controller()


def send_whatsapp_message(msg: str):
    try:
        pywhatkit.sendwhatmsg_instantly(
            phone_no="<phone-number>", 
            message=msg,
            tab_close=True
        )
        time.sleep(10)
        pyautogui.click()
        time.sleep(2)
        keyboard.press(Key.enter)
        keyboard.release(Key.enter)
        print("Message sent!")
    except Exception as e:
        print(str(e))


if __name__ == "__main__":
    send_whatsapp_message(msg="Test message from a Python script!")

I've saved this code to tester.py file, and now I'll run it through the Terminal:

python tester.py
Image 5 - Running a Python script through the Terminal (image by author)
Image 5 - Running a Python script through the Terminal (image by author)

You'll see the same Whatsapp Web browser tab open and the message field populated, but this time the message will be sent after a couple of seconds without your intervention.

Here's a full chat history:

Image 6 - Sending the last automated message through Python (image by author)
Image 6 - Sending the last automated message through Python (image by author)

And that's how you can work around the current bugs in the library. Let's briefly go over some more advanced use cases before calling it a day.

Advanced Usage: Groups and Images

You can also send messages to Whatsapp groups and send images with pywhatkit. Refer to these convenient functions built into the library:

  • sendwhatmsg_to_group(group_id: str, message: str, time_hour: int, time_min: int) - Used to send a message to a group.
  • sendwhatmsg_to_group_instantly(group_id: str, message: str) - Just like the previous function, but sends the message as soon as you run the code.
  • sendwhats_image(receiver: str, img_path: str) - Instantly sends an image to a number or a group. There's an optional caption parameter used to, well, caption the image. Keep in mind that the PNG file format isn't supported currently.

And that's pretty much all there is to pywhatkit Python library, at least regarding Whatsapp. Feel free to play around with these three functions on your own, I'm sure you can handle it!

The library also packs additional functionality for YouTube and general web browsing, but I'll leave these topics for another time.


Stay connected