Master Method: Send & Automate Whatsapp Messages with Python

How to Automate Whatsapp Messages With Python Selenium and Pywhatkit:

Automate WhatsApp messages with just two lines of python code, and also you’ll schedule to send messages in the dark while you’ll be sleeping. To automate your WhatsApp you wish python installed in your system and any text editor or IDE (Integrated Development Kit).

Sometimes we want to schedule and send messages at a specific time. Hence WhatsApp not providing this feature to schedule and message so, i feel to supply the tutorial to resolve this problem. this is often very simple so let’s start.
Install required packages

To automate WhatsApp you wish to put in pywhatkit the package. This package is providing many awesome features with WhatsApp you’ll take a look at here. So to put in pywhatkit open your terminal and run the subsequent command:

pip install pywhatkit

 

Send a scheduled message:

The parameters are

  • phone_num (required) — sign of the target with country code
  • message (required) — Message that you just want to send
  • time_hour (required) — Hours at which you would like to send a message in 24-hour format
  • time_min (required) — Minutes at which you would like to send a message
  • wait_time (optional, val = 20) — Seconds after which the message are going to be sent after opening the net
  • print_wait_time (optional, val = True) — Will print the remaining time if set to true
  • tab_close (optional, val = False) — True if you wish to shut the tab after sending the message

Example

import pywhatkit as pwk

pwk.sendwhatmsg("+911212121212","This is test message", 12,14) 

 

Send a picture with caption:

To send a picture, Gif, or video with a caption we’ve to use sendwhats_image(…) method.

The parameters are

  • phone_no (required) — sign of the target with country code
  • img_path (required) — Path to image or gif or video
  • caption (required) — The text that ought to appear below images
  • wait_time (optional, val = 15) — Seconds after which the message are going to be sent after opening the online

Example:

import pywhatkit as pwk

pwk.sendwhats_image(phone_no="+911212121212",img_path="path_to_image",caption="This is test message")

 

Send Bulk WhatsApp Messages Using Python Selenium:

WhatsApp Web

WhatsApp Web could be a feature of WhatsApp that permits you to operate your
WhatsApp from your laptop or desktop browser. To use WhatsApp web are so simple one of web application, simply open a chrome browser in your computer and type the website url  web.whatsapp.com, and simply scan the QR code by using your phone, and your WhatsApp messages will appear on your chrome browser. Here you’ll message anyone or any group or can see WhatsApp status.

 

Send Bulk messahes

 

The script starts by importing all the specified modules.

  • The art module is employed to make and display ASCII art for the script. If you wanna understand how it works, you’ll be able to take a look at this blog.
  • Time is employed to halt program execution for a few seconds using time.sleep()
  • OS is employed to run OS commands within the script.
  • The platform module is employed to spot the OS.

Together, os and platform are wont to clear the screen, as you’ll be able to see
here.

  • Colorama and termcolor are wont to display colored console output of the script. If you wanna know more about them, you’ll take a look at this blog.
  • Pandas is employed to read data from the excel file.
  • Datetime is employed to seek out the present date and time.
  • We’ve got selenium. of these import statements you see here are just importing
  • Required classes and functions from selenium.

 

Download ChromeDriver Here

 

import art, time, os, platform
from colorama import init, Fore
from termcolor import colored
import pandas as pd
import datetime
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

FILE_LOC = "data.xlsx"
SRNO = 'SRNO'
NAME = 'Name'
PHONENUMBER = 'Phone Number'
MESSAGE = 'Message'
REPLACENAME = '{{name}}'
URL = 'https://web.whatsapp.com/'
WAITER_ELEMENT = "landing-title _3-XoE"
PHONE_NUMER_INPUT = "//*[@id='side']/div[1]/div/label/div/div[2]"
PERSON_DIV = "//*[@id='pane-side']/div[1]/div/div/div[1]/div/div/div[1]/div/div/img"
MESSAGE_INPUT = "//*[@id='main']/footer/div[1]/div[2]/div/div[1]/div/div[2]"
SEND_BUTTON = "//*[@id='main']/footer/div[1]/div[2]/div/div[2]/button"

