Send WhatsApp Messages with Python
Introduction:
WhatsApp has become an integral part of our daily communication, and sometimes, automating messages can save you time and effort. In this blog post, we will explore how to send a WhatsApp message programmatically using Python. We’ll utilize the pywhatkit library and some additional tools to make this process seamless. By the end of this tutorial, you’ll be able to send WhatsApp messages with just a few lines of Python code.
Prerequisites:
Before we dive into the code, make sure you have the following prerequisites in place:
The pywhatkit library: Install it using pip with the following command:
pip install pywhatkit
The pynput library: Install it using pip with the following command:
pip install pynput
Getting Started:
Once you’ve installed the required libraries, let’s walk through the Python code to send WhatsApp messages:
import pywhatkit
import time
from pynput.keyboard import Key, Controller
# Set the receiver's mobile number (include country code)
phone_no = "+919876543210"
# Set the message to be sent
message = "Hi, how are you?"
# Open WhatsApp Web
pywhatkit.sendwhatmsg_instantly(phone_no, message)
# Wait for a few seconds to allow WhatsApp Web to load
time.sleep(10)
# You can change the time according to you
# Simulate a keyboard press to send the message
keyboard = Controller()
keyboard.press(Key.enter)
keyboard.release(Key.enter)
Explanation of the Code:
- Import the necessary libraries, including pywhatkit, time, and pynput.
- Set the
phone_no
variable to the recipient's mobile number, including the country code. - Set the
message
variable to the message you want to send. - Use
pywhatkit.sendwhatmsg_instantly()
to open WhatsApp Web and send the message instantly. - Wait for a few seconds (in this case, 10 seconds) to allow WhatsApp Web to load properly.
- Simulate a keyboard press of the Enter key using the pynput library to send the message.
Conclusion:
You’ve successfully written Python code to send WhatsApp messages programmatically using the pywhatkit and pynput libraries. This automation can be handy for various use cases, such as sending regular reminders or notifications.
Please note that automating WhatsApp messages should be used responsibly and in compliance with WhatsApp’s terms of service. Additionally, keep your credentials and code secure.
Happy coding, and enjoy automating your WhatsApp messages!
Still you have any issue regarding the code, Contact me on LinkedIn.