GithubHelp home page GithubHelp logo

visweswaran1998 / simple-yet-hackable-whatsapp-api Goto Github PK

View Code? Open in Web Editor NEW
611.0 65.0 153.0 124 KB

There is no official WhatsApp API. Here is a simple python class which satisfies the need.

License: Apache License 2.0

Python 100.00%
whatsapp whatsapp-bot

simple-yet-hackable-whatsapp-api's Introduction

Simple-Yet-Hackable-WhatsApp-api

visitors

Installation

To use this api in your project, you can download whatsapp.py and emoji.json from this repository, and keep it in the same folder/subfolder of your project. Create a new .py file for your project and import this api with

from whatsapp import Whatsapp

For this api to work, it requires selenium, requests, pillow and bs4 modules. Please copy the reqirements.txt of this project into your project's requirements.txt so it can work seamlessly with your project.

Usage

Using This API you can achieve many things in less than 5 lines of code

Sending a message with an emoji:

from whatsapp import WhatsApp
whatsapp = WhatsApp(10)
print(whatsapp.send_message("Name",":heart: Good!"))  

Result:
Image

Running from an existing session: It it very difficult for us to scan the QR code for logging in everytime if the session is not saved, you can avoid it by adding the session parameter like this,

# SWAMI KARUPPASWAMI THUNNAI

import os
from whatsapp import WhatsApp

whatsapp = WhatsApp(100, session="mysession")
whatsapp.send_document("Thamarai", os.path.join(os.getcwd(), "message.txt"))

Your data will be saved into mysession folder from the above example. Make sure you protect your session folder.

Getting the status message of a person:

from whatsapp import WhatsApp
whatsapp = WhatsApp(10)
print(whatsapp.get_status("Name"))

Getting last seen of a person:

from whatsapp import WhatsApp
whatsapp = WhatsApp(10)
print(whatsapp.get_last_seen("Name"))

Getting the no of participants in the group:

from whatsapp import WhatsApp
whatsapp = WhatsApp(10)
result = app.participants_count_for_group("The Night Ghost Company")

creating a new group and getting invite link

# SWAMI KARUPPASWAMI THUNNAI

from whatsapp import WhatsApp
import time

app = WhatsApp(100)
parameter1: group name, parameter 2: group members
app.create_group("group", ["Thamarai", "Jeeva"])
time.sleep(10)
print(app.get_invite_link_for_group("group"))

Join the group using invite link

# SWAMI KARUPPASWAMI THUNNAI

from whatsapp import WhatsApp

app = WhatsApp(10)
app.override_timeout(30)
app.join_group("https://chat.whatsapp.com/4AIA2B3GuLp4RJOKF0M8zY")
app.send_blind_message("I am in :)")

Exiting the group

# SWAMI KARUPPASWAMI THUNNAI

from whatsapp import WhatsApp

app = WhatsApp(100)
app.exit_group("X-Test")

Sending Anonymous messages [WHATSAPP WILL BAN YOUR PHONE NUMBER IF YOU SEND MANY ANONYMOUS MESSAGES]
Note: The phone number should not contain spaces and special characters(+, -) but shall contain country code. Example: +91-861 123 4567 should be formatted to 918611234567

# SWAMI KARUPPASWAMI THUNNAI

from whatsapp import WhatsApp

app = WhatsApp(10)
app.send_anon_message("91XXXXXXXXXX", "I am sorry for what is happening sir! But I have no other choice.")

Sending Messages to multiple participants
Sometimes we need to send messages to multiple persons who may or may not be in our contact list. So we need to a combination of both send_message and send_anon_message. Here is an example where we get the contact numbers from a group and sending messages to individual persons in that group.

# SWAMI KARUPPASWAMI THUNNAI

from whatsapp import WhatsApp
import time

app = WhatsApp(100)
app.override_timeout(30)
participants = app.get_group_participants("GDG")
print(participants)

