Python | Whatsapp birthday bot - GeeksforGeeks

02 Aug, 2021
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 ) 
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. 
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  
Python3
# get current date in required formatimport datetime # store the birthdates of your contactsimport json  from selenium import webdriver  # add a delay so that all elements of# the webpage are loaded before proceedingimport time # Global variable Do not use elsewhereeleNM = None # This function is just to return a# string of the message requireddef 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 attributes' 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 objectchropt.add_argument("user-data-<LOCATION TO YOUR CHROME USER DATA>") # Creating a Chrome webdriver objectdriver = webdriver.Chrome(executable_path ="<LOCATION TO CHROME WEBDRIVER>",                                                          options = chropt)driver.get("https://web.whatsapp.com/") # delay added to give time for all elements to loadtime.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
How the JSON file looks 
[
  {
    "name": "NAME1",
    "birth_month": "1",
    "birth_date": "12"
  },
  {
    "name": "NAME2",
    "birth_month": "5",
    "birth_date": "15"
  }

]
 
simmytarika5
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python