首页 > 解决方案 > Python Bot 在 Whatsapp 上回复你好

问题描述

我应该添加什么代码,以便当有人给我写“hi”时,我的机器人回复“hi”?

这是其余工作正常的代码。

from selenium import webdriver    
import time

from selenium.webdriver.common.by import By

chrome_browser = 
webdriver.Chrome(executable_path='/Users/gladwin/Desktop/drivers/chromedriver')
chrome_browser.get('https://web.whatsapp.com/')
options = webdriver.ChromeOptions()
options.add_argument('--user-data-directory=')

time.sleep(15)
user_name = 'WhatsApp Bot'


user = chrome_browser.find_element_by_xpath('//span[@title="{}"]'.format(user_name))`
user.click()

message_box = chrome_browser.find_element_by_xpath('//div[@class="_3uMse"]')`
message_box.send_keys('Hey, I am your whatsapp bot')

message_box = chrome_browser.find_element_by_xpath('//button[@class="_1U1xa"]')
message_box.click()

标签: pythonseleniumpycharmchatbotwhatsapp

解决方案


message-inclass 在这里真的很有用,只需列出这个 class 的所有元素并用这个 class 读取最后一个元素的内容。

def send_message(driver, message):
    # Send a message if driver has a conversation in focus
    message_box = driver.find_element_by_xpath('//div[@class="_3uMse"]')`
    message_box.send_keys('Hey, I am your whatsapp bot')

    message_box = driver.find_element_by_xpath('//button[@class="_1U1xa"]')
    message_box.click()
    
def find_hi_and_reply(driver):
    # If last received message is "hi", replies "hi back!!"
    messages_in = driver.find_elements_by_class_name('message-in')
    last_message = messages_in[-1]
    last_msg_content = last_message.find_element_by_class_name('copyable-text').text

    if last_msg_content == 'hi':
        send_message(driver, 'hi back!!')

推荐阅读