for participant in participants:
    print("Sending: ", participant)
    time.sleep(1)
    try:
        app.send_message(participant.strip(), "Hello, I'm a bot. And this is a research. Please ignore me and dont ping back")
    except Exception as e:
        print(e)
        participant = participant.replace("+", "")
        participant = participant.replace(" ", "")
        app.send_anon_message(participant.strip(), "Hello, I'm a bot. And this is a research. Please ignore me and dont ping back")
    app.goto_main()

Sending pictures to a person:

# Note of Thanks: This part of code have been taken from WhatsApp Assistant bot by Jean-Claude Tissier(@jctissier).
# Github repo-link: https://github.com/jctissier/whatsapp-assistant-bot
# License: MIT
app.send_picture("Vignesh", os.getcwd()+"/pic.jpg")

Sending documents to a person:

# SWAMI KARUPPASWAMI THUNNAI

import os
from whatsapp import WhatsApp

whatsapp = WhatsApp(100)
whatsapp.send_document("Thamarai", os.path.join(os.getcwd(), "message.txt"))

Clearing the chat:

# SWAMI KARUPPASWAMI THUNNAI

from whatsapp import WhatsApp

whatsapp = WhatsApp(100)
whatsapp.clear_chat("Test")

Getting usernames with unread messages: Will return the list of usernames for which we have yet to reply that person. Increase the count of scrolls according to your needs.

# SWAMI KARUPPASWAMI THUNNAI

from whatsapp import WhatsApp

whatsapp = WhatsApp(100, session="mysession")
print(whatsapp.unread_usernames(scrolls=1000))

and we will receive an output as a Python list. Something like this,

['Ziv Freelance Employer', 'Vignesh', 'InstagramTest', '+91 9xx36 8xxx2', 'Sundar Sir', '+91 xxx47 8xxx9']

Getting the last sent messages for a username:

# SWAMI KARUPPASWAMI THUNNAI

from whatsapp import WhatsApp

whatsapp = WhatsApp(100, session="mysession")
messages = whatsapp.get_last_message_for("Thamarai")
print(messages)

Note: I am still working on it and it might break.

Interesting use cases:

Replying to all stale messages:

# SWAMI KARUPPASWAMI THUNNAI

from whatsapp import WhatsApp

whatsapp = WhatsApp(100, session="mysession")
usernames = whatsapp.unread_usernames(scrolls=1000)
for username in usernames:
    try:
        whatsapp.send_message(username, "Hello I am a bot, apologies that my creator hasn't replied to you yet. please ping again. ")
        whatsapp.send_blind_message("Know more about me: https://github.com/VISWESWARAN1998/Simple-Yet-Hackable-WhatsApp-api")
    except:
        print("You don't have permission to send message to this group/person")

Note: Ir just automated the whatsapp, Nothing More, Nothing Less. This program is Licensed under Apache 2.0.

Thank you for so many stars on this project, you can support me in follwing ways,

  1. Paypal: [email protected]
  2. 1 GitHub follower = 1 supporter for me to get recogonized.
  3. LinkedIn skill Endorsement: https://www.linkedin.com/in/visweswaran-nagasivam-975a8b167/

simple-yet-hackable-whatsapp-api's People

Contributors

aahnik avatar cristianlivella avatar dependabot[bot] avatar elievischel avatar friedgreenrepos avatar imgbotapp avatar ngapa avatar vigneshsp94 avatar visweswaran1998 avatar z404 avatar

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  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

simple-yet-hackable-whatsapp-api's Issues

