Code Monkey home page Code Monkey logo

whatsapp-assistant-bot's Introduction

WhatsApp Assistant Bot

Demo

A personal WhatsApp assistant bot that will help you search anything on the web:
script is automated with selenium, the bot will check the chat and reply on valid commands

  • Search Google
  • Search Google Images
  • Directions from Google Maps
    • User can set {origin}, {destination} and {travelmode}

If bot fails when you first run it, please check and update if the class attribute for Line 13 has changed:

MESSAGE_BUBBLE_CLASS_NAME = "_13mgZ"

1) Inspect the Whatsapp text bubble element
2) Extract the class attribute and update Line 13

TODOs

Features

  • Bot can poll 1 conversation
  • Bot can poll multiple assigned conversations
  • Search Google
  • Search Google Images
  • Search Google Maps
  • Google Maps directions from user's location

Down the road

  • Remotely access the QR code
  • Image to text analysis w/ Pytesseract
  • Flask server running headless Chrome

Step by Step Guide

I have been receiving a lot of requests about what to do when the bot starts running. Here is a step by step example:

  1. Once the bot is running, it should automatically open chrome and display the whatsapp web QR code. Once you scan it, you should be able to see a list of your conversations, choose the one you want to test with. QR Code Scan

  2. Line 293 of whatsapp_assistant_bot.py can be changed to read incoming messages (other person in conversation) vs outgoing messages (your own messages)

text_bubbles = driver.find_elements_by_class_name("message-out")  # message-in = incoming, message-out = outgoing

Incoming vs Outgoing

  1. Example of sending commands and the bot scanning for outgoing messages (my messages) Test outgoing

  2. Example of asking the bot to google something. Since the bot is running on your computer, chrome will be automated by selenium and you will see a chrome page open, a screenshot will be taken and attached to the chat. Test Google

What You'll Need

  1. Install Chromedriver and make sure the Setup is completed (add the path to the chromedriver executable)

Chromedriver

  1. Install Selenium from your command line Selenium
$ pip3 install selenium

How to Run

Clone the repo

$ git clone https://github.com/jctissier/whatsapp-assistant-bot.git
$ cd whatsapp-assistant-bot
$ python3 whatsapp_assistant_bot.py

If you get an error at this stage, it's most likely due to Chromedriver not being installed properly. Repeat the first step.

Script is running properly if you see "Bot is active, scan your QR code from your phone's WhatsApp"

  • Scan your QR Code QR Code
  • Select a chat and start sending commands

Valid Commands

The bot will always send back screenshots of the Chrome browser

/google {query}              # Search google text
/images {query}              # Search google images
/maps                        # Directions with Google Maps
    /origin {from where}     # Sub-menus from /maps
    /dest {to where}
    /mode {driving, walking, transit, bicycling}

How Selenium Automates the Bot

I was able to scan incoming/outgoing messages by inspecting the HTML and using selenium to access on class names and xpath Scan Messages

Testing

You can either create a bot account (as mentioned below) or you can use your own account to test it.

  • In the function chat_history(), set the first line of the function to "message-out"
    • This allows the bot to only scan for messages sent by yourself
    • You can send commands to yourself and the bot will respond (no need for a spare account)
  • "message-in" forces to bot to scan for incoming messages from the other person

Flowchart for Main Features Flow Chart

How I Use It

I run the script from my home computer in Canada and I have a separate WhatsApp account running 24/7.

You can create a free WhatsApp account if you have a spare/old smartphone.

  • Charge the device 24/7, have it on Wifi and download WhatsApp on it (SIM card is not needed)
  • When they ask you to verify your WhatsApp and need a number to text
    • Download one of the many apps on app store which allows you to get a temporary phone number
      • For example, I use textPlus - FREE
      • Generate a free number and use it to verify your bot account
    • For the verification, ask for a call, answer the call and set the password
    • Account should now be created, you can now message the bot to that particular number that was generated with the app

There is plenty more that can be done with this bot, but I only needed basic googling.

Comments

Author: Jean-Claude Tissier
MIT License

I created this bot for when I travel since I have unlimited WhatsApp everywhere in the world but no data plan. I needed a way to be able to find directions, search for touristy attractions and general googling necessities in a new city without having data.

Feel free to grab the code and let me know if you have questions.

PS: This bot is not meant for spamming and is only meant for personal use.

whatsapp-assistant-bot's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

whatsapp-assistant-bot's Issues

help!!

Hey I'm getting this error while running the script .Could ya help me out ??

('/google bots', '14-05-28')
Command args: ['google', 'bots']
Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="main"]/header/div[3]/div/div[2]/span/div/div/ul/li[1]/input"}
(Session info: chrome=73.0.3683.86)
(Driver info: chromedriver=73.0.3683.68 (47787ec04b6e38e22703e856e101e840b65afe72),platform=Windows NT 10.0.17134 x86_64)

('bot failed to retrieve search content, try again...', '14-05-42')

hello

hello I would like to help me with a question I have, I would like to find the contact id in whatsapp to which you are receiving the message or how to automate the message so as not to click on the contact

Thank you!. :)

/all_commands will add the entire "/help" content after using /help and followed by "/add_commands"

Hello, jctissier,

I recently tested your code and found a interesting thing.
After I used some commands (including /help) and at last I tried /all_commands. I got a entire content of "/help" while using the command /all_commands.

