forked from shauryauppal/PyWhatsapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPyWhatsapp.py
302 lines (263 loc) · 10.4 KB
/
PyWhatsapp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import schedule
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
try:
import autoit
except ModuleNotFoundError:
pass
import time
import datetime
import os
import argparse
parser = argparse.ArgumentParser(description='PyWhatsapp Guide')
parser.add_argument('--chrome_driver_path', action='store', type=str, default='./chromedriver.exe', help='chromedriver executable path (MAC and Windows path would be different)')
parser.add_argument('--message', action='store', type=str, default='', help='Enter the msg you want to send')
parser.add_argument('--remove_cache', action='store', type=str, default='False', help='Remove Cache | Scan QR again or Not')
args = parser.parse_args()
if args.remove_cache == 'True':
os.system('rm -rf User_Data/*')
browser = None
Contact = None
message = None if args.message == '' else args.message
Link = "https://web.whatsapp.com/"
wait = None
choice = None
docChoice = None
doc_filename = None
unsaved_Contacts = None
def input_contacts():
global Contact, unsaved_Contacts
# List of Contacts
Contact = []
unsaved_Contacts = []
while True:
# Enter your choice 1 or 2
print("PLEASE CHOOSE ONE OF THE OPTIONS:\n")
print("1.Message to Saved Contact number")
print("2.Message to Unsaved Contact number\n")
x = int(input("Enter your choice(1 or 2):\n"))
print()
if x == 1:
n = int(input('Enter number of Contacts to add(count)->'))
print()
for i in range(0, n):
inp = str(input("Enter contact name(text)->"))
inp = '"' + inp + '"'
# print (inp)
Contact.append(inp)
elif x == 2:
n = int(input('Enter number of unsaved Contacts to add(count)->'))
print()
for i in range(0, n):
# Example use: 919899123456, Don't use: +919899123456
# Reference : https://faq.whatsapp.com/en/android/26000030/
inp = str(input("Enter unsaved contact number with country code(interger):\n\nValid input: 91943xxxxx12\nInvalid input: +91943xxxxx12\n\n"))
# print (inp)
unsaved_Contacts.append(inp)
choi = input("Do you want to add more contacts(y/n)->")
if choi == "n":
break
if len(Contact) != 0:
print("\nSaved contacts entered list->", Contact)
if len(unsaved_Contacts) != 0:
print("Unsaved numbers entered list->", unsaved_Contacts)
input("\nPress ENTER to continue...")
def input_message():
global message
# Enter your Good Morning Msg
print()
print("Enter the message and use the symbol '~' to end the message:\nFor example: Hi, this is a test message~\n\nYour message: ")
message = []
temp = ""
done = False
while not done:
temp = input()
if len(temp) != 0 and temp[-1] == "~":
done = True
message.append(temp[:-1])
else:
message.append(temp)
message = "\n".join(message)
print()
print(message)
def whatsapp_login(chrome_path):
global wait, browser, Link
chrome_options = Options()
chrome_options.add_argument('--user-data-dir=./User_Data')
browser = webdriver.Chrome(executable_path=chrome_path, options=chrome_options)
wait = WebDriverWait(browser, 600)
browser.get(Link)
browser.maximize_window()
print("QR scanned")
def send_message(target):
global message, wait, browser
try:
x_arg = '//span[contains(@title,' + target + ')]'
ct = 0
while ct != 10:
try:
group_title = wait.until(EC.presence_of_element_located((By.XPATH, x_arg)))
group_title.click()
break
except:
ct += 1
time.sleep(3)
input_box = browser.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')
for ch in message:
if ch == "\n":
ActionChains(browser).key_down(Keys.SHIFT).key_down(Keys.ENTER).key_up(Keys.ENTER).key_up(Keys.SHIFT).key_up(Keys.BACKSPACE).perform()
else:
input_box.send_keys(ch)
input_box.send_keys(Keys.ENTER)
print("Message sent successfuly")
time.sleep(1)
except NoSuchElementException:
return
def send_unsaved_contact_message():
global message
try:
time.sleep(7)
input_box = browser.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')
for ch in message:
if ch == "\n":
ActionChains(browser).key_down(Keys.SHIFT).key_down(Keys.ENTER).key_up(Keys.ENTER).key_up(Keys.SHIFT).key_up(Keys.BACKSPACE).perform()
else:
input_box.send_keys(ch)
input_box.send_keys(Keys.ENTER)
print("Message sent successfuly")
except NoSuchElementException:
print("Failed to send message")
return
def send_attachment():
# Attachment Drop Down Menu
clipButton = browser.find_element_by_xpath('//*[@id="main"]/header/div[3]/div/div[2]/div/span')
clipButton.click()
time.sleep(1)
# To send Videos and Images.
mediaButton = browser.find_element_by_xpath('//*[@id="main"]/header/div[3]/div/div[2]/span/div/div/ul/li[1]/button')
mediaButton.click()
time.sleep(3)
hour = datetime.datetime.now().hour
# After 5am and before 11am scheduled this.
if(hour >= 5 and hour <= 11):
image_path = os.getcwd() + "\\Media\\" + 'goodmorning.jpg'
# After 9pm and before 11pm schedule this
elif (hour >= 21 and hour <= 23):
image_path = os.getcwd() + "\\Media\\" + 'goodnight.jpg'
else: # At any other time schedule this.
image_path = os.getcwd() + "\\Media\\" + 'howareyou.jpg'
# print(image_path)
autoit.control_focus("Open", "Edit1")
autoit.control_set_text("Open", "Edit1", image_path)
autoit.control_click("Open", "Button1")
time.sleep(3)
whatsapp_send_button = browser.find_element_by_xpath('//*[@id="app"]/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/span[2]/div/div/span')
whatsapp_send_button.click()
# Function to send Documents(PDF, Word file, PPT, etc.)
def send_files():
global doc_filename
# Attachment Drop Down Menu
clipButton = browser.find_element_by_xpath('//*[@id="main"]/header/div[3]/div/div[2]/div/span')
clipButton.click()
time.sleep(1)
# To send a Document(PDF, Word file, PPT)
docButton = browser.find_element_by_xpath('//*[@id="main"]/header/div[3]/div/div[2]/span/div/div/ul/li[3]/button')
docButton.click()
time.sleep(1)
docPath = os.getcwd() + "\\Documents\\" + doc_filename
autoit.control_focus("Open", "Edit1")
autoit.control_set_text("Open", "Edit1", (docPath))
autoit.control_click("Open", "Button1")
time.sleep(3)
whatsapp_send_button = browser.find_element_by_xpath('//*[@id="app"]/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/span[2]/div/div/span')
whatsapp_send_button.click()
def sender():
global Contact, choice, docChoice, unsaved_Contacts
for i in Contact:
send_message(i)
print("Message sent to ", i)
if(choice == "yes"):
try:
send_attachment()
except:
print('Attachment not sent.')
if(docChoice == "yes"):
try:
send_files()
except:
print('Files not sent')
time.sleep(5)
if len(unsaved_Contacts) > 0:
for i in unsaved_Contacts:
link = "https://web.whatsapp.com/send?phone={}&text&source&data&app_absent".format(i)
#driver = webdriver.Chrome()
browser.get(link)
print("Sending message to", i)
send_unsaved_contact_message()
if(choice == "yes"):
try:
send_attachment()
except:
print('Attachment not sent.')
if(docChoice == "yes"):
try:
send_files()
except:
print('Files not sent')
time.sleep(7)
# For GoodMorning Image and Message
schedule.every().day.at("07:00").do(sender)
# For How are you message
schedule.every().day.at("13:35").do(sender)
# For GoodNight Image and Message
schedule.every().day.at("22:00").do(sender)
# Example Schedule for a particular day of week Monday
schedule.every().monday.at("08:00").do(sender)
# To schedule your msgs
def scheduler():
while True:
schedule.run_pending()
time.sleep(1)
if __name__ == "__main__":
print("Web Page Open")
# Append more contact as input to send messages
input_contacts()
if message == None:
# Enter the message you want to send
input_message()
# If you want to schedule messages for
# a particular timing choose yes
# If no choosed instant message would be sent
isSchedule = input('Do you want to schedule your Message(yes/no):')
if(isSchedule == "yes"):
jobtime = input('input time in 24 hour (HH:MM) format - ')
# Send Attachment Media only Images/Video
choice = input("Would you like to send attachment(yes/no): ")
docChoice = input("Would you file to send a Document file(yes/no): ")
if(docChoice == "yes"):
# Note the document file should be present in the Document Folder
doc_filename = input("Enter the Document file name you want to send: ")
# Let us login and Scan
print("SCAN YOUR QR CODE FOR WHATSAPP WEB")
whatsapp_login(args.chrome_driver_path)
# Send message to all Contact List
# This sender is just for testing purpose to check script working or not.
# Scheduling works below.
if(isSchedule == "yes"):
schedule.every().day.at(jobtime).do(sender)
else:
sender()
# First time message sending Task Complete
print("Task Completed")
# Messages are scheduled to send
# Default schedule to send attachment and greet the personal
# For GoodMorning, GoodNight and howareyou wishes
# Comment in case you don't want to send wishes or schedule
scheduler()
# browser.quit()