├── .gitignore ├── LICENSE ├── README.md ├── Screenshot (747).png ├── emoji.json ├── requirements.txt └── whatsapp.py /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017, Visweswaran Nagasivam 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Simple-Yet-Hackable-WhatsApp-api 2 | 3 | ![visitors](https://visitor-badge.glitch.me/badge?page_id=simplehackablewhatsapp) 4 | 5 | ## Installation 6 | 7 | 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 8 | ```python 9 | from whatsapp import Whatsapp 10 | ``` 11 | 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. 12 | 13 | ## Usage 14 | 15 | **Using This API you can achieve many things in less than 5 lines of code** 16 | 17 | **Sending a message with an emoji:** 18 | 19 | ```python 20 | from whatsapp import WhatsApp 21 | whatsapp = WhatsApp(10) 22 | print(whatsapp.send_message("Name",":heart: Good!")) 23 | ``` 24 | **Result:**
25 | ![Image](https://raw.githubusercontent.com/VISWESWARAN1998/Simple-Yet-Hackable-WhatsApp-api/master/Screenshot%20(747).png) 26 | 27 | **Running from an existing session:** 28 | 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, 29 | ```python 30 | # SWAMI KARUPPASWAMI THUNNAI 31 | 32 | import os 33 | from whatsapp import WhatsApp 34 | 35 | whatsapp = WhatsApp(100, session="mysession") 36 | whatsapp.send_document("Thamarai", os.path.join(os.getcwd(), "message.txt")) 37 | ``` 38 | 39 | Your data will be saved into `mysession` folder from the above example. Make sure you protect your session folder. 40 | 41 | **Getting the status message of a person:** 42 | 43 | ```python 44 | from whatsapp import WhatsApp 45 | whatsapp = WhatsApp(10) 46 | print(whatsapp.get_status("Name")) 47 | ``` 48 | 49 | **Getting last seen of a person:** 50 | 51 | ```python 52 | from whatsapp import WhatsApp 53 | whatsapp = WhatsApp(10) 54 | print(whatsapp.get_last_seen("Name")) 55 | ``` 56 | 57 | **Getting the no of participants in the group:** 58 | 59 | ```python 60 | from whatsapp import WhatsApp 61 | whatsapp = WhatsApp(10) 62 | result = app.participants_count_for_group("The Night Ghost Company") 63 | ``` 64 | 65 | **creating a new group and getting invite link** 66 | 67 | ```python 68 | # SWAMI KARUPPASWAMI THUNNAI 69 | 70 | from whatsapp import WhatsApp 71 | import time 72 | 73 | app = WhatsApp(100) 74 | parameter1: group name, parameter 2: group members 75 | app.create_group("group", ["Thamarai", "Jeeva"]) 76 | time.sleep(10) 77 | print(app.get_invite_link_for_group("group")) 78 | ``` 79 | 80 | **Join the group using invite link** 81 | ```python 82 | # SWAMI KARUPPASWAMI THUNNAI 83 | 84 | from whatsapp import WhatsApp 85 | 86 | app = WhatsApp(10) 87 | app.override_timeout(30) 88 | app.join_group("https://chat.whatsapp.com/4AIA2B3GuLp4RJOKF0M8zY") 89 | app.send_blind_message("I am in :)") 90 | 91 | ``` 92 | 93 | 94 | **Exiting the group** 95 | ```python 96 | # SWAMI KARUPPASWAMI THUNNAI 97 | 98 | from whatsapp import WhatsApp 99 | 100 | app = WhatsApp(100) 101 | app.exit_group("X-Test") 102 | 103 | ``` 104 | 105 | **Sending Anonymous messages [WHATSAPP WILL BAN YOUR PHONE NUMBER IF YOU SEND MANY ANONYMOUS MESSAGES]**
106 | *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* 107 | ```python 108 | # SWAMI KARUPPASWAMI THUNNAI 109 | 110 | from whatsapp import WhatsApp 111 | 112 | app = WhatsApp(10) 113 | app.send_anon_message("91XXXXXXXXXX", "I am sorry for what is happening sir! But I have no other choice.") 114 | ``` 115 | 116 | **Sending Messages to multiple participants**
117 | 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. 118 | 119 | ```python 120 | # SWAMI KARUPPASWAMI THUNNAI 121 | 122 | from whatsapp import WhatsApp 123 | import time 124 | 125 | app = WhatsApp(100) 126 | app.override_timeout(30) 127 | participants = app.get_group_participants("GDG") 128 | print(participants) 129 | 130 | for participant in participants: 131 | print("Sending: ", participant) 132 | time.sleep(1) 133 | try: 134 | app.send_message(participant.strip(), "Hello, I'm a bot. And this is a research. Please ignore me and dont ping back") 135 | except Exception as e: 136 | print(e) 137 | participant = participant.replace("+", "") 138 | participant = participant.replace(" ", "") 139 | app.send_anon_message(participant.strip(), "Hello, I'm a bot. And this is a research. Please ignore me and dont ping back") 140 | app.goto_main() 141 | 142 | ``` 143 | 144 | **Sending pictures to a person:** 145 | 146 | ```python 147 | # Note of Thanks: This part of code have been taken from WhatsApp Assistant bot by Jean-Claude Tissier(@jctissier). 148 | # Github repo-link: https://github.com/jctissier/whatsapp-assistant-bot 149 | # License: MIT 150 | app.send_picture("Vignesh", os.getcwd()+"/pic.jpg") 151 | ``` 152 | 153 | **Sending documents to a person:** 154 | 155 | ```python 156 | # SWAMI KARUPPASWAMI THUNNAI 157 | 158 | import os 159 | from whatsapp import WhatsApp 160 | 161 | whatsapp = WhatsApp(100) 162 | whatsapp.send_document("Thamarai", os.path.join(os.getcwd(), "message.txt")) 163 | ``` 164 | 165 | **Clearing the chat:** 166 | 167 | ```python 168 | # SWAMI KARUPPASWAMI THUNNAI 169 | 170 | from whatsapp import WhatsApp 171 | 172 | whatsapp = WhatsApp(100) 173 | whatsapp.clear_chat("Test") 174 | ``` 175 | 176 | **Getting usernames with unread messages:** 177 | Will return the list of usernames for which we have yet to reply that person. Increase the count of scrolls according to your needs. 178 | 179 | ```python 180 | # SWAMI KARUPPASWAMI THUNNAI 181 | 182 | from whatsapp import WhatsApp 183 | 184 | whatsapp = WhatsApp(100, session="mysession") 185 | print(whatsapp.unread_usernames(scrolls=1000)) 186 | ``` 187 | 188 | and we will receive an output as a Python list. Something like this, 189 | 190 | ``` 191 | ['Ziv Freelance Employer', 'Vignesh', 'InstagramTest', '+91 9xx36 8xxx2', 'Sundar Sir', '+91 xxx47 8xxx9'] 192 | ``` 193 | 194 | ### Getting the last sent messages for a username: 195 | 196 | ```python 197 | # SWAMI KARUPPASWAMI THUNNAI 198 | 199 | from whatsapp import WhatsApp 200 | 201 | whatsapp = WhatsApp(100, session="mysession") 202 | messages = whatsapp.get_last_message_for("Thamarai") 203 | print(messages) 204 | ``` 205 | 206 | *Note:* I am still working on it and it might break. 207 | 208 | ### Interesting use cases: 209 | 210 | **Replying to all stale messages:** 211 | 212 | ```python 213 | # SWAMI KARUPPASWAMI THUNNAI 214 | 215 | from whatsapp import WhatsApp 216 | 217 | whatsapp = WhatsApp(100, session="mysession") 218 | usernames = whatsapp.unread_usernames(scrolls=1000) 219 | for username in usernames: 220 | try: 221 | whatsapp.send_message(username, "Hello I am a bot, apologies that my creator hasn't replied to you yet. please ping again. ") 222 | whatsapp.send_blind_message("Know more about me: https://github.com/VISWESWARAN1998/Simple-Yet-Hackable-WhatsApp-api") 223 | except: 224 | print("You don't have permission to send message to this group/person") 225 | ``` 226 | 227 | 228 | **Note:** Ir just automated the whatsapp, Nothing More, Nothing Less. This program is Licensed under Apache 2.0. 229 | 230 | Thank you for so many stars on this project, you can support me in follwing ways, 231 | 232 | 1. Paypal: visweswaran.nagasivam98@gmail.com 233 | 2. 1 GitHub follower = 1 supporter for me to get recogonized. 234 | 3. LinkedIn skill Endorsement: https://www.linkedin.com/in/visweswaran-nagasivam-975a8b167/ 235 | -------------------------------------------------------------------------------- /Screenshot (747).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VISWESWARAN1998/Simple-Yet-Hackable-WhatsApp-api/745533ff01d3d18d7b313b45246359e03f50a0d2/Screenshot (747).png -------------------------------------------------------------------------------- /emoji.json: -------------------------------------------------------------------------------- 1 | { 2 | ":laughing:" : ":-d", 3 | ":neutral_face:" : ":-|", 4 | "stuck_out_tongue:" : ":-p", 5 | ":heart:" : "<3", 6 | ":simple_smile:" : ":-)", 7 | ":worried:" : ":-(", 8 | ":-1:" : "(n)", 9 | ":thumbsup:" : "(y)", 10 | ":wink:" : ";-)" 11 | } -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | selenium==3.12.0 2 | requests==2.20.0 3 | Pillow==8.1.1 4 | beautifulsoup4==4.6.3 5 | -------------------------------------------------------------------------------- /whatsapp.py: -------------------------------------------------------------------------------- 1 | # SWAMI KARUPPASWAMI THUNNAI 2 | 3 | # ============================================================ 4 | # Simple yet Hackable! WhatsApp API [UNOFFICIAL] for Python3 5 | # Note: The author gives permission to use it under Apache 2.0 6 | # Special Thanks To: alecxe, For reviewing my code! 7 | # ============================================================ 8 | 9 | import time 10 | import datetime as dt 11 | import json 12 | import os 13 | import requests 14 | import shutil 15 | import pickle 16 | from PIL import Image 17 | from selenium import webdriver 18 | from selenium.webdriver.common.by import By 19 | from selenium.webdriver.support import expected_conditions as EC 20 | from selenium.webdriver.common.keys import Keys 21 | from selenium.webdriver.support.ui import WebDriverWait 22 | from selenium.common.exceptions import NoSuchElementException, ElementNotVisibleException 23 | from selenium.webdriver.common.alert import Alert 24 | from selenium.webdriver.common.action_chains import ActionChains 25 | from selenium.common.exceptions import TimeoutException 26 | from selenium.webdriver.chrome.options import Options 27 | from urllib.parse import urlencode 28 | try: 29 | from bs4 import BeautifulSoup 30 | except ModuleNotFoundError: 31 | print("Beautiful Soup Library is required to make this library work(For getting participants list for the specified group).\npip3 install beautifulsoup4") 32 | 33 | 34 | class WhatsAppElements: 35 | 36 | search = (By.CSS_SELECTOR, "#side > div.SgIJV > div > label > div > div._2_1wd.copyable-text.selectable-text") 37 | attach_icon = (By.CSS_SELECTOR, ".bDS3i > div:nth-child(1) > div:nth-child(1) > span:nth-child(1)") 38 | 39 | 40 | class WhatsApp: 41 | """ 42 | This class is used to interact with your whatsapp [UNOFFICIAL API] 43 | """ 44 | emoji = {} # This dict will contain all emojies needed for chatting 45 | browser = None 46 | timeout = 10 # The timeout is set for about ten seconds 47 | 48 | # This constructor will load all the emojies present in the json file and it will initialize the webdriver 49 | def __init__(self, wait, screenshot=None, session=None): 50 | chrome_options = Options() 51 | if session: 52 | chrome_options.add_argument("--user-data-dir={}".format(session)) 53 | self.browser = webdriver.Chrome(options=chrome_options) # we are using chrome as our webbrowser 54 | else: 55 | self.browser = webdriver.Chrome() 56 | self.browser.get("https://web.whatsapp.com/") 57 | # emoji.json is a json file which contains all the emojis 58 | with open("emoji.json") as emojies: 59 | self.emoji = json.load(emojies) # This will load the emojies present in the json file into the dict 60 | WebDriverWait(self.browser,wait).until(EC.presence_of_element_located( 61 | WhatsAppElements.search)) 62 | if screenshot is not None: 63 | self.browser.save_screenshot(screenshot) # This will save the screenshot to the specified file location 64 | 65 | # This method is used to send the message to the individual person or a group 66 | # will return true if the message has been sent, false else 67 | def send_message(self, name, message): 68 | message = self.emojify(message) # this will emojify all the emoji which is present as the text in string 69 | search = self.browser.find_element(*WhatsAppElements.search) 70 | search.send_keys(name+Keys.ENTER) # we will send the name to the input key box 71 | try: 72 | send_msg = WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located( 73 | (By.XPATH, "/html/body/div/div/div/div[4]/div/footer/div[1]/div[2]/div/div[2]"))) 74 | messages = message.split("\n") 75 | for msg in messages: 76 | send_msg.send_keys(msg) 77 | send_msg.send_keys(Keys.SHIFT+Keys.ENTER) 78 | send_msg.send_keys(Keys.ENTER) 79 | return True 80 | except TimeoutException: 81 | raise TimeoutError("Your request has been timed out! Try overriding timeout!") 82 | except NoSuchElementException: 83 | return False 84 | except Exception: 85 | return False 86 | 87 | # This method will count the no of participants for the group name provided 88 | def participants_count_for_group(self, group_name): 89 | search = self.browser.find_element(*WhatsAppElements.search) 90 | search.send_keys(group_name+Keys.ENTER) # we will send the name to the input key box 91 | # some say this two try catch below can be grouped into one 92 | # but I have some version specific issues with chrome [Other element would receive a click] 93 | # in older versions. So I have handled it spereately since it clicks and throws the exception 94 | # it is handled safely 95 | try: 96 | click_menu = WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located( 97 | (By.CSS_SELECTOR, "._19vo_ > span:nth-child(1)"))) 98 | click_menu.click() 99 | except TimeoutException: 100 | raise TimeoutError("Your request has been timed out! Try overriding timeout!") 101 | except NoSuchElementException as e: 102 | return "None" 103 | except Exception as e: 104 | return "None" 105 | current_time = dt.datetime.now() 106 | participants_selector = "div._2LSbZ:nth-child(5) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > span:nth-child(1)" 107 | while True: 108 | try: 109 | participants_count = self.browser.find_element_by_css_selector(participants_selector).text 110 | if "participants" in participants_count: 111 | return participants_count 112 | except Exception as e: 113 | pass 114 | new_time = dt.datetime.now() 115 | elapsed_time = (new_time - current_time).seconds 116 | if elapsed_time > self.timeout: 117 | return "NONE" 118 | 119 | # This method is used to get all the participants 120 | def get_group_participants(self, group_name): 121 | self.participants_count_for_group(group_name) 122 | search = self.browser.find_element(*WhatsAppElements.search) 123 | search.send_keys(group_name+Keys.ENTER) # we will send the name to the input key box 124 | # some say this two try catch below can be grouped into one 125 | # but I have some version specific issues with chrome [Other element would receive a click] 126 | # in older versions. So I have handled it spereately since it clicks and throws the exception 127 | # it is handled safely 128 | try: 129 | click_menu = WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located( 130 | (By.CSS_SELECTOR, "#main > header > div._1WBXd > div._2EbF- > div > span"))) 131 | click_menu.click() 132 | except TimeoutException: 133 | raise TimeoutError("Your request has been timed out! Try overriding timeout!") 134 | except NoSuchElementException as e: 135 | return "None" 136 | except Exception as e: 137 | return "None" 138 | participants = [] 139 | scrollbar = self.browser.find_element_by_css_selector("#app > div > div > div.MZIyP > div._3q4NP._2yeJ5 > span > div > span > div > div") 140 | for v in range(1, 70): 141 | print(v) 142 | self.browser.execute_script('arguments[0].scrollTop = '+str(v*300), scrollbar) 143 | time.sleep(0.10) 144 | elements = self.browser.find_elements_by_tag_name("span") 145 | for element in elements: 146 | try: 147 | html = element.get_attribute('innerHTML') 148 | soup = BeautifulSoup(html, "html.parser") 149 | for i in soup.find_all("span", class_="_3TEwt"): 150 | if i.text not in participants: 151 | participants.append(i.text) 152 | print(i.text) 153 | except Exception as e: 154 | pass 155 | elements = self.browser.find_elements_by_tag_name("div") 156 | for element in elements: 157 | try: 158 | html = element.get_attribute('innerHTML') 159 | soup = BeautifulSoup(html, "html.parser") 160 | for i in soup.find_all("div", class_="_25Ooe"): 161 | j = i.find("span", class_="_1wjpf") 162 | if j: 163 | j = j.text 164 | if "\n" in j: 165 | j = j.split("\n") 166 | j = j[0] 167 | j = j.strip() 168 | if j not in participants: 169 | participants.append(j) 170 | print(j) 171 | except Exception as e: 172 | pass 173 | return participants 174 | 175 | # This method is used to get the main page 176 | def goto_main(self): 177 | try: 178 | self.browser.refresh() 179 | Alert(self.browser).accept() 180 | except Exception as e: 181 | print(e) 182 | WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located( 183 | WhatsAppElements.search)) 184 | 185 | 186 | 187 | # get the status message of a person 188 | # TimeOut is approximately set to 10 seconds 189 | def get_status(self, name): 190 | search = self.browser.find_element(*WhatsAppElements.search) 191 | search.send_keys(name+Keys.ENTER) # we will send the name to the input key box 192 | try: 193 | group_xpath = "/html/body/div/div/div/div[3]/header/div[1]/div/span/img" 194 | click_menu = WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located( 195 | (By.XPATH, group_xpath))) 196 | click_menu.click() 197 | except TimeoutException: 198 | raise TimeoutError("Your request has been timed out! Try overriding timeout!") 199 | except NoSuchElementException: 200 | return "None" 201 | except Exception: 202 | return "None" 203 | try: 204 | status_css_selector = ".drawer-section-body > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > span:nth-child(1) > span:nth-child(1)" # This is the css selector for status 205 | WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located( 206 | (By.CSS_SELECTOR, status_css_selector))) 207 | status = self.browser.find_element_by_css_selector(status_css_selector).text 208 | # We will try for 100 times to get the status 209 | for i in range(10): 210 | if len(status) > 0: 211 | return status 212 | else: 213 | time.sleep(1) # we need some delay 214 | return "None" 215 | except TimeoutException: 216 | raise TimeoutError("Your request has been timed out! Try overriding timeout!") 217 | except NoSuchElementException: 218 | return "None" 219 | except Exception: 220 | return "None" 221 | 222 | # to get the last seen of the person 223 | def get_last_seen(self, name, timeout=10): 224 | search = self.browser.find_element(*WhatsAppElements.search) 225 | search.send_keys(name+Keys.ENTER) # we will send the name to the input key box 226 | last_seen_css_selector = "._315-i" 227 | start_time = dt.datetime.now() 228 | try: 229 | WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located( 230 | (By.CSS_SELECTOR, last_seen_css_selector))) 231 | while True: 232 | last_seen = self.browser.find_element_by_css_selector(last_seen_css_selector).text 233 | if last_seen and "click here" not in last_seen: 234 | return last_seen 235 | end_time = dt.datetime.now() 236 | elapsed_time = (end_time-start_time).seconds 237 | if elapsed_time > 10: 238 | return "None" 239 | except TimeoutException: 240 | raise TimeoutError("Your request has been timed out! Try overriding timeout!") 241 | except NoSuchElementException: 242 | return "None" 243 | except Exception: 244 | return "None" 245 | 246 | # This method does not care about anything, it sends message to the currently active chat 247 | # you can use this method to recursively send the messages to the same person 248 | def send_blind_message(self, message): 249 | try: 250 | message = self.emojify(message) 251 | send_msg = WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located( 252 | (By.XPATH, "/html/body/div/div/div/div[4]/div/footer/div[1]/div[2]/div/div[2]"))) 253 | messages = message.split("\n") 254 | for msg in messages: 255 | send_msg.send_keys(msg) 256 | send_msg.send_keys(Keys.SHIFT+Keys.ENTER) 257 | send_msg.send_keys(Keys.ENTER) 258 | return True 259 | except NoSuchElementException: 260 | return "Unable to Locate the element" 261 | except Exception as e: 262 | print(e) 263 | return False 264 | 265 | # This method will send you the picture 266 | def send_picture(self, name, picture_location, caption=None): 267 | search = self.browser.find_element(*WhatsAppElements.search) 268 | search.send_keys(name+Keys.ENTER) # we will send the name to the input key box 269 | try: 270 | send_file_xpath = '/html/body/div[1]/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/span/div/div/span' 271 | attach_type_xpath = '/html/body/div[1]/div/div/div[4]/div/footer/div[1]/div[1]/div[2]/div/span/div/div/' \ 272 | 'ul/li[1]/button/input' 273 | # open attach menu 274 | attach_btn = self.browser.find_element(*WhatsAppElements.attach_icon) 275 | attach_btn.click() 276 | 277 | # Find attach file btn and send screenshot path to input 278 | time.sleep(1) 279 | attach_img_btn = self.browser.find_element_by_xpath(attach_type_xpath) 280 | 281 | # TODO - might need to click on transportation mode if url doesn't work 282 | attach_img_btn.send_keys(picture_location) # get current script path + img_path 283 | time.sleep(1) 284 | if caption: 285 | caption_xpath = "/html/body/div[1]/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/div[1]/span/" \ 286 | "div/div[2]/div/div[3]/div[1]/div[2]" 287 | send_caption = self.browser.find_element_by_xpath(caption_xpath) 288 | send_caption.send_keys(caption) 289 | send_btn = self.browser.find_element_by_xpath(send_file_xpath) 290 | send_btn.click() 291 | 292 | except (NoSuchElementException, ElementNotVisibleException) as e: 293 | print(str(e)) 294 | 295 | # For sending documents 296 | def send_document(self, name, document_location): 297 | search = self.browser.find_element(*WhatsAppElements.search) 298 | search.send_keys(name+Keys.ENTER) # we will send the name to the input key box 299 | try: 300 | attach_xpath = '//*[@id="main"]/header/div[3]/div/div[2]/div' 301 | send_file_xpath = '/html/body/div[1]/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/span/div/div/span' 302 | attach_type_xpath = '/html/body/div[1]/div/div/div[4]/div/header/div[3]/div/div[2]/span/div/div/ul/li[3]' \ 303 | '/button/input' 304 | # open attach menu 305 | attach_btn = self.browser.find_element_by_xpath(attach_xpath) 306 | attach_btn.click() 307 | 308 | # Find attach file btn and send screenshot path to input 309 | time.sleep(1) 310 | attach_img_btn = self.browser.find_element_by_xpath(attach_type_xpath) 311 | 312 | # TODO - might need to click on transportation mode if url doesn't work 313 | attach_img_btn.send_keys(document_location) # get current script path + img_path 314 | time.sleep(1) 315 | send_btn = self.browser.find_element_by_xpath(send_file_xpath) 316 | send_btn.click() 317 | 318 | except (NoSuchElementException, ElementNotVisibleException) as e: 319 | print(str(e)) 320 | 321 | 322 | 323 | # Clear the chat 324 | def clear_chat(self, name): 325 | self.browser.find_element(*WhatsAppElements.search).send_keys(name+Keys.ENTER) 326 | menu_xpath = "/html/body/div[1]/div/div/div[4]/div/header/div[3]/div/div[3]/div/span" 327 | WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located( 328 | (By.XPATH, menu_xpath))) 329 | menu = self.browser.find_element_by_xpath(menu_xpath) 330 | menu.click() 331 | chains = ActionChains(self.browser) 332 | for i in range(4): 333 | chains.send_keys(Keys.ARROW_DOWN) 334 | chains.send_keys(Keys.ENTER) 335 | chains.perform() 336 | clear_xpath = '//*[@id="app"]/div/span[2]/div/div/div/div/div/div/div[2]/div[2]' 337 | WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located( 338 | (By.XPATH, clear_xpath))) 339 | self.browser.find_element_by_xpath(clear_xpath).click() 340 | 341 | 342 | 343 | # override the timeout 344 | def override_timeout(self, new_timeout): 345 | self.timeout = new_timeout 346 | 347 | # This method is used to emojify all the text emoji's present in the message 348 | def emojify(self,message): 349 | for emoji in self.emoji: 350 | message = message.replace(emoji,self.emoji[emoji]) 351 | return message 352 | 353 | def get_profile_pic(self, name): 354 | search = self.browser.find_element(*WhatsAppElements.search) 355 | search.send_keys(name+Keys.ENTER) 356 | try: 357 | open_profile = WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located( 358 | (By.XPATH, "/html/body/div[1]/div/div/div[3]/div/header/div[1]/div/img"))) 359 | open_profile.click() 360 | except: 361 | print("nothing found") 362 | try: 363 | open_pic = WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located( 364 | (By.XPATH, "/html/body/div[1]/div/div/div[1]/div[3]/span/div/span/div/div/div/div[1]/div[1]/div/img"))) 365 | open_pic.click() 366 | except: 367 | print("Nothing found") 368 | try: 369 | img = WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located( 370 | (By.XPATH,'//*[@id="app"]/div/span[2]/div/div/div[2]/div/div/div/div/img'))) 371 | except: 372 | print("Couldn't find the URL to the image") 373 | img_src_url = img.get_attribute('src') 374 | self.browser.get(img_src_url) 375 | self.browser.save_screenshot(name+"_img.png") 376 | 377 | def create_group(self, group_name, members): 378 | more = self.browser.find_element_by_css_selector("#side > header > div._20NlL > div > span > div:nth-child(3) > div > span") 379 | more.click() 380 | chains = ActionChains(self.browser) 381 | chains.send_keys(Keys.ARROW_DOWN+Keys.ENTER) 382 | chains.perform() 383 | for member in members: 384 | contact_name = self.browser.find_element_by_css_selector("._16RnB") 385 | contact_name.send_keys(member+Keys.ENTER) 386 | time.sleep(3) # little delay to make the process robust 387 | next_step = self.browser.find_element_by_css_selector("._3hV1n > span:nth-child(1)") 388 | next_step.click() 389 | group_text = self.browser.find_element_by_css_selector(".bsmJe > div:nth-child(2)") 390 | group_text.send_keys(group_name+Keys.ENTER) 391 | 392 | def set_group_picture(self, group_name, picture_location): 393 | search = self.browser.find_element(*WhatsAppElements.search) 394 | search.send_keys(group_name+Keys.ENTER) # we will send the group name to the input key box 395 | try: 396 | menu_xpath = '/html/body/div[1]/div/div/div[4]/div/header/div[3]/div/div[3]/div/span' 397 | group_info_xpath = '/html/body/div[1]/div/div/div[4]/div/header/div[3]/div/div[3]/span/div/ul/li[1]/div' 398 | image_input_xpath = '/html/body/div[1]/div/div/div[2]/div[3]/span/div/span/div/div/div[1]/div[1]/div[1]/div/input' 399 | zoom_out_xpath = '/html/body/div[1]/div/span[2]/div/div/div/div/div/div/span/div/div/div[1]/div[1]/div[2]/span' 400 | save_btn_xpath = '/html/body/div[1]/div/span[2]/div/div/div/div/div/div/span/div/div/div[2]/span/div/div' 401 | exit_group_info_xpath = '/html/body/div[1]/div/div/div[2]/div[3]/span/div/span/div/header/div/div[1]/button/span' 402 | 403 | # open group info 404 | menu = self.browser.find_element_by_xpath(menu_xpath) 405 | menu.click() 406 | time.sleep(1) 407 | group_info = self.browser.find_element_by_xpath(group_info_xpath) 408 | group_info.click() 409 | 410 | # find image input and send picutre path 411 | time.sleep(1) 412 | image_input = self.browser.find_element_by_xpath(image_input_xpath) 413 | image_input.send_keys(picture_location) 414 | 415 | # zoom out picture and save 416 | time.sleep(1) 417 | zoom_out = self.browser.find_element_by_xpath(zoom_out_xpath) 418 | for i in range(0, 5): 419 | zoom_out.click() 420 | save_btn = self.browser.find_element_by_xpath(save_btn_xpath) 421 | save_btn.click() 422 | 423 | # close the group info 424 | time.sleep(1) 425 | exit_group_info = self.browser.find_element_by_xpath(exit_group_info_xpath) 426 | exit_group_info.click() 427 | except (NoSuchElementException, ElementNotVisibleException) as e: 428 | print(str(e)) 429 | 430 | def join_group(self, invite_link): 431 | self.browser.get(invite_link) 432 | try: 433 | Alert(self.browser).accept() 434 | except: 435 | print("No alert Found") 436 | join_chat = self.browser.find_element_by_css_selector("#action-button") 437 | join_chat.click() 438 | WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located((By.XPATH, '//*[@id="app"]/div/span[3]/div/div/div/div/div/div/div[2]/div[2]'))) 439 | join_group = self.browser.find_element_by_xpath('//*[@id="app"]/div/span[3]/div/div/div/div/div/div/div[2]/div[2]') 440 | join_group.click() 441 | 442 | # This method is used to get an invite link for a particular group 443 | def get_invite_link_for_group(self, groupname): 444 | search = self.browser.find_element(*WhatsAppElements.search) 445 | search.send_keys(groupname+Keys.ENTER) 446 | self.browser.find_element_by_css_selector("#main > header > div._5SiUq > div._16vzP > div > span").click() 447 | try: 448 | #time.sleep(3) 449 | WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located( 450 | (By.CSS_SELECTOR, "#app > div > div > div.MZIyP > div._3q4NP._2yeJ5 > span > div > span > div > div > div > div:nth-child(5) > div:nth-child(3) > div._3j7s9 > div > div"))) 451 | invite_link = self.browser.find_element_by_css_selector("#app > div > div > div.MZIyP > div._3q4NP._2yeJ5 > span > div > span > div > div > div > div:nth-child(5) > div:nth-child(3) > div._3j7s9 > div > div") 452 | invite_link.click() 453 | WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located( 454 | (By.ID, "group-invite-link-anchor"))) 455 | link = self.browser.find_element_by_id("group-invite-link-anchor") 456 | return link.text 457 | except: 458 | print("Cannot get the link") 459 | 460 | # This method is used to exit a group 461 | def exit_group(self, group_name): 462 | search = self.browser.find_element(*WhatsAppElements.search) 463 | search.send_keys(group_name+Keys.ENTER) 464 | self.browser.find_element_by_css_selector("._2zCDG > span:nth-child(1)").click() 465 | WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located((By.CSS_SELECTOR, "div._1CRb5:nth-child(6) > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > span:nth-child(1)"))) 466 | time.sleep(3) 467 | _exit = self.browser.find_element_by_css_selector("div._1CRb5:nth-child(6) > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > span:nth-child(1)") 468 | _exit.click() 469 | WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located((By.CSS_SELECTOR, "div._1WZqU:nth-child(2)"))) 470 | confirm_exit = self.browser.find_element_by_css_selector("div._1WZqU:nth-child(2)") 471 | confirm_exit.click() 472 | 473 | # Send Anonymous message 474 | def send_anon_message(self, phone, text): 475 | payload = urlencode({"phone": phone, "text": text, "source": "", "data": ""}) 476 | self.browser.get("https://api.whatsapp.com/send?"+payload) 477 | try: 478 | Alert(self.browser).accept() 479 | except: 480 | print("No alert Found") 481 | WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#action-button"))) 482 | send_message = self.browser.find_element_by_css_selector("#action-button") 483 | send_message.click() 484 | confirm = WebDriverWait(self.browser, self.timeout+5).until(EC.presence_of_element_located( 485 | (By.XPATH, "/html/body/div/div/div/div[4]/div/footer/div[1]/div[2]/div/div[2]"))) 486 | confirm.clear() 487 | confirm.send_keys(text+Keys.ENTER) 488 | 489 | # Check if the message is present in an user chat 490 | def is_message_present(self, username, message): 491 | search = self.browser.find_element(*WhatsAppElements.search) 492 | search.send_keys(username+Keys.ENTER) 493 | search_bar = WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located((By.CSS_SELECTOR, "._1i0-u > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > span:nth-child(1)"))) 494 | search_bar.click() 495 | message_search = self.browser.find_element_by_css_selector("._1iopp > div:nth-child(1) > label:nth-child(4) > input:nth-child(1)") 496 | message_search.clear() 497 | message_search.send_keys(message+Keys.ENTER) 498 | try: 499 | WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[1]/div/div/div[2]/div[3]/span/div/div/div[2]/div/div/div/div/div[1]/div/div/div/div[2]/div[1]/span/span/span"))) 500 | return True 501 | except TimeoutException: 502 | return False 503 | 504 | # Get all starred messages 505 | def get_starred_messages(self, delay=10): 506 | starred_messages = [] 507 | self.browser.find_element_by_css_selector("div.rAUz7:nth-child(3) > div:nth-child(1) > span:nth-child(1)").click() 508 | chains = ActionChains(self.browser) 509 | time.sleep(2) 510 | for i in range(4): 511 | chains.send_keys(Keys.ARROW_DOWN) 512 | chains.send_keys(Keys.ENTER) 513 | chains.perform() 514 | time.sleep(delay) 515 | messages = self.browser.find_elements_by_class_name("MS-DH") 516 | for message in messages: 517 | try: 518 | message_html = message.get_attribute("innerHTML") 519 | soup = BeautifulSoup(message_html, "html.parser") 520 | _from = soup.find("span", class_="_1qUQi")["title"] 521 | to = soup.find("div", class_="copyable-text")["data-pre-plain-text"] 522 | message_text = soup.find("span", class_="selectable-text invisible-space copyable-text").text 523 | message.click() 524 | selector = self.browser.find_element_by_css_selector("#main > header > div._5SiUq > div._16vzP > div > span") 525 | title = selector.text 526 | selector.click() 527 | time.sleep(2) 528 | WebDriverWait(self.browser, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR, "div._14oqx:nth-child(3) > div:nth-child(1) > div:nth-child(1) > span:nth-child(1) > span:nth-child(1)"))) 529 | phone = self.browser.find_element_by_css_selector("div._14oqx:nth-child(3) > div:nth-child(1) > div:nth-child(1) > span:nth-child(1) > span:nth-child(1)").text 530 | if title in _from: 531 | _from = _from.replace(title, phone) 532 | else: 533 | to = to.replace(title, phone) 534 | starred_messages.append([_from, to, message_text]) 535 | except Exception as e: 536 | print("Handled: ", e) 537 | return starred_messages 538 | 539 | # Getting usernames which has unread messages 540 | def unread_usernames(self, scrolls=100): 541 | self.goto_main() 542 | initial = 10 543 | usernames = [] 544 | for i in range(0, scrolls): 545 | self.browser.execute_script("document.getElementById('pane-side').scrollTop={}".format(initial)) 546 | soup = BeautifulSoup(self.browser.page_source, "html.parser") 547 | for i in soup.find_all("div", class_="_2EXPL CxUIE"): 548 | if i.find("div", class_="_2FBdJ"): 549 | username = i.find("div", class_="_25Ooe").text 550 | usernames.append(username) 551 | initial += 10 552 | # Remove duplicates 553 | usernames = list(set(usernames)) 554 | return usernames 555 | 556 | # Get the driver object 557 | def get_driver(self): 558 | return self.browser 559 | 560 | # Get last messages 561 | def get_last_message_for(self, name): 562 | messages = list() 563 | search = self.browser.find_element(*WhatsAppElements.search) 564 | search.send_keys(name+Keys.ENTER) 565 | time.sleep(3) 566 | soup = BeautifulSoup(self.browser.page_source, "html.parser") 567 | for i in soup.find_all("div", class_="message-in"): 568 | message = i.find("span", class_="selectable-text") 569 | if message: 570 | message2 = message.find("span") 571 | if message2: 572 | messages.append(message2.text) 573 | messages = list(filter(None, messages)) 574 | return messages 575 | 576 | # This method is used to quit the browser 577 | def quit(self): 578 | self.browser.quit() 579 | --------------------------------------------------------------------------------