[feature request] please consider these issues

  1. Adding delete chat feature.(not same as clear chat)

  2. Feature to create whatsapp brodcast lists and delete them

  3. Seperate the functionality into different modules.(maintaining the code is difficult as everything is in same file )

  4. Xpath and css selector portions must be seperated from code and be hosted in a CDN .( Atleast kept in a seperate var.py file or a json file , so it's easy to modify)

  5. A test module to test whether all features of api is working properly or not. And print exactly where the api is breaking.

  6. Pack all the modules into a package and adding init.py and setup.py so we can pip install the api in entire system

  7. Issue 48 is solved only in method send_message
    The issue exists in send_picture and send_document

  8. The path of chrome driver installation and the json file containing the latest xpath&css selector should be passed to the constructor . So that the api works in a hassle free manner across.

Thanks a ton 🙂
Aahnik

Error while getting whatsapp status

Hi,

First of all thank you for the api!

I am getting below error while looking for "Status" of contact.

Kindly look into this

C:\Users\Sagar\AppData\Local\Programs\Python\Python37\python.exe C:/Users/Sagar/Downloads/Simple-Yet-Hackable-WhatsApp-api-master/Simple-Yet-Hackable-WhatsApp-api-master/group.py
Traceback (most recent call last):
File "C:\Users\Sagar\Downloads\Simple-Yet-Hackable-WhatsApp-api-master\Simple-Yet-Hackable-WhatsApp-api-master\whatsapp.py", line 185, in get_status
(By.XPATH, group_xpath)))
File "C:\Users\Sagar\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:/Users/Sagar/Downloads/Simple-Yet-Hackable-WhatsApp-api-master/Simple-Yet-Hackable-WhatsApp-api-master/group.py", line 3, in
print(whatsapp.get_status("Ketan"))
File "C:\Users\Sagar\Downloads\Simple-Yet-Hackable-WhatsApp-api-master\Simple-Yet-Hackable-WhatsApp-api-master\whatsapp.py", line 188, in get_status
raise TimeoutError("Your request has been timed out! Try overriding timeout!")
TimeoutError: Your request has been timed out! Try overriding timeout!

Process finished with exit code 1

!!!UPDATE THE API!!!

most of the xpaths, selectors and classes are outdated since whatsapp's website changes every few updates. PLEASE UPDATE!!

error

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
(Session info: chrome=81.0.4044.138)

Whatsapp search box element name change and behaviour change

The code is no longer working due to recent Whatsapp changes:

  • Element name changed from _2zCfw to _3u328
  • Behaviour changed where search text box does not respond to enter to open up the chat. Need to click on the object of the first search result element "_2WP9Q" (first result element is always _2WP9Q)
search = self.browser.find_element_by_css_selector("._3u328")
search.send_keys(name+Keys.ENTER) 
chat = self.browser.find_element_by_css_selector("._2WP9Q")
chat.click()

Getting usernames with unread messages not work

from whatsapp import WhatsApp
whatsapp = WhatsApp(100, session="mysession")
print(whatsapp.unread_usernames(scrolls=100))

Hello, when I tried to run this code, I've got just [ ]
Bot doesn't see persons which has unread messages.
Maybe problem in Chrome version?

Please upload to pip

So we can install pip from command line on terminal to make it easy to use...

In Case Number is not a Vaild Whatsapp User

Your Script runs great .
I am having a bit of a issue while sending bulk messages, if the phone number is not a valid whatsapp user, and i am executing send_anon_message() , it breaks. I was hoping it skips that number and move onto the next line.

installation and setup instruction

Hi, i am interested in testing this project out. are there instructions somewhere?
does this just work or it has dependencies?

it will be nice and helpful if you can write-up a short installation and setup instructions.

problem

Traceback (most recent call last):
File "test.py", line 1, in
from whatsapp import WhatsApp
File "/root/Downloads/Simple-Yet-Hackable-WhatsApp-api-master/whatsapp.py", line 36, in
class WhatsApp:
File "/root/Downloads/Simple-Yet-Hackable-WhatsApp-api-master/whatsapp.py", line 41, in WhatsApp
browser = webdriver.Chrome() # we are using chrome as our webbrowser
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/chrome/webdriver.py", line 81, in init
desired_capabilities=desired_capabilities)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 157, in init
self.start_session(capabilities, browser_profile)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
(unknown error: DevToolsActivePort file doesn't exist)
(The process started from chrome location /usr/bin/chromium is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
(Driver info: chromedriver=72.0.3626.53,platform=Linux 4.19.0-kali3-amd64 x86_64)

Erro

As mensagens de erro não estão sendo apresentadas.

error

Traceback (most recent call last):
File "test.py", line 2, in
from whatsapp import WhatsApp
File "/root/Downloads/Simple-Yet-Hackable-WhatsApp-api-master/whatsapp.py", line 25, in
from urllib.parse import urlencode
ImportError: No module named parse

Error "init (By.CSS_SELECTOR, '.jN-F5')))"

Hi,
I executed the program, it is the error message obtained.
The browser gets good web.whatsapp and the error is coming up.

C:\Python37\python.exe C:/Wp/Simple/main.py
Traceback (most recent call last):
File "C:/Wp/Simple/main.py", line 6, in
app = WhatsApp(10)
File "C:\Wp\Simple\whatsapp.py", line 51, in init
(By.CSS_SELECTOR, '.jN-F5')))
File "C:\Python37\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

