python - 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()
解决方案
message-in
class 在这里真的很有用,只需列出这个 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!!')
推荐阅读
- oracle - SAS 中的 Oracle to_date 格式为 J (Julian)
- javascript - 什么是 VS Code 中的 Prettier 键盘快捷键命令,用于仅格式化 React 代码块,而不仅仅是在文件自动保存时格式化?
- reactjs - 反应路由器未在 url 更新时显示组件
- c# - 如何过滤来自表单帖子的数据库结果?
- django - 尝试连接 /admin 页面时 Django 服务器死机
- python - 比较由 PDF 页面制作的 Tif 文件
- javascript - 反应图像轮播
- python - 在 SQLite3 中使用 executemany 执行 UPDATE 语句
- c# - 为一类对象赋值
- java - 数组的方法和命令