简体   繁体   中英

How do I read whatsapp messages from a contact using python?

I'm building a bot that logs into zoom at specified times and the links are being obtained from whatsapp. So i was wondering if it is was possible to retrieve those links from whatsapp directly instead of having to copy paste it into python. Google is filled with guides to send messages but is there any way to READ and RETRIEVE those messages and then manipulate it?

You can, at most, try to read WhatsApp messages with Python using Selenium WebDriver since I strongly doubt that you can access WhatsApp APIs.

Selenium is basically an automation tool that lets you automate tasks in your browser so, perhaps, you could write a Python script using Selenium that automatically opens WhatsApp and parses HTML information regarding your WhatsApp web client.

First of all, we mentioned Selenium, but we will use it only to automate the opening and closing of WhatsApp, now we have to find a way to read what's inside the WhatsApp client, and that's where the magic of Web Scraping comes is hand.

Web scraping is a process of extracting data from a website, in this case, the data is represented by the Zoom link you need to automatically obtain, while the web site is your WhatsApp client. To perform this process you need a way to extract (parse) information from the website, to do so I suggest you use Beautiful Soup , but I advise you that a minimum knowledge of how HTML works is required.

Sorry if this may not completely answer your question but this is all the knowledge I have on this specific topic.

You can open WhatsApp on browser using https://selenium-python.readthedocs.io/ in Python.

Selenium is basically an automation tool that lets you automate tasks in your browser so, perhaps, you could write a Python script using Selenium that automatically opens WhatsApp and parses HTML information regarding your WhatsApp web client.

I learn and use code from " https://towardsdatascience.com/complete-beginners-guide-to-processing-whatsapp-data-with-python-781c156b5f0b " this site. Go through the details written on mentioned link.

You have to install external python library " whatsapp-web " from this link --- " https://pypi.org/project/whatsapp-web/ ". Just type in command prompt / windows terminal by "python -m pip install whatsapp-web".

It will show result ---

python -m pip install whatsapp-web

Collecting whatsapp-web

Downloading whatsapp_web-0.0.1-py3-none-any.whl (21 kB)

Installing collected packages: whatsapp-web

Successfully installed whatsapp-web-0.0.1

Update:

Please change the xpath's class name of each section from the current time class name of WhatsApp web by using inspect element section in WhatsApp web to use the following code. Because WhatsApp have changed its element's class names.

I have tried that in creating a WhatsApp bot using python. But there are still many bugs because of I am also beginner.

steps based on my research:

  1. Open browser using selenium webdriver
  2. Login on WhatsApp using qr code
  3. If you know from which number you are going to received the meeting link then use this step otherwise check the following process mention after this process.
  • Find and open the chat room where you are going to received zoom meeting link.

For getting message from known chat room to perform action

#user_name = "Name of meeting link Sender as in your contact list"
Example :
user_name = "Anurag Kushwaha"
#In above variable at place of `Anurag Kushwaha` pass Name or number of Your Teacher
# who going to sent you zoom meeting link same as you have in your contact list.
user = webdriver.find_element_by_xpath('//span[@title="{}"]'.format(user_name))
user.click()
# For getting message to perform action 
message = webdriver.find_elements_by_xpath("//span[@class='_3-8er selectable-text copyable-text']") 
# In the above line Change the xpath's class name from the current time class name by inspecting span element
# which containing received text message of any chat room.

for i in message:
    try:
        if "zoom.us" in str(i.text):
            # Here you can use you code to preform action according to your need
            print("Perform Your Action")
     except:
        pass
  1. If you do not know by which number you are going to received the link.
  2. Then you can get div class of any unread contact block and get open all the chat room list which are containing that unread div class.
  3. Then check all the unread messages of open chat and get the message from the div class.

When you don't know from whom you gonna received zoom meeting link.

# For getting unread chats you can use
unread_chats = webdriver.find_elements_by_xpath("// span[@class='_38M1B']")
# In the above line Change the xpath's class name from the current time class name by inspecting span element
# which containing the number of unread message showing the contact card inside a green circle before opening the chat room.