Process finished with exit code 1

Thank you.

Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)

Problem:
I want to send a message using the phone number and I used send_anon_message function but I got an error.

Error:
DevTools listening on ws://127.0.0.1:58386/devtools/browser/87426bed-43cb-4db8-a658-7e54be26a153
[11144:12812:0706/012329.621:ERROR:device_event_log_impl.cc(214)] [01:23:29.629] USB: usb_device_handle_win.cc:1048 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)

My Code:
from whatsapp import WhatsApp
whatsapp = WhatsApp(100, session="C:/Users/users/Desktop/Simple-Yet-Hackable-WhatsApp-api-master/mysession")
print(whatsapp.send_anon_message("6282136218888",":heart: Good!"))

My environtment:
OS : Windows 11
Python Version: 3.9
selenium : 3.12.0
requests : 2.20.0

Get chat messages?

Feature to get new chat messages with various types (text, picture, document...)

Reading

Any methods for reading conversations?

[feature request] Check if a file is successfully sent

@VISWESWARAN1998 I want to add a very important feature request.(for me it is important.) Documents can be big or small. If the document is too big, the selenium will close before the file is uploaded. If we increase the time, the next file may be small and it will waste time. We should together sort this issue. There must be some workaround to check if the message is sent.

stuck after login

i try this script on linux mint after chrome appear and login bot dont run the code

Timeout error when trying getting the last seen of a invisible.

I'm trying to get the last seen from somebody that has their settings like set so only it is seen when they are online but not their last seen. But if they are online I'm getting the Error TimeoutError: Your request has been timed out! Try overriding timeout!. And now I'm asking how do I override this error and just basically wait till they come online and then get their last seen status aka the Online Status?

[enhancement]emojify is making the program slower

is emojify actually needed?

the common emojis can be easily sent by typing text faces

I commented out emojify and related lines then

this piece of code

from whatsapp import WhatsApp

wapp = WhatsApp(100, session='aahnik')

msg = """ *Hi Demo Emoji and Formatting*
:-) i am a smiling face *i am a bold text*

_i am italicised lorem ipsum_ 

~strike through message~

;-) i am winking  <3 love is pure
(y) cheers :-p tounge out :-( i am unhappy 

        *MORE EMOJIS*
:-) ;-) (y) 
*It works* Bye """

wapp.send_message('Aahnik Personal', msg)

produced this output

emoji_demo

How to send image?

Hi I'm trying to send image with this code. I'm new to python where I'm I going wrong. It opens chrome browser and asks for qr code confirmation. After confirmation It searches for the Name and opens a chat then it stops there.

from whatsapp import WhatsApp
whatsapp = WhatsApp(20)
whatsapp.send_picture("Name","C:/Users/Levis/Desktop/Images/python.png","Image send test")

Wierd Problem! Sending Message to Previous Person when search of Current Person takes longer loading

Imagine a situation, i have a list of 5 receipients.(the contacts are saved in phone )

wapp = WhatsApp(100, session='sess')
for i in range(0, len(contacts)):
    name = contacts[i]
    wapp.send_message(name, f"""Hi {name}
... msg... :-)
""")

the program sends correct message successfully to person 1,2 and 3.

Now Searching person 4 (in whatsapp search bar) takes longer, the message to be sent to person 4 gets send to person 3.

then person 5 again recieves correct message

I think some changes must be made in the send_message method, after entering keys of a name in search bar and pressing enter, the program should wait until the new person is loaded and not send the message to previous person.

