Python | Whatsapp birthday bot


Have you ever wished to automatically wish your friends on their birthdays, or send a set of messages to your friend ( or any Whastapp contact! ) automatically at a pre-set time, or send your friends by sending thousands of random text on whatsapp! Using Browser Automation you can do all of it and much more!

First you must install these:-
1) Python Bindings for Selenium ( Browser Automation software )

pip install selenium

2) Chrome webdriver
Download Chrome driver from here: Chromedriver download page( choose your specific version )

How the bot does it

The script uses PySelenium package to open a Chrome webdriver window on which all tasks are done. It checks if the current date and month matches the ones in a json file. If yes, the ‘name’ attribute of it is returned which is used to find the corresponding chat in Whatsapp web(finding by xpath). The script then simulates click on the chat, opens it, types the message in the chat box and simulates a click on the send button.

What is JSON?

JSON stands for JavaScript Object Notation. It is a very simple and light way of storing data. Though it’s derived from JavaScript, it is language independent and is similar in looks to Python Dictionaries
Check out this article for more on JSON.

Below is the implementation

filter_none

edit
close

play_arrow

link
brightness_4
code

# get current date in required format
import datetime
  
# store the birthdates of your contacts
import json
   
from selenium import webdriver
   
# add a delay so that all elements of
# the webpage are loaded before proceeding
import time
  
# Global variable Do not use elsewhere
eleNM = None 
  
# This function is just to return a 
# string of the message required
def wish_birth(name):
    return "Happy Birthday " + name.split(" ")[0] + "!!"
  
# This function returns a list of values of some 
# attribute based on conditions on two attributes from the JSON file.
# use to return names of contacts having their birthday on current date.
def getJsonData(file, attr_ret, attr1, attr2, attr_val1, attr_val2):
      
    # Load the file's data in 'data' variable
    data = json.load(file)
    retv =[]
  
    # If the attribues' value conditions are satisfied, 
    # append the name into the list to be returned.
    for i in data:
        if(i[attr1]== attr_val1 and i[attr2]== attr_val2):
           retv.append(i[attr_ret])
    return retv
  
# Opening the JSON file (birthdays.json) in read only mode.
data_file = open("birthdays.json", "r")
namev =[]
print("Script Running")
  
# This will keep rerunning the part of 
# the code from 'while True' to 'break'.
# use to keep waiting for the JSON function
# to return a non empty list.
# In practice, this function will keep rerunning at 
# 11:59pm a day before the birthday and break out at 12:00am.
while True:
    try:
        # to get current date
        datt = datetime.datetime.now()
        namev = getJsonData(data_file, "name", "birth_month", "birth_date",
                                           str(datt.month), str(datt.day))
  
    except json.decoder.JSONDecodeError:
        continue
    if(namev !=[]):
        break
  
# ChromeOptions allows us use the userdata of chrome
# so that you don't have to sign in manually everytime.
chropt = webdriver.ChromeOptions()
  
# adding userdata argument to ChromeOptions object
chropt.add_argument("user-data-<LOCATION TO YOUR CHROME USER DATA>")
  
# Creating a Chrome webdriver object
driver = webdriver.Chrome(executable_path ="<LOCATION TO CHROME WEBDRIVER>"
                                                          options = chropt)
  
# delay added to give time for all elements to load
time.sleep(10)
  
print(namev)
  
# Finds the chat of your contacts (as in the namev list)
for inp in namev:
    try:
        eleNM = driver.find_element_by_xpath('//span[@title ="{}"]'.format(inp))
    except Exception as ex:
        print(ex)
        continue
    # Simulates a mouse click on the element
    eleNM.click()
  
    while(True):
        # Finds the chat box element
        eleTF = driver.find_element_by_class_name("_13mgZ")
        # Writes the message(function call to wish_birth())
        eleTF.send_keys(wish_birth(inp))
        # Finds the Send button
        eleSND = driver.find_element_by_class_name("_3M-N-")
        # Simulates a click on it
        eleSND.click()
        break

chevron_right


How the JSON file looks

[
  {
    "name": "NAME1",
    "birth_month": "1",
    "birth_date": "12"
  },
  {
    "name": "NAME2",
    "birth_month": "5",
    "birth_date": "15"
  }

]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.