简体   繁体   English

如何使用 python 读取联系人的 whatsapp 消息?

[英]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.我正在构建一个在指定时间登录缩放的机器人,并且链接是从 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.所以我想知道是否可以直接从 whatsapp 中检索这些链接,而不必将其复制粘贴到 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 WebDriver阅读带有 Python 的 WhatsApp 消息,因为我强烈怀疑您是否可以访问 WhatsApp API。

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. 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.首先,我们提到了 Selenium,但我们只会使用它来自动打开和关闭 WhatsApp,现在我们必须找到一种方法来读取 WhatsApp 客户端内部的内容,这就是 Web Scraping 的魔力所在。

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. Web 抓取是从网站提取数据的过程,在这种情况下,数据由您需要自动获取的 Zoom 链接表示,而 web 站点是您的 WhatsApp 客户端。 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.要执行此过程,您需要一种从网站中提取(解析)信息的方法,为此我建议您使用Beautiful Soup ,但我建议您至少需要了解 HTML 的工作原理。

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.您可以使用 Python 中的https://selenium-python.readthedocs.io/在浏览器上打开 WhatsApp。

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. 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.我从“ https://towardsdatascience.com/complete-beginners-guide-to-processing-whatsapp-data-with-python-781c156b5f0b ”这个网站学习和使用代码。 Go through the details written on mentioned link. Go 通过上述链接上的详细信息。

You have to install external python library " whatsapp-web " from this link --- " https://pypi.org/project/whatsapp-web/ ".您必须从此链接安装外部 python 库“ whatsapp-web ”---“ https://pypi.org/project/whatsapp-web/ ”。 Just type in command prompt / windows terminal by "python -m pip install whatsapp-web".只需通过“python -m pip install whatsapp-web”输入命令提示符/windows 终端。

It will show result ---它会显示结果---

python -m pip install whatsapp-web python -m pip 安装whatsapp-web

Collecting whatsapp-web收集whatsapp-web

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

Installing collected packages: whatsapp-web安装收集的包:whatsapp-web

Successfully installed whatsapp-web-0.0.1成功安装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. 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.因为 WhatsApp 已更改其元素的 class 名称。

I have tried that in creating a WhatsApp bot using python.我已经尝试过使用 python 创建一个 WhatsApp 机器人。 But there are still many bugs because of I am also beginner.但是由于我也是初学者,所以仍然有很多错误。

steps based on my research:基于我的研究的步骤:

  1. Open browser using selenium webdriver使用 selenium webdriver 打开浏览器
  2. Login on WhatsApp using qr code使用二维码登录 WhatsApp
  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.然后,您可以获得任何未读联系人块的 div class 并打开所有包含该未读 div class 的聊天室列表。
  3. Then check all the unread messages of open chat and get the message from the div class.然后检查打开聊天的所有未读消息,并从 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注意:在上面的代码中,“webdriver”是您打开 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.可以在以下链接中阅读我的另一个答案,以获取有关使用 python 的 WhatsApp web 的更多信息。

  • Line breaks in WhatsApp messages sent with Python 使用 Python 发送的 WhatsApp 消息中的换行符

  • I am developing WhatsApp bot using python.我正在使用 python 开发 WhatsApp 机器人。

  • For contribution you can contact at: anurag.cse016@gmail.com对于贡献,您可以联系: anurag.cse016@gmail.com

  • Please give a star on my https://github.com/4NUR46 If this Answer helps you.如果这个答案对你有帮助,请给我的https://github.com/4NUR46 打个星。

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.您可以从 whatsapp web 读取所有 cookies 并将它们添加到标头并使用请求模块,或者您也可以使用 selenium 。

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:)所以现在你必须安装 pyautogui、pyperclip 并按照代码片段中的注释进行操作,一切都应该正常工作:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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