I modified the code a little bit to support two-way inputs (sender+receiver), but... I tried the original code as well and the same things happens.

Here's a screenshot of it (but unfortunately I don't have the "logs" from the terminal)
屏幕截图(22)
屏幕截图(23)

Hope for the best.
QT0̸

Not working

Hi, thanks for sharing such interesting bot

I've tried to follow all the instruction but it is just not working.

after I scan the barcode and select the chat it shows this in the console:

➜ whatsapp-assistant-bot git:(master) python3 whatsapp_assistant_bot.py
Bot is active, scan your QR code from your phone's WhatsApp
('/help', '13-46-21')
Command args: ['help']
Asking for help
Traceback (most recent call last):
File "whatsapp_assistant_bot.py", line 337, in
Bot()
File "whatsapp_assistant_bot.py", line 44, in init
self.init_bot()
File "whatsapp_assistant_bot.py", line 48, in init_bot
self.poll_chat()
File "whatsapp_assistant_bot.py", line 65, in poll_chat
self.bot_options(action=last_msg)
File "whatsapp_assistant_bot.py", line 80, in bot_options
send_message(simple_menucommand_args[0])
File "whatsapp_assistant_bot.py", line 323, in send_message
whatsapp_msg = driver.find_element_by_class_name('_2S1VP')
File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 564, in find_element_by_class_name
return self.find_element(by=By.CLASS_NAME, value=name)
File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
'value': value})['value']
File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"class name","selector":"_2S1VP"}
(Session info: chrome=74.0.3729.169)
(Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Mac OS X 10.13.6

any thoughts?

Bot doesnt start, only shows messages in command prompt

When i run commands nothing happen. They just show up in the console log.

also
thsi happens when i google something

('/google yes', '18-56-58')
Command args: ['google', 'yes']
Traceback (most recent call last):
  File "c:\Users\Gerrid\Documents\whatsapp-assistant-bot\whatsapp_assistant_bot.py", line 339, in <module>
    Bot()
  File "c:\Users\Gerrid\Documents\whatsapp-assistant-bot\whatsapp_assistant_bot.py", line 48, in __init__
    self.init_bot()
  File "c:\Users\Gerrid\Documents\whatsapp-assistant-bot\whatsapp_assistant_bot.py", line 52, in init_bot
    self.poll_chat()
  File "c:\Users\Gerrid\Documents\whatsapp-assistant-bot\whatsapp_assistant_bot.py", line 69, in poll_chat
    self.bot_options(action=last_msg)
  File "c:\Users\Gerrid\Documents\whatsapp-assistant-bot\whatsapp_assistant_bot.py", line 91, in bot_options
    g_search.search(qry=query)
  File "c:\Users\Gerrid\Documents\whatsapp-assistant-bot\whatsapp_assistant_bot.py", line 187, in search
    send_message("Searching Google for: '{qry}'".format(qry=qry))
  File "c:\Users\Gerrid\Documents\whatsapp-assistant-bot\whatsapp_assistant_bot.py", line 325, in send_message
    whatsapp_msg = driver.find_element_by_class_name(MESSAGE_BUBBLE_CLASS_NAME)
  File "C:\Users\Gerrid\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 564, in find_element_by_class_name
    return self.find_element(by=By.CLASS_NAME, value=name)
  File "C:\Users\Gerrid\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Users\Gerrid\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Gerrid\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"._13mgZ"}
  (Session info: chrome=89.0.4389.114)

Sending images xpath has been outdated

Here is the modified one

attach_xpath = '//*[@id="main"]/header/div[3]/div/div[2]/div'
            send_file_xpath = '/html/body/div[1]/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/span[2]/div/div/span'
            attach_type_xpath = '/html/body/div[1]/div/div/div[4]/div/header/div[3]/div/div[2]/span/div/div/ul/li[1]/button/input'

The Bubble Tag is not Bubble anymore

Aparently the Bubble Tag is not called bubble anymore, therefore

`def chat_history():
text_bubbles = driver.find_elements_by_class_name("message-out") # message-in = receiver, message-out = sender
tmp_queue = []

try:
    for bubble in text_bubbles:
        msg_texts = bubble.find_elements_by_class_name("copyable-text")
        for msg in msg_texts:
            #raw_msg_text = msg.find_element_by_class_name("selectable-text.invisible-space.copyable-text").text.lower()
            # raw_msg_time = msg.find_element_by_class_name("bubble-text-meta").text        # time message sent
            tmp_queue.append(msg.text.lower())

    if len(tmp_queue) > 0:
        return tmp_queue[-1]  # Send last message in list

except StaleElementReferenceException as e:
    print(str(e))
    # Something went wrong, either keep polling until it comes back or figure out alternative

return False`

Anyway, this is just the beginning as am getting "selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"class name","selector":"pluggable-input-body"}" so i guess classes have to be updated.

Receiving and passing on to a webservice?

Hi @jctissier,

I just found your project and it looks promising.

I once used https://github.com/tgalal/yowsup only for receiving Whatsapp messages. Until yowsup started to become too much of a struggle to keep it running and I abandoned it. I now think yowsup has too many problems and is dead.

I have been experimenting with WhatsappWeb, Selenium and Ruby for receiving Whatsapp messages, but found it not stable and quick enough.

Do you think, it would be possible to use/extent your project for receiving messages (with attachments) from multiple unknown contacts and simply passing them on to a webservice for processing?

Thanks
Christian

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.