I was messaging about 200 + contacts about 10 people received wrong messages.

this problem occurs only when the person doesnt appear immediately after entering the keys of persons name and enter into search bar

Find input bar by ID not working

I tried to use your API but the input bar in WhatsApp web can't be accessed via browser.get_element_by_id since the id is not available (at least not anymore). Therefore I updated it with browser.get_element_by_xpath followed by the input search bar XPATH.

example (line 42):
WebDriverWait(self.browser,wait).until(EC.presence_of_element_located( (By.XPATH, '//*[@id="side"]/div[2]/div/label/input')))

Sending to anon number not working

Since whatsapp web takes the user to a window looking for the app installed, in order to send the message it is needed to click in the "go to whatsapp web" link and then press enter to send the message

XPATH Error

Code I use:
from whatsapp import WhatsApp whatsapp = WhatsApp(10) print(whatsapp.get_last_seen("Max"))
I'm trying to get the last seen of somebody but I always get this error:

Exception has occurred: selenium.common.exceptions.TimeoutException Message: File "C:\Users\Thore\Desktop\WA Track\whatsapp.py", line 44, in __init__ (By.XPATH, '//*[@id="side"]/div[2]/div/label/input'))) File "C:\Users\Thore\Desktop\WA Track\tracker.py", line 2, in <module> whatsapp = WhatsApp(10)

Error Msg "selenium.common.exceptions.TimeoutException: Message:"

Hi ...

i can`t execute the script and it show error msg "selenium.common.exceptions.TimeoutException: Message:"

My Simple script ( To send Message ) :
from whatsapp import WhatsApp whatsapp = WhatsApp(100, session="mysession") print(whatsapp.send_message("Same",":heart: Good!"))

first cmd output :
https://b.top4top.io/p_1887puw2p1.png

its open whatsapp web page but after a while it show me error :
https://c.top4top.io/p_18876h5wc2.png

DevTools listening on ws://127.0.0.1:52819/devtools/browser/eb05022d-aacf-45aa-8 7bd-a822c0d99afa [0302/121025.282:ERROR:gl_surface_egl.cc(773)] EGL Driver message (Error) eglQue ryDeviceAttribEXT: Bad attribute. Traceback (most recent call last): File "XXXXXXXXXXXXXXX\Simple-Yet-Hackable-WhatsApp-api-master\test.py" , line 2, in <module> whatsapp = WhatsApp(50, session="mysession") File "XXXXXXXXXXXXXXX\Simple-Yet-Hackable-WhatsApp-api-master\whatsapp .py", line 61, in __init__ WhatsAppElements.search)) File "XXXXXXXXXXXXXXX\Python\Python37-32\lib\site-packa ges\selenium\webdriver\support\wait.py", line 80, in until raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message:

with no more actions on the whatsapp web page, So please help me to solve this issues !

question

how to send messages to whatsapp numbers other than my contacts

error

File "t.py", line 1, in
from whatsapp import WhatsApp
File "D:\download\Simple-Yet-Hackable-WhatsApp-api-master\Simple-Yet-Hackable-WhatsApp-api-master\whatsapp.py", line 36, in
class WhatsApp:
File "D:\download\Simple-Yet-Hackable-WhatsApp-api-master\Simple-Yet-Hackable-WhatsApp-api-master\whatsapp.py", line 41, in WhatsApp
browser = webdriver.Chrome() # we are using chrome as our webbrowser
File "C:\Python37\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 75, in init
desired_capabilities=desired_capabilities)
File "C:\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 156, in init
self.start_session(capabilities, browser_profile)
File "C:\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 245, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "C:\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 314, in execute
self.error_handler.check_response(response)
File "C:\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 75

How to use Apache 2.0 Liscense

I want to refactor some of the code in this repo and use it for a personal project. I'm confused on what the Apache License requires me to do to use the code. Could someone please explain it to me?

Read messages

I'd like to read messages by others (in a group chat) and respond depending on the message. This doesn't seem possible at present. It would be great if it would be possible to read messages from chats!

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.