-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
2008 lines (1766 loc) · 73.6 KB
/
main.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Built-in
import sys, os, time, re, json, html, base64, shutil, subprocess, datetime
import clipboard
import pyperclip
from string import Template
from datetime import timedelta
# Global
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import ElementNotInteractableException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import WebDriverException
import requests
from requests.exceptions import ConnectionError
import urllib.request as request
from io import BytesIO
import win32clipboard
from PIL import Image
import speech_recognition as sr
# Local
from boot.pyrebase import database
from boot.firebase_admin import firestore
class WhatsAppBot:
def __init__(self):
self.on = True
self.driver = None
self.dir = os.path.dirname(__file__)
self.dir_downloads = os.path.dirname(self.dir + '\\downloads\\')
self.dir_uploads = os.path.dirname(self.dir + '\\uploads\\')
# Authentication
self.authenticated = False
self.streaming = False
self.authentication_hash = ''
# Chat
self.phone_number = '' # Put your phone number here
self.chat_opened = False
self.chat_message_text = ''
self.chat_message_sent = False
self.chats_with_unread_messages = None
self.count_of_chats_with_unread_messages = None
self.chat_last_session = None
## Flow
self.flow_enabled_key = None
self.flow_enabled_data = None
## Message
self.last_message = { 'contact_phone': 'message_id' }
# Command
self.executing_command = False
self.bypass_stream_executing = False
self.commands = { '@': False, 'action': 'action_name', 'payload': { 'variable': 'value' } }
# Contact
self.contact_name_in_chat = ''
self.selected_contact_name = None
# Setting
self.settings = { '@': { 'autoresponder': True, 'log': { '@': True, 'terminal': True }, 'restart': False } }
## Chat
### Flow
self.settings_chat_flow = { 'execution': { '@': False } }
## Command
### Execute
self.settings_command_execute = { '@': True, 'close_chat_after_execute': True, 'remove_after_execute': False, 'remove_inactived_message': False }
def boot(self):
self.log('\x1b[0;30;43m' + 'WhatsAppBot booting...' + '\x1b[0m' + '.')
# Database
try:
#* Commands
database.child('commands').child(self.phone_number).child('@').set(self.commands)
#* Flow
database.child('chats').child('flows').child(self.phone_number).stream(self.flowing)
#* Settings
database.child('settings').set(self.settings)
#database.child('settings').child(self.phone_number).set(self.settings)
#*? Chats
database.child('settings').child('chat').child('flow').set(self.settings_chat_flow)
#*? Commands
database.child('settings').child('command').child('execution').set(self.settings_command_execute)
#* Stream
#*? Settings
database.child('settings').stream(self.setting)
#database.child('settings').child(self.phone_number).stream(self.setting)
#*? Commands
database.child('commands').child(self.phone_number).stream(self.executing)
except:
self.log('\x1b[6;30;41m' + 'WhatsAppBot booting... failed! [1] Connecting again...' + '\x1b[0m')
time.sleep(1)
return self.boot()
try:
# Driver
#* Boot
### Chrome
chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_experimental_option('prefs', {
'download.default_directory': self.dir_downloads,
'safebrowsing.enabled': 'false'
})
#options.add_argument('lang=pt-br')
chromeOptions.add_argument('--lang=en-us')
chromeOptions.add_argument('log-level=3')
#* Instance
### Chrome
self.driver = webdriver.Chrome(executable_path=r'chromedriver.exe', options=chromeOptions)
### Firefox
#self.driver = webdriver.Firefox()
#* Configure
self.driver.maximize_window()
#self.driver.implicitly_wait(1) #default is 0
self.driver.set_page_load_timeout(10)
#* Get
self.driver.get('https://web.whatsapp.com/')
except TimeoutException:
self.log('\x1b[6;30;41m' + 'WhatsAppBot booting... failed! [2] Refreshing page...' + '\x1b[0m')
self.driver.refresh()
#except:
# self.log('\x1b[6;30;41m' + 'WhatsAppBot booting... failed! [3] Trying again in 10 seconds...' + '\x1b[0m')
# time.sleep(10)
# return self.boot()
#self.driver.execute_script(
'''
setInterval(function(){
var videos = document.getElementsByTagName("video");
if (videos.length != 0) {
videos[0].removeAttribute("autoplay")
}
}, 10);
'''
#)
self.log('\x1b[6;30;42m' + 'WhatsAppBot started!' + '\x1b[0m' + '.')
def log(self, message, color = None, now = True):
if not self.settings['@']['log']['@']:
return
if not self.settings['@']['log']['terminal']:
return
if now:
now = datetime.datetime.now().time()
print(f'[{now}] ', message)
else:
print(message)
def shutdown(self):
self.on = False
self.driver.quit()
self.driver = None
def get_last_downloaded_file_name(self, timeout = 10): # timeout in seconds
main_window = self.driver.current_window_handle
# Open new window
self.driver.execute_script("window.open()")
# Switch to new tab
self.driver.switch_to.window(self.driver.window_handles[-1])
# Navigate to chrome downloads
self.driver.get('chrome://downloads')
# Set file name
file_name = None
# Get file name
while True:
try:
downloadPercentage = self.driver.execute_script("""
var progress = document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('#progress')
if (progress !== null) {
return progress.value;
}
else {
return false;
}
""")
if downloadPercentage == False or downloadPercentage == 100:
file_name = self.driver.execute_script("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content #file-link').text")
break
except:
pass
time.sleep(1)
if time.time() > time.time() + timeout:
break
# Close current tab
self.driver.execute_script("window.close()")
self.driver.switch_to.window(main_window)
return file_name
#! Authentication
# Authenticate
def authenticate(self):
if not self.driver: return
if not self.authenticated:
try:
# Click to reload QR Code button
qr_refresh_element = self.driver.find_element_by_xpath('//button[(@role="button" or @class="_2znac") and contains(@style, "scale")]')
self.log('\x1b[0;30;43m' + 'Refreshing QR Code...' + '\x1b[0m')
self.wait(1)
qr_refresh_element.click()
self.wait(1)
self.log('\x1b[6;30;42m' + 'Refreshing QR Code... done!' + '\x1b[0m')
except NoSuchElementException:
pass
except ElementNotInteractableException:
self.log('\x1b[6;30;41m' + 'Refreshing QR Code... failed! (Element not iterable)!' + '\x1b[0m')
return
except:
self.log('\x1b[6;30;41m' + 'Refreshing QR Code... failed! (Unknown error)!' + '\x1b[0m')
return
try:
qr_string = self.driver.find_element_by_xpath('//div[@data-ref]').get_attribute('data-ref')
if qr_string != self.authentication_hash:
self.authentication_hash = qr_string
self.authenticated = False
database.child('authentications').child(self.phone_number).set({ "hash": self.authentication_hash, "@": False })
self.log('\x1b[0;31;40m' + f"Authentication Hash: {qr_string}" + '\x1b[0m')
except NoSuchElementException:
try:
self.driver.find_element_by_xpath('//div[contains(@class, "copyable-text selectable-text")]')
self.wait(1)
self.login()
except NoSuchElementException:
#self.log('\x1b[6;30;41m' + 'Auth error! (No Such Element)' + '\x1b[0m')
self.authenticated = False
#except:
# self.log('\x1b[6;30;41m' + 'Auth error! (Unknown error)!' + '\x1b[0m')
# self.authenticated = False
except:
self.authenticated = False
# Login
def login(self):
if not self.driver: return
if not self.authenticated:
self.authenticated = True
database.child('authentications').child(self.phone_number).update({ "@": True })
self.log('\x1b[6;30;42m' + 'WhatsAppBot authenticated!' + '\x1b[0m' + '.')
executed = 0
if self.commands is not None:
for key, command in self.commands.items():
if self.execute(key, command):
executed += 1
if executed > 0:
self.log('\x1b[0;37;44m' + 'Commands executed:' + '\x1b[0m' + f' {executed}')
# Logout
def logout(self):
if not self.driver: return
#self.driver.delete_all_cookies()
self.authenticated = False
#! Contact
## Select contact
def select_contact(self, by, source, contact = None, index = 0):
self.log('\x1b[0;30;44m' + 'Selecting contact...' + '\x1b[0m')
if by == 'name':
if source == 'in_chat_list':
self.select_contact_by_name_loaded_in_chat_list(contact, index)
elif source == 'in_chat_list_search':
self.select_contact_by_name_in_chat_list_search(contact, index)
elif source == 'in_chat_list_pinned':
pass
elif source == 'in_chat_list_not_in_pinned':
pass
elif source == 'in_new_search':
pass
elif source == 'in_group_list':
pass
elif by == 'phone':
if source == 'in_chat_list_search':
pass
elif source == 'in_new_search':
pass
elif source == 'in_group_list':
pass
elif by == 'index':
if source == 'in_new':
pass
elif source == 'in_chat_list':
pass
elif source == 'in_chat_list_pinned':
pass
elif source == 'in_chat_list_not_in_pinned':
pass
self.log('\x1b[6;30;42m' + 'Contact selected!' + '\x1b[0m')
self.log('\x1b[6;30;42m' + f"Contact selected by: {by}" + '\x1b[0m')
self.log('\x1b[6;30;42m' + f"Contact source: {source}" + '\x1b[0m')
### By name
def select_contact_by_name_in_chat_list_search(self, contact_name, index = 0):
#try:
# self.driver.find_element_by_xpath(f'//div[@role="option" and @aria-selected="true" and .//span[@dir="auto" and @title="{contact_name}"]]')
# return
#except:
# pass
try:
if not self.selected_contact_name or not self.chat_opened:
chat_list_search_element = WebDriverWait(self.driver, 1).until(
EC.presence_of_element_located(
(By.XPATH, '//div[@id="app"]//div[contains(@class, "copyable-text selectable-text")]')
)
)
chat_list_search_element.click()
chat_list_search_element.send_keys(contact_name)
chat_list_search_element.send_keys(Keys.ENTER)
self.chat_opened = True
self.selected_contact_name = contact_name
except NoSuchElementException:
self.selected_contact_name = None
self.chat_opened = False
except ElementNotInteractableException:
self.selected_contact_name = None
self.chat_opened = False
except StaleElementReferenceException:
self.selected_contact_name = None
self.chat_opened = False
#except:
# self.chat_opened = False
def select_contact_by_name_loaded_in_chat_list(self, contact_name, index = 0):
try:
# TODO refactor with webdriver wait
chat_item = self.driver.find_element_by_xpath(f'//span[@title="{contact_name}"]')
chat_item.click()
self.chat_opened = True
except NoSuchElementException:
self.chat_opened = False
#except:
# pass
def open_contact_info(self):
try:
header_contact_image = self.driver.find_element_by_xpath('//header[@class="_1UuMR"]/div[@class="_1vGIp"]')
header_contact_image.click()
return True
except:
return False
def get_contact_info(self):
contact = {}
try:
if self.chat_opened:
if self.open_contact_info():
contact_info = WebDriverWait(self.driver, 1).until(
EC.presence_of_element_located(
(By.XPATH, '//div[@class="i5ly3 _299go"]')
)
)
contact_id = contact_info.find_element_by_xpath('.//span[contains(@class, "copyable-text")]/span[@class="_3Tk1z _27rts"]')
try:
contact_name = contact_info.find_element_by_xpath('(.//span[@class="OXGxe _1VzZY"]|.//span[@class="_3ZYWe _27rts"]/span)[last()]')
except:
contact_name = None
try:
contact_image = contact_info.find_element_by_xpath('.//div[@class="Lffaz"]//img')
except:
contact_image = None
if contact_id:
contact['id'] = contact_id.get_attribute('innerHTML')[1:].replace(' ', '').replace('-', '')
# TODO if contact['name'] == contact['id'] then contact['name'] = None
if contact_name:
try:
emojis_imgs = contact_name.find_elements_by_xpath('.//img[@data-plain-text]')
for emoji_img in emojis_imgs:
emoji = emoji_img.get_attribute('data-plain-text')
self.driver.execute_script("arguments[0].innerHTML = arguments[1];", emoji_img, emoji)
except:
pass
contact['name'] = contact_name.get_attribute("textContent")
else:
contact['name'] = None
if contact_image:
matches = re.search(r'u=(.*)%40c', contact_image.get_attribute('src'))
if matches:
contact['image'] = matches.group(1)
except TimeoutException:
# TODO emit error
pass
return contact
#! Chat
def open_chat(self, element):
try:
element.click()
self.chat_opened = True
return True
except:
self.chat_opened = False
return False
def close_chat(self):
first_chat = self.driver.find_element_by_xpath('//div[@id="app"]//div[contains(@aria-label, "Chat list")]/*[1]')
first_chat.click()
self.chat_opened = False
self.selected_contact_name = None
def check_unread_chats_by_title(self):
matches = re.search(r'\((.*)\)', self.driver.title)
if matches:
try:
count = int(matches.group(1))
self.count_of_chats_with_unread_messages = count
return True
except:
self.chats_with_unread_messages = []
return False
else:
self.chats_with_unread_messages = []
return False
def check_unread_chats_in_chat_list(self):
chats_with_unread_messages = self.driver.find_elements_by_xpath('//div[@id="pane-side"]//div[@role="option" and not(.//span[contains(@data-icon, "status-")]) and .//span[@class="VOr2j"] and @aria-selected="false"]')
if chats_with_unread_messages:
self.chats_with_unread_messages = chats_with_unread_messages
self.count_of_chats_with_unread_messages = len(self.chats_with_unread_messages)
return True
else:
self.chats_with_unread_messages = []
self.count_of_chats_with_unread_messages = 0
return False
def check_and_return_unread_chats_in_chat_list(self):
chats_with_unread_messages = self.driver.find_elements_by_xpath('//div[@id="pane-side"]//div[@role="option" and not(.//span[@data-icon="status-dblcheck"] or .//span[@data-icon="status-time"] or .//span[@data-icon="muted"]) and .//span[@class="VOr2j"] and @aria-selected="false"]')
if chats_with_unread_messages:
return chats_with_unread_messages
else:
return []
def get_chat_item_info(self, chat_list_item):
#! Contact
#try:
# chat_contact_image_src = chat_list_item.find_element_by_xpath('.//img').get_attribute('src')
# matches = re.search(r'u=(.*)%40c', chat_contact_image_src)
# if matches:
# chat_contact_id = matches.group(1)
# chat_contact_name = chat_list_item.find_element_by_xpath('.//span[@dir="auto" and @title]').get_attribute("textContent")
# if chat_contact_name[1:] == '+' and chat_contact_name[1:].replace(' ', '').replace('-', '') == chat_contact_id:
# chat_contact_name = None
#except NoSuchElementException:
# chat_contact_image_src = None
# chat_contact_id = None
# chat_contact_name = None
#! Message
#? Count
try:
chat_message_count = int(chat_list_item.find_element_by_xpath('.//span[@aria-label]').get_attribute("textContent"))
except:
chat_message_count = 0
#? Type
chat_message_type_audio = False
chat_message_type_ptt = False
chat_message_type_document = False
chat_message_type_image = False
chat_message_type_video = False
chat_message_type_location = False
chat_message_type_contact = False
try:
chat_list_item.find_element_by_xpath('.//span[@class="_3MjzD"]/div[contains(@class, "_3sDwr") or contains(@class, "status-")]')
chat_message_type_text = False
except NoSuchElementException:
chat_message_type_text = True
chat_message_text = ''
if not chat_message_type_text:
### Audio
try:
chat_message_type_audio = chat_list_item.find_element_by_xpath('.//span[@data-icon="status-audio"]')
except NoSuchElementException:
chat_message_type_audio = False
### PTT
try:
chat_message_type_ptt = chat_list_item.find_element_by_xpath('.//span[@data-icon="status-ptt"]')
except NoSuchElementException:
chat_message_type_ptt = False
### Document
try:
chat_message_type_document = chat_list_item.find_element_by_xpath('.//span[@data-icon="status-document"]')
except NoSuchElementException:
chat_message_type_document = False
### Image
try:
chat_message_type_image = chat_list_item.find_element_by_xpath('.//span[@data-icon="status-image"]')
except NoSuchElementException:
chat_message_type_image = False
### Video
try:
chat_message_type_video = chat_list_item.find_element_by_xpath('.//span[@data-icon="status-video"]')
except NoSuchElementException:
chat_message_type_video = False
### Location
try:
chat_message_type_location = chat_list_item.find_element_by_xpath('.//span[@data-icon="status-location"]')
except NoSuchElementException:
chat_message_type_location = False
### Contact
try:
chat_message_type_contact = chat_list_item.find_element_by_xpath('.//span[@data-icon="status-vcard"]')
except NoSuchElementException:
chat_message_type_contact = False
else:
try:
chat_message_text = chat_list_item.find_element_by_xpath('.//span[@class="_3MjzD"]').get_attribute('title')[1:-1]
except NoSuchElementException:
chat_message_text = ''
if chat_message_type_text:
chat_message_type = 'text'
elif chat_message_type_ptt:
chat_message_type = 'ptt'
elif chat_message_type_audio:
chat_message_type = 'audio'
elif chat_message_type_document:
chat_message_type = 'document'
elif chat_message_type_image:
chat_message_type = 'image'
elif chat_message_type_video:
chat_message_type = 'video'
elif chat_message_type_location:
chat_message_type = 'location'
elif chat_message_type_contact:
chat_message_type = 'contact'
else:
chat_message_type = None
chat_item_info = {
"@": chat_list_item,
#"contact": {
# "id": chat_contact_id,
# "name": chat_contact_name,
# "image": chat_contact_image_src,
#},
"message": {
"@": {
"@type": chat_message_type,
"text": chat_message_text
},
"unreads": chat_message_count
}
}
return chat_item_info
def select_chats_with_unread_messages(self, limit = None):
try:
chats_unread = WebDriverWait(self.driver, 3).until(
EC.presence_of_all_elements_located(
(By.XPATH, '//div[@id="app"]//span[@class="VOr2j"]')
)
)
i = 0
for chat_unread in chats_unread:
i += 1
#unread_attribute = chat_unread.get_attribute('aria-label')
#unread_count = int(unread_attribute.split(" ", 1)[0])
chat_unread.click()
self.chat_opened = True
time.sleep(1)
if limit and limit == i:
break
except TimeoutException:
pass
#? Input chat
## Text
def click_to_input_chat_text(self):
try:
#chat_input_text_element = self.driver.find_element_by_xpath('//div[@id="app"]//div[contains(@class, "copyable-text selectable-text") and @spellcheck]')
chat_input_text_element = WebDriverWait(self.driver, 2).until(
EC.presence_of_element_located(
(By.XPATH, '//div[@id="app"]//div[contains(@class, "copyable-text selectable-text") and @spellcheck]')
)
)
chat_input_text_element.click()
return chat_input_text_element
except:
return False
def click_to_input_chat_caption(self):
try:
chat_input_caption_element = WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located(
(By.XPATH, '//div[contains(@class, "copyable-text selectable-text") and @spellcheck and not(../div[contains(text(), "message")])]')
)
)
chat_input_caption_element.click()
return chat_input_caption_element
except ElementNotInteractableException:
return False
except:
return False
## Attach
def click_to_input_chat_attach(self):
try:
WebDriverWait(self.driver, 2).until(EC.presence_of_element_located((By.XPATH, '//div[@role="button" and @title="Attach"]'))).click()
return True
except:
return False
def input_chat_attach(self, path):
try:
input_chat_attach = WebDriverWait(self.driver, 2).until(
EC.presence_of_element_located(
(By.XPATH, '//div[@id="app"]//input[@accept="*"]')
)
)
input_chat_attach.send_keys(path)
return True
except:
self.log('\x1b[6;30;41m' + 'Input file failed! [Unknown error]' + '\x1b[0m')
return False
### Audio
def input_chat_attach_audio(self, path):
try:
input_chat_attach = WebDriverWait(self.driver, 2).until(
EC.presence_of_element_located(
(By.XPATH, '//div[@id="app"]//input[@accept="*"]')
)
)
input_chat_attach.send_keys(path)
return True
except:
self.log('\x1b[6;30;41m' + 'Input file audio failed! [Unknown error]' + '\x1b[0m')
return False
### Document
def input_chat_attach_document(self, path):
try:
input_chat_attach = WebDriverWait(self.driver, 2).until(
EC.presence_of_element_located(
(By.XPATH, '//div[@id="app"]//input[@accept="*"]')
)
)
input_chat_attach.send_keys(path)
return True
except:
self.log('\x1b[6;30;41m' + 'Input file document failed! [Unknown error]' + '\x1b[0m')
return False
### Image
def input_chat_attach_image(self, path):
try:
input_chat_attach_image_video = WebDriverWait(self.driver, 2).until(
EC.presence_of_element_located(
(By.XPATH, '//div[@id="app"]//input[@accept="image/*,video/mp4,video/3gpp,video/quicktime"]')
)
)
input_chat_attach_image_video.send_keys(path)
return True
except:
self.log('\x1b[6;30;41m' + 'Input file image failed! [Unknown error]' + '\x1b[0m')
return False
### Video
def input_chat_attach_video(self, path):
try:
input_chat_attach_image_video = WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located(
(By.XPATH, '//div[@id="app"]//input[@accept="image/*,video/mp4,video/3gpp,video/quicktime"]')
)
)
input_chat_attach_image_video.send_keys(path)
return True
except TimeoutException:
self.log('\x1b[6;30;41m' + 'Input file video failed! [Timeout]' + '\x1b[0m')
return False
except:
self.log('\x1b[6;30;41m' + 'Input file video failed! [Unknown error]' + '\x1b[0m')
return False
#! Chat -> Flow
def execute_chat_flow(self, contact, message):
#try:
flows = self.flow_enabled_data
if not flows:
return
session = self.start_chat_session(contact["id"])
keys_stored = session["@"] # '1;2+3+'
flow_level = session["@level"] # 1
keys_found = ''
keys_actived = ''
start_at = None
restart = True
while restart:
restart = False
if keys_stored:
started = True # True
else:
started = False
for key, flow in flows.items(): # TODO replace to key, value?
if key == 'children':
children = flow # children = value
print(children)
if start_at and key != start_at:
continue
if key[-1:] not in [';', '+']:
continue
if not started:
keys_stored = keys_found
else:
keys_stored = keys_stored #[4] '1;2+3+'
keys_found += key #[4] 1;2+3+
# Get flow?
if keys_stored and keys_stored == keys_found: #[2] '1;2+3+' == 1;2+3+
keys_actived = keys_found
if key[-1:] == ';': # Not iterable
break
elif key[-1:] == '+': # Iterable
if 'settings' in flow:
flow_settings = flow['settings']
else:
flow_settings = None
# TODO self.get_chat_flow_settings(flow, 'convert_ptt_to_text_option')?
if flow["@"] == 'menu':
#? Select menu option
if 'option' not in session:
#try:
if not message["text"] or type(message["text"]) != str:
if flow_settings and flow_settings.get('convert_ptt_to_text_option', None) and message['@type'] == 'ptt':
response = self.read_and_save_last_message_in_chat('ptt')
ptt_full_path = response['messages'][0]['ptt']
ptt_dir_path = os.path.dirname(ptt_full_path)
ptt_file_path = os.path.basename(ptt_full_path)
ptt_output_file_path = os.path.join(ptt_dir_path, ptt_file_path.replace('.oga', '.wav'))
converted = self.convert_media_file_using_ffmpeg(ptt_full_path, ptt_output_file_path)
if converted:
text_in_ptt = self.read_text_from_ptt(ptt_output_file_path)
if text_in_ptt:
message["text"] = text_in_ptt
self.log('\x1b[6;30;42m' + 'Option text recognized in PTT:' + '\x1b[0m' + f' {text_in_ptt}')
else:
self.log('\x1b[6;30;41m' + 'Non-text message used in flow menu options' + '\x1b[0m' + ':')
self.close_chat()
return
#except:
# self.log('\x1b[6;30;41m' + 'Error in message used in flow menu options' + '\x1b[0m' + ':')
# print(message)
# self.close_chat()
# return
# Non iterable as option
option = message["text"] + '-'
# Iterable as option
if option not in flow:
option = message["text"] + '+'
# Options id and references
if option not in flow:
for flow_option in flow["options"]:
# id
option_id = flow["options"][flow_option]["id"]
if message["text"] == option_id:
option = flow_option
break
# references
references = flow["options"][flow_option]["references"].split(",")
for reference in references:
if message["text"].lower() == reference:
option = flow["options"][flow_option]["@"]
break
if option in flow:
break
# Recall
if option not in flow:
if 'recall' in flow:
recalls = flow['recall']['references'].split(",")
for recall in recalls:
if message['text'].lower() == recall:
self.execute_component_flow(contact, message, flow)
return self.close_chat()
else:
option = session['option']
# Deselect option
if flow_settings and 'words_to_deselect_option' in flow_settings:
deselects = flow_settings['words_to_deselect_option'].split(",")
for deselect in deselects:
if message['text'].lower() == deselect:
self.execute_component_flow(contact, message, flow)
self.set_chat_session(contact["id"], {
"@": keys_found,
"@component": flow["@"],
"@level": flow_level
})
return self.close_chat()
#? Enter menu option
if option in flow:
flows1 = flow[option]
#flow = flow1
if flows1['@'] == 'node':
pass
elif flows1["@"] == 'menu':
response = self.execute_component_flow(contact, message, flows1)
if response:
self.set_chat_session(contact["id"], {
"@": keys_found + option,
"@component": "menu",
"@level": flow_level + 1
})
break
elif flows1["@"] == 'link':
# TODO remove flow_level?
self.set_chat_session(contact["id"], {
"@": flows1["from"],
"@component": "link",
"@level": flows1["flow_level"]
})
# Set flow loop variables
# TODO build keys_stored dinamically
keys_stored = ''
keys_found = flows1["from"]
start_at = flows1["to"]
flow_level = flows1["flow_level"]
# Restart flow loop and break current loop
flows = self.flow_enabled_data
restart = True
break
elif flows1["@"] == 'send_attachment':
# TODO check if component was executed with successfully
# Execute component flow
self.execute_component_flow(contact, message, flows1)
# Send Menu again
# TODO send menu message again as schedule message after checking if attachment was sent
#self.execute_component_flow(contact, message, flow)
# Close Chat
return self.close_chat()
elif flows1["@"] == 'receive_attachment':
if 'option' in session:
if message['@type'] in flows1['types'] or not flows1['types']:
self.execute_component_flow(contact, message, flows1)
else:
self.send_message_text(flows1['messages']['notice']['type'])
else:
# Send CTA message
self.send_message_text(flows1['messages']['info']['cta'])
# TODO create update session?
# Set session
self.set_chat_session(contact['id'], {
"@": keys_found,
"@component": "menu",
"@level": flow_level,
'option': option
})
# Close Chat
return self.close_chat()
elif flows1["@"] == 'finish_session':
self.reset_chat_session(contact["id"])
self.execute_component_flow(contact, message, flows1)
self.close_chat()
return
else:
# Invalid option
if flow_settings and 'respond_if_option_is_invalid' in flow_settings:
if flow_settings['respond_if_option_is_invalid']:
self.send_message_text('Opção inválida!')
else:
self.send_message_text('Opção inválida!')
return self.close_chat()
elif flow['@'] == 'node':
pass
elif keys_stored and keys_stored.startswith(keys_found): #[2] '1;2+3+' starts with 1;2+1+
keys_actived = keys_found
if key[-1:] == ';': #[1] 1;
continue
elif key[-1:] == '+': #[2] 2+
flows = flow
restart = True
break
elif started:
if key[-1:] == '+': #[3] 1+
keys_found = keys_actived #[3] '1;2+3+' = 1;2+
continue
# Execute component flow
response = self.execute_component_flow(contact, message, flow)
if response == -1:
break
# Update keys_stored with metadata of current node flow
if response:
self.set_chat_session(contact["id"], {
"@": keys_found,
"@component": flow["@"],
"@level": flow_level
})
self.close_chat()
def render_component_message(self, message, contact):
if '$' in message:
template = Template(message)
if '$contact_name' in message:
message = template.substitute(contact_name = contact['name'] if contact['name'] else '')
return message
def execute_component_flow(self, contact, message, flow):
#? Render component message
if 'message' in flow:
component_message = flow["message"]
if '$' in component_message:
template = Template(component_message)
if '$contact_name' in component_message:
component_message = template.substitute(contact_name = contact['name'] if contact['name'] else '')
#? Execute component flow
if flow["@"] == 'start_session':
if 'triggers' in flow:
triggered = False
triggers = flow["triggers"].split(",")
for trigger in triggers:
if message["text"] and message["text"].lower() == trigger:
triggered = True
break
if not triggered:
return -1
return self.send_message_text(component_message)
elif flow["@"] == 'menu':
for flow_option in flow["options"]:
component_message += "\n" + str(flow["options"][flow_option]["id"]) + " - " + flow["options"][flow_option]["label"]
if 'recall' in flow:
component_message += '\n\n' + flow['recall']['message']
return self.send_message_text(component_message)
elif flow["@"] == 'send_attachment':
return self.execute(None, flow["command"])
elif flow['@'] == 'receive_attachment':
response = self.read_and_save_last_message_in_chat(message['@type'])
if flow['~convert']:
if flow['~convert']['@'] == 'text' and (message['@type'] == 'ptt' or message['@type'] == 'audio'):
audio_type = response['messages'][0]['@']
audio_full_path = response['messages'][0][audio_type]
data_converted = self.convert_audio_to_text(audio_full_path)
if flow['~reply']:
if flow['~reply']['@'] == '$messages':
# TODO refactor check if attachment was read
if not response['messages']:
return self.send_message_text(flow['messages']['error']['received'])
# TODO refactor check if attachment was saved
if not response['messages'][0][message['@type']]:
return self.send_message_text(flow['messages']['error']['saved'])