'Problem with repetitive messages for whatsapp - python

I have been making a whatsapp chatbot with python, my problem is that it answers many messages, I think I have some open loop and I am not checking if the last message is mine or not, they told me that I should apply a if the last message was from the other, if so, it executes read message and if it does not send a message by default, but I do not know very well where to put it

Help me please

enter image description here

My code is :

from time import sleep
import time
from selenium import webdriver
# Sirve para esperar un tiempo entre procesos:
from selenium.webdriver.support.wait import WebDriverWait 
#Para poder Acoplarnos  a la session que se tiene abierta en el otro terminal :
from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver
import re
#Normalizar ciertos caracteres 
from unicodedata import normalize

#Primero abrira el archivo txt
filepath  ='./resource/driver/whatsapp_sessionV2.txt'
driver = webdriver

#en esta funcion buscara los dos atributos la url y el id
def crear_driver_session():

    with open(filepath) as fp:
        for cnt, line in enumerate(fp):
            if cnt == 0:
                executor_url = line
            if cnt == 1:
                session_id = line

    def new_command_execute(self, command, params=None):
        if command == "newSession":
            # Mock the response
            return {'success': 0, 'value': None, 'sessionId': session_id}
        else:
            return org_command_execute(self, command, params)
                
    org_command_execute = RemoteWebDriver.execute

    RemoteWebDriver.execute = new_command_execute

    new_driver = webdriver.Remote(command_executor=executor_url, desired_capabilities={})
    new_driver.session_id = session_id

    RemoteWebDriver.execute = org_command_execute

    return new_driver

def  buscar_chats():
        print("BUSCANDO CHATS")
            #buscar los elementos que contengan la siguiente clase , si es = 0
        if len(driver.find_elements_by_class_name("zaKsw")) == 0:
            print("CHAT ABIERTO")
            message = identificar_mensaje()
        
            if message != None:
                  return  True
      
        chats = driver.find_elements_by_class_name("_3m_Xw")

        for chat in chats:
              print("DETECTANDO MENSAJES SIN LEER")

              chats_mensajes = chat.find_elements_by_class_name("_1pJ9J") #l7jjieqr
              

              if  len(chats_mensajes) == 0:
                    print("CHATS ATENDIDOS")
                    continue #Quiere decir que acabara el ciclo del for y seguira con el siguiente #elemento en el if
          
              element_name = chat.find_elements_by_class_name('zoWT4')
              name = element_name[0].text.upper().strip() 

              print("IDENTIFICAR CONTACTO")

              with open("./resource/contactos_autorizados.txt", mode='r', encoding='utf-8') as archivo:
                      contactos = [linea.rstrip() for linea in archivo]
                      if name not in contactos:
                          print("CONTACTO NO AUTORIZADO : ", name)
                          continue

              print(name, "AUTORIZADO PARA SER ATENDIDO POR BOT")
          
              chat.click()
              return True
        return False

def normalizar(message: str):
      # -> NFD y eliminar diacríticos , tildes , la ñ la trata de entender
      message = re.sub(
              r"([^n\u0300-\u036f]|n(?!\u0303(?![\u0300-\u036f])))[\u0300-\u036f]+", r"\1", 
              normalize( "NFD", message), 0, re.I
      )

      # -> NFC
      return normalize( 'NFC', message)

def identificar_mensaje():
      element_box_message = driver.find_elements_by_class_name("Nm1g1")
      posicion = len(element_box_message)  -1

      color = element_box_message[posicion].value_of_css_property("background-color")
      print("Color Utilizado :", color)

      #Si el color es de  algunos de estos 2 verdes quiere decir que el ultimo que ha hablado es el bot
      if color == "rgba(217, 253, 211,1)" or color == "rgba(0, 92, 75,1)":  # el 1 es la opacidad , #por default es mejor dejarlo en 1
          print("CHAT ATENDIDO")
          return


      element_message = element_box_message[posicion].find_elements_by_class_name("_1Gy50")
      message = element_message[0].text.upper().strip()
      print("MENSAJE RECIBIDO : ", message)
      return normalizar(message)


def preparar_respuesta(message :str):
      print("PREPARANDO RESPUESTA")

      if message.__contains__("HOLA"):
            response = "Hola!, Bienvenido soy Lea un bot de Whatsapp :-D \n" \
                                "Si necesita información sobre sus requisiciones, ingrese el nombre de su usuario de EPICOR \n"
      elif message.__contains__("1"):
            response = "Puedes visitarnos \n"
      elif message.__contains__("2"):
            response = "Puedes unirte  \n"
      elif message.__contains__("QUE PUEDES HACER"):
            text1 = open("./resource/respuesta1.txt", mode='r', encoding='utf-8')
            response = text1.readlines()
            text1.close()
      elif message.__contains__("GRACIAS"):
            response = "Ha sido un place ayudarte ;-)  \n"
      else:     
            response = "Hola, Soy Lea un bot creado por el área de Sistemas. \n" \
                            "Para mayor información pregúnteme ¿Qué puedo hacer? :-D \n"

      return response

def procesar_mensaje(message :str):
      chatbox = driver.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[2]')
      response = preparar_respuesta(message)
      chatbox.send_keys(response)
      
def whatsapp_boot_init():
      global driver
      driver = crear_driver_session()

      while True:
            if not buscar_chats():
                  sleep(10)
                  continue
              
            message = identificar_mensaje()

            if message == None:  
                  continue

            procesar_mensaje(message)

whatsapp_boot_init()


Solution 1:[1]

I am not very familiar with seleniums api but i would suggest looking into the "send_keys" function. Usually such api provide a possibilty to send to specific receiptians. Usually with whatspp and telegramm bots you get your receiptian name in the communication data (in for example the text-request from the user).

With that info you can for example try to find the corresponding user-id to send the response back to.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 4lexKidd