driver = webdriver.Chrome('chromedriver.exe')
driver.implicitly_wait(10)
waiter = WebDriverWait(driver, 10)
data = []

def printData(message, type):
    if type == 'INFO':
        print('[' + colored(datetime.datetime.now().strftime('%H:%M:%S'), 'cyan') + '][' + colored('INFO', 'green') +  '] ' + message)
    elif type == 'WARNING':
        print('[' + colored(datetime.datetime.now().strftime('%H:%M:%S'), 'cyan') + '][' + colored('WARNING', 'yellow') +  '] ' + message)
    elif type == 'ERROR':
        print('[' + colored(datetime.datetime.now().strftime('%H:%M:%S'), 'cyan') + '][' + colored('ERROR', 'red') +  '] ' + message)

def read_data_from_excel():
    try:
        df = pd.read_excel(FILE_LOC)
        printData("Retrieving data from excel", 'INFO')
    except:
        printData("Excel 'data.xlsx' not found", 'ERROR')
    printData("Found {0} messages to be send".format(len(df.index)), 'INFO')
    for i in df.index:
        if '+' not in str(df[PHONENUMBER][i]):
            number = '+91' + str(df[PHONENUMBER][i])
        else:
            number = str(df[PHONENUMBER][i])
        output = {
            'SrNo': df[SRNO][i],
            'Name': df[NAME][i],
            'PhoneNumber': number,
            'Message': df[MESSAGE][i].replace(REPLACENAME, df[NAME][i])
        }
        data.append(output)

def send_whatsapp_message():
    global driver
    driver.get(URL)
    printData("Loading site...", 'INFO')
    waiter.until(EC.title_is("WhatsApp"))
    printData("Site loaded successfully...", 'INFO')
    printData("Waiting for user to log in using WhatsApp Web", 'INFO')
    waitCounter = 0
    while 1:
        try:
            waiter.until(EC.presence_of_element_located((By.XPATH, "//canvas[@aria-label='Scan me!']")))
            waitCounter+=1
            if waitCounter%1000 == 0:
                printData("Waiting for user to log in...", 'WARNING')
        except:
            printData("Logged in to WhatsApp", 'INFO')
            break

    for entry in data:
        driver.find_element_by_xpath(PHONE_NUMER_INPUT).send_keys(str(entry['PhoneNumber']))
        time.sleep(5)
        driver.find_element_by_xpath(PHONE_NUMER_INPUT).send_keys(Keys.ENTER)
        time.sleep(5)
        driver.find_element_by_xpath(MESSAGE_INPUT).send_keys(str(entry['Message']))
        time.sleep(5)
        driver.find_element_by_xpath(SEND_BUTTON).click()
        time.sleep(5)
        printData("Successfully send message to {0}, name: {1}".format(str(entry['PhoneNumber']), str(entry['Name'])), 'INFO')

if __name__ == '__main__':
    # Initialize colorama
    init()

    # Clear the screen
    if platform.system() == 'Windows':
        os.system('cls')
    else:
        os.system('clear')

    # Display ASCII art
    print(art.text2art("WhatsApp Python"))
    print(Fore.CYAN + "\nCreated By:" + Fore.RESET + " Vishesh Dvivedi [All About Python]\n")
    print(Fore.YELLOW + "GitHub: " + Fore.RESET + "   visheshdvivedi")
    print(Fore.YELLOW + "Youtube:" + Fore.RESET + "   All About Python")
    print(Fore.YELLOW + "Instagram:" + Fore.RESET + " @itsallaboutpython")
    print(Fore.YELLOW + "Blog Site:" + Fore.RESET + " itsallaboutpython.blogspot.com\n")


    # Read data from 'data.xlsx' file
    read_data_from_excel()

    # Send whatsapp message 
    send_whatsapp_message()

    # Close chromedriver
    driver.close()