How to send WhatsApp messages using Python ?

WhatsApp does not provide an official public API for sending messages or managing chats for regular accounts. The official API provided by WhatsApp is the WhatsApp Business API, which is primarily aimed at medium and large businesses to manage communication with their customers.

However, there are several third-party libraries and APIs developed by the open-source community that allows interaction with WhatsApp to a certain extent. These libraries utilize different techniques like web scraping and simulating user interaction with WhatsApp Web to achieve their functionality.

Note on Third-Party Libraries:

It’s crucial to note that using third-party APIs to send messages or automate interactions with WhatsApp is against WhatsApp’s terms of service. Your number can be banned from using WhatsApp if it’s detected to be sending automated messages or behaving in a bot-like manner. Always ensure that you respect privacy and adhere to all legalities when handling communications of any form.

1. Yowsup:

Yowsup is one of the widely known third-party implementations for interacting with WhatsApp. It’s a Python library that enables you to build applications that can send and receive WhatsApp messages.

2. WhatsApp Web API with Selenium:

A common method developers use to interact with WhatsApp is by automating the WhatsApp Web interface using a web automation tool, such as Selenium.

Example of sending a message using Selenium:

Here’s a basic example to illustrate the concept, though please remember the aforementioned note about adhering to WhatsApp’s terms of service.

Prerequisites:

  • Install Selenium: pip install selenium
  • Download the appropriate WebDriver for the browser you want to use (e.g., ChromeDriver for Chrome).

Sample Code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

# Set up the webdriver and open WhatsApp Web
driver = webdriver.Chrome(executable_path='path_to_your_chromedriver.exe')
driver.get('https://web.whatsapp.com/')
input("Press Enter after QR code is scanned...")

# Navigate to the chat
search_box = driver.find_element('xpath', '//*[@id="side"]/div[1]/div/label/div/div[2]')
search_box.send_keys("Your Contact Name")
search_box.send_keys(Keys.ENTER)

# Send a message
message_box = driver.find_element('xpath', '//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')
message_box.send_keys("Hello, this is a test message.")
message_box.send_keys(Keys.ENTER)

# Optional: Wait for some time and close the driver
time.sleep(5)
driver.quit()

3. Twilio API for WhatsApp:

As mentioned in the previous message, Twilio provides an API for WhatsApp, which allows you to send messages through the Twilio platform, using the WhatsApp Business API.

Sending messages to WhatsApp using Python can be achieved through the Twilio API. Twilio provides a flexible API for WhatsApp that allows you to send messages, media, and more without requiring you to manage the complex nuances of WhatsApp’s Business APIs.

Prerequisites:

  • Twilio Account: You’ll need to sign up for a Twilio account and obtain your Account SID and Auth Token.
  • Twilio WhatsApp Sandbox: Before using the API, you need to activate the Twilio WhatsApp Sandbox for testing, where you can send messages to your own WhatsApp account.

Steps:

1. Install Twilio:

Install the Twilio Python library using pip:

pip install twilio

2. Setup Twilio Account and Get Credentials:

After creating your Twilio account, go to the dashboard and get your Account SID and Auth Token. You’ll also need to activate the WhatsApp Sandbox and follow the instructions to send a message to the sandbox number.

3. Send a Message:

Here’s a basic example of sending a WhatsApp message using Twilio in Python:

from twilio.rest import Client

# Twilio credentials
account_sid = 'your_account_sid'
auth_token = 'your_auth_token'

# Create a Twilio client
client = Client(account_sid, auth_token)

# Send a message
message = client.messages.create(
    body="Hello, this is a test message!",
    from_='whatsapp:your_twilio_sandbox_number',
    to='whatsapp:your_personal_number'
)

print(f"Message sent with ID: {message.sid}")

Explanation:

  • account_sid and auth_token are your Twilio credentials which you’ll get from the Twilio dashboard.
  • your_twilio_sandbox_number is the number provided by Twilio for the sandbox environment. It should look like +14155238886.
  • your_personal_number is your own WhatsApp number to which the sandbox is connected. Make sure to include the country code (like +1234567890).

Note:

  • Ensure you follow all legal and ethical guidelines when sending automated messages.
  • Be sure to handle and manage user data with utmost care and comply with data protection regulations.
  • When you are ready to move to production, you need to apply for WhatsApp Business API access and set up a business profile. More information can be found on the Twilio website.

Additional Features:

Twilio’s API for WhatsApp also allows you to send media messages, manage message status feedback, create message templates, and much more, which you may explore as per your requirements.

For comprehensive documentation, visit Twilio’s documentation on sending WhatsApp messages.

Reminder:

Always respect user privacy, adhere to all applicable laws and guidelines, and follow WhatsApp’s terms of service when interacting with the platform programmatically. Use official APIs wherever possible to ensure compliance and reliability. Always secure user data and ensure that your use case does not infringe upon the rights or privacy of the users.

Leave a comment