# Open each chat using loop and read message.
for chat in unread_chats:
    chat.click()

    # For getting message to perform action
    message = webdriver.find_elements_by_xpath("//span[@class='_3-8er selectable-text copyable-text']")
    # In the above line Change the xpath's class name from the current time class name by inspecting span element
    # which containing received text message of any chat room.
    for i in messge:
        try:
            if "zoom.us" in str(i.text):
                # Here you can use you code to preform action according to your need
                print("Perform Your Action")
         except:
             pass

Note: In the above code 'webdriver' is the driver by which you open web.whatsapp.com

Example:

from selenium import webdriver
webdriver = webdriver.Chrome("ChromePath/chromedriver.exe")
webdriver.get("https://web.whatsapp.com")
# This wendriver variable is used in above code.
# If you have used any other name then please rename in my code or you can assign your variable in that code variable name as following line.
webdriver = your_webdriver_variable

A complete code reference Example:


from selenium import webdriver
import time
webdriver = webdriver.Chrome("ChromePath/chromedriver.exe")
webdriver.get("https://web.whatsapp.com")
time.sleep(25) # For scan the qr code
# Plese make sure that you have done the qr code scan successful.
confirm = int(input("Press 1 to proceed if sucessfully login or press 0 for retry : "))
if confirm == 1:
   print("Continuing...")
elif confirm == 0:
   webdriver.close()
   exit()
else:
   print("Sorry Please Try again")
   webdriver.close()
   exit()
while True:
    unread_chats = webdriver.find_elements_by_xpath("// span[@class='_38M1B']")
    # In the above line Change the xpath's class name from the current time class name by inspecting span element
    # which containing the number of unread message showing the contact card inside a green circle before opening the chat room.
    
    # Open each chat using loop and read message.
    for chat in unread_chats:
        chat.click()
        time.sleep(2)
        # For getting message to perform action
        message = webdriver.find_elements_by_xpath("//span[@class='_3-8er selectable-text copyable-text']")
        # In the above line Change the xpath's class name from the current time class name by inspecting span element
        # which containing received text message of any chat room.
        for i in messge:
            try:
                if "zoom.us" in str(i.text):
                    # Here you can use you code to preform action according to your need
                    print("Perform Your Action")
             except:
                pass

  • Please make sure that the indentation is equal in code blocks if you are copying it.

  • Can read my another answer in following link for more info about WhatsApp web using python.

  • Line breaks in WhatsApp messages sent with Python

  • I am developing WhatsApp bot using python.

  • For contribution you can contact at: anurag.cse016@gmail.com

  • Please give a star on my https://github.com/4NUR46 If this Answer helps you.

You can read all the cookies from whatsapp web and add them to headers and use the requests module or you can also use selenium with that.

Try This Its A bit of a hassle but it might work

import pyautogui
import pyperclip
import webbrowser

grouporcontact = pyautogui.locateOnScreen("#group/contact", confidence=.6) # Take a snip of the group or contact name/profile photo
link = pyperclip.paste()

def searchforgroup():
     global link
     time.sleep(5)
     webbrowser.open("https://web.whatsapp.com")
     time.sleep(30)#for you to scan the qr code if u have done it then u can edit it to like 10 or anything
     grouporcontact = pyautogui.locateOnScreen("#group/contact", confidence=.6)
     x = grouporcontact[0]
     y = grouporcontact[1]
     if grouporcontact == None:
        #Do any other option in my case i just gave it my usual link as
        link = "mymeetlink"
     else:
         pyautogui.moveTo(x,y, duration=1)
         pyautogui.click() 
# end of searching group
def findlink():
    global link
    meetlink = pyautogui.locateOnScreen("#", confidence=.6)#just take another snap of a meet link without the code after the "/"
    f = meetlink[0]
    v = meetlink[1]
    if meetlink == None:
        #Do any other option in my case i just gave it my usual link as
        link = "mymeetlink"
   else:
       pyautogui.moveTo(f,v, duration=.6)
       pyautogui.rightClick()
       pyautogui.moveRel(0,0, duration=2) # You Have to play with this it basically is considered by your screen size so just edit that and edit it till it reaches the "Copy Link Address"
       pyautogui.click()
       link = pyperclip.paste()
       webbrowser.open(link) # to test it out

So Now You Have It Have To Install pyautogui, pyperclip and just follow the comments in the snippet and everything should work:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM