def __init__(self, auto_run=False, auto_long_run=False, headless=False): self._chromedriver = os.environ.get( 'CHROMEDRIVE_PATH', os.path.join(os.path.dirname(__file__), "chromedriver")) self._profile_path = os.path.join(os.path.dirname(__file__), "chromeprofile") self._headless = headless self._driver = WhatsAPIDriver( username="******", client="chrome", profile=self._profile_path, executable_path=self._chromedriver, headless=self._headless, chrome_options=[ "user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36", ], heroku=self._headless) self._bot_actions = BotActions(self._driver) self._thread_pool = ThreadPoolExecutor(max_workers=2) self._threaded_users = [] if auto_long_run: self.keep_running() elif auto_run: self.run()
def init(): global driver global sent_message driver = WhatsAPIDriver() driver.view_unread() schedule.every(20).seconds.do(job) sent_message = construct_message()
def init_driver(client_id): """Initialises a new driver via webwhatsapi module @param client_id: ID of user client @return webwhatsapi object """ # Create profile directory if it does not exist profile_path = CHROME_CACHE_PATH + str(client_id) if not os.path.exists(profile_path): os.makedirs(profile_path) # Options to customize chrome window chrome_options = [ 'window-size=' + CHROME_WINDOW_SIZE, '--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/60.0.3112.78 Chrome/60.0.3112.78 Safari/537.36' ] if CHROME_IS_HEADLESS: chrome_options.append('--headless') if CHROME_DISABLE_GPU: chrome_options.append('--disable-gpu') # Create a whatsapidriver object d = WhatsAPIDriver( username=client_id, profile=profile_path, # client='chrome', client='remote', command_executor=os.environ["SELENIUM"], chrome_options=chrome_options) d.subscribe_new_messages(NewMessageObserver()) return d
def new(self, user): profile = "profiles/%s/" % user media_location = "media/%s/" % user if not os.path.exists(profile): os.makedirs(profile) if not os.path.exists(media_location): os.makedirs(media_location) if self.get(user) == None: obj = { "user": user, "profile": profile, "media_location": media_location, "obj": WhatsAPIDriver(profile=profile, headless=True, loadstyles=True), } self.drivers.append(obj) else: obj_old = self.get(user) obj = self.get(user) obj["obj"] = WhatsAPIDriver(profile=profile, headless=True, loadstyles=True) self.drivers.remove(obj_old) self.drivers.append(obj) return obj
def __init__(self): try: self.driver = WhatsAPIDriver(username="******") # self.driver = webdriver.Chrome() except: print('There was an error in loading the chrome driver.')
def start(self): print("Iniciando bot...") self.driver = WhatsAPIDriver(profile=self.profile) time.sleep(3) if not self.driver.get_status() == "LoggedIn": print("Carregando QRCode") self.driver.get_qr("qrcode.png") print("Escaneie o QRCode no arquivo qrcode.png") self.driver.wait_for_login() print("Bot iniciado") self.driver.save_firefox_profile() while True: time.sleep(1) for contact in self.driver.get_unread(include_me=False, include_notifications=True, use_unread_count=True): if len(contact.messages) == 1: for message in contact.messages: if isinstance(message, Message): self.new_message(message.content, contact) self.driver.chat_send_seen(contact.chat.id) time.sleep(3) else: contact.chat.send_message( "Fico confuso com muitas mensagens :S Por favor, envie uma de cada vez e espere eu responder tá?" ) contact.chat.send_message(CHANNEL_ASK_KEYWORD)
def init(): global driver global contacts try: driver.close() except Exception: pass driver = WhatsAPIDriver(client='chrome') qr_tmp = driver.get_qr() qr = 'static/qr/{}'.format(qr_tmp.split('/')[-1]) shutil.move(qr_tmp, qr) return qr
def check_if_number_exists(driver: WhatsAPIDriver, number: str) -> bool: """ Function to check if a number exists on WhatsApp :param driver: driver object used for checking :param number: The number to check :return: True if the number exists, else false """ try: driver.get_chat_from_phone_number(number, createIfNotFound=True) return True except ChatNotFoundError: return False
def login(): """ Log into WhatsApp Web. Selenium + manually scanning QR-Code once. :return: """ driver = WhatsAPIDriver(username="******") print("Waiting for login") driver.wait_for_login() if driver.is_connected(): print('Driver successfully connected!') return driver
def webCrawler(): #os.system('export PATH=$PATH:/path/t-/geckodriver') driver_executable_path="./geckodriver" driver = WhatsAPIDriver( driver_executable_path="./geckodriver") #driver.firstrun() print("Waiting for QR") driver.wait_for_login() print("Bot started") files = {} caminho = "./" path = './' today_date = "" file_name = "" while True: time.sleep(3) file_name = "AllMessages_" + today_date[-2:] + ".txt" file_t = open(caminho + file_name, 'a', 0) time.sleep(3) #try: msg_list = driver.get_unread(include_me=False, include_notifications=False, use_unread_count=False) if len(msg_list) == 0: continue for i in msg_list: if len(i.messages)>0: print >> file_t, i.chat for j in i.messages: date = get_date_from_message(j) if today_date != date: #update day today_date = date file_t.close() file_name = "AllMessages_" + today_date[-2:] + ".txt" file_t = open(caminho + file_name, 'a', 0) get_text_from_message(j, file_t) get_image_from_message(j) get_video_from_message(j) get_audio_from_message(j) #except Exception, err: # sys.stderr.write('ERROR: %sn' % str(err)) # if 'Message: Tried to run command without establishing a connection' in str(err): # webCrawler() file_t.close()
def Conexion(directorio): global driver print("[+] Conectando...") try: driver = WhatsAPIDriver(client='firefox', loadstyles=True, profile=directorio) print("[+] Esperando validación de QR") driver.wait_for_login() print("[+] Robot Conectado!") return True except: print("[-] No se pudo conectar, intente otra vez.") return False
def wrapper_webdriver_mgmt(): if driver_running: func() else: driver = WhatsAPIDriver() driver_running = True func()
def connectWsp(): global driver if driver == None: driver = WhatsAPIDriver( profile=profiledir, client='remote', command_executor='http://172.17.0.3:4444/wd/hub')
def __init__(self, identifier): self.driver = WhatsAPIDriver(loadstyles=True) self.identifier = identifier self.messagesSent = 0 self.messageQueue = [] self.status = {} print("Waiting for QR") try: self.driver.wait_for_login() super(Whatsapp, self).__init__() self.setDaemon(True) except Exception as ex: print("Error", ex) print("New Browser Opened")
def init_driver(client_id): """Initialises a new driver via webwhatsapi module @param client_id: ID of user client @return webwhatsapi object """ # Create profile directory if it does not exist profile_path = CHROME_CACHE_PATH + str(client_id) if not os.path.exists(profile_path): os.makedirs(profile_path) # Options to customize chrome window chrome_options = [ "window-size=" + CHROME_WINDOW_SIZE, "--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/60.0.3112.78 Chrome/60.0.3112.78 Safari/537.36", ] if CHROME_IS_HEADLESS: chrome_options.append("--headless") if CHROME_DISABLE_GPU: chrome_options.append("--disable-gpu") # Create a whatsapidriver object d = WhatsAPIDriver( username=client_id, profile=profile_path, client="chrome", chrome_options=chrome_options, ) return d
def on_welcome(*args): try: global driver write_log('Socket-Info','Connection success') # In case of reconnect # if driver != None and driver.is_logged_in(): # Send account info # _wsp = {} _wsp['whatsAppJoin'] = driver.is_logged_in() _wsp['bateryLevel'] = driver.get_battery_level() _wsp['numero'] = driver.get_phone_number() _wsp['accountDown'] = False socketIO.emit('change',_wsp) # Send messages old # oldMessges = Thread(target=getOldMessages) oldMessges.start() else: # Send inital data # _wsp = {} _wsp['whatsAppJoin'] = False _wsp['accountDown'] = False socketIO.emit('change',_wsp) driver = WhatsAPIDriver(profile=profiledir, client='remote', command_executor=selemiunIP) write_log('Socket-Info','Check if have cache') rember = Thread(target=rememberSession) rember.start() except Exception as e: write_log('Socket-Error',traceback.format_exc()) errorSend(traceback.format_exc())
def start_web_session() -> Tuple[WhatsAPIDriver, str]: """ Method to start a new session of WhatsApp Web for web app :return: returning the driver object and qr """ # create driver object with above options driver = WhatsAPIDriver(client="remote", command_executor=config("SELENIUM")) # Get the qr code qr_image_path = driver.get_qr() with open(qr_image_path, 'rb') as image: qr = b64encode(image.read()).decode('utf-8') if isfile(qr_image_path): remove(qr_image_path) return driver, qr
def wait_till_login(driver: WhatsAPIDriver): """ wait till user is logged into whatsapp web :param driver: WhatsApiDriver object in which user is trying to login """ login_status = False while not login_status: print("Wait for login...") try: login_status = driver.wait_for_login(timeout=5) except: continue
class WhatsAppAgent(object): def __init__(self): self.driver = WhatsAPIDriver(client=WhatsAppAgentConstants.BROWSER) logger.info("Waiting for successful QR Code scan...") self.driver.wait_for_login() logger.info("Logged in!") def get_all_chats(self): return self.driver.get_all_chats() def get_all_msgs_in_chat(self, chat=None): if chat is None: return [] return self.driver.get_all_messages_in_chat(chat) def get_msg_text(self, message=None): if message is None: return "" return message.safe_content def get_unread_msgs(self): for contact in self.driver.get_unread(): for message in contact.messages: if isinstance(message, Message): whatsAppMsg = WhatsAppAgentMessage( chatId=contact.chat.id, chatName=contact.chat.name, senderId="", senderName=message.sender.get_safe_name(), msgType="", msgData=message.safe_content, msgTime=message.timestamp) logger.debug("New message: %s", whatsAppMsg.readable_format()) def run(self): while True: time.sleep(WhatsAppAgentConstants.NEW_MSG_POLL) self.get_unread_msgs()
def on_getQr(*args): write_log('Socket-Info', 'give the qr') global driver if driver == None: driver = WhatsAPIDriver(profile=profiledir, client='remote', command_executor=selemiunIP) if driver.is_logged_in(): write_log('Socket-Info', 'session started') socketIO.emit('sendQr', {'idSend': args[0], 'status': 'Session okay'}) else: write_log('Socket-Info', 'go to qr') name = uuid4().hex + '.png' if os.path.exists(name): os.remove(name) driver.get_qr(name) write_log('Socket-Info', 'saving qr') shutil.move('./' + name, pathSource + name) socketIO.emit('sendQr', { 'idSend': args[0], 'file': str(pathSource + name) }) on_waitLogin()
def send_message(num: int, msg: str, driver: WhatsAPIDriver): """ Method to send a message to someone :param num: phone number to which message is to be sent :param msg: the message to be sent :param driver: WhatsApidDiver object using which whatsapp web is to be operated :return: string with name and link to chat """ # get chat with user chat = driver.get_chat_from_phone_number(str(num), createIfNotFound=True) try: chat.send_message(msg) # send message except (JsException, JavascriptException): pass
def on_getQr(*args): try: global driver if driver == None: driver = WhatsAPIDriver(profile=profiledir, client='remote', command_executor=selemiunIP) if driver.is_logged_in(): write_log('Socket-Info','session started') socketIO.emit('change',{'whatsAppJoin':True,'accountDown':False}) socketIO.emit('sendQr', {'socketId':args[0],'error':'The session is started'} ) else: write_log('Socket-Info','go to qr') name = uuid4().hex+'.png' if os.path.exists(name): os.remove(name) driver.get_qr(name) write_log('Socket-Info','saving qr') shutil.move('./'+name,pathSource+name) write_log('Socket-Info','send qr') socketIO.emit('sendQr',{'socketId':args[0],'file':str(name)}) on_waitLogin(args[0]) except Exception as e: socketIO.emit('sendQr', {'socketId':args[0],'error':traceback.format_exc()} ) write_log('Socket-Error',traceback.format_exc()) errorSend(traceback.format_exc())
def __init__(self, **kwargs): """Initialises a new driver via webwhatsapi module @param client_id: ID of user client or botname @param profile_path: path to store user data @ """ # Gather the most kwargs will used client_id = kwargs.get('client_id', 'wabot') profile_path = kwargs.get('profile_path', os.getcwd()) # Create profile directory if it does not exist profile_path = os.path.join(profile_path + '/' + str(client_id)) if not os.path.exists(profile_path): os.makedirs(profile_path) # Options to customize chrome window chrome_options = [ 'window-size=' + kwargs.get('windows_size', "910,512"), '--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/60.0.3112.78 Chrome/60.0.3112.78 Safari/537.36' ] if kwargs.get('is_headless', True): chrome_options.append('--headless') if kwargs.get('is_disable_gpu', True): chrome_options.append('--disable-gpu') self.attributes = [] self.properties = {} # Create a whatsapidriver object self.driver = WhatsAPIDriver( username=client_id, profile=profile_path, client='chrome', chrome_options=chrome_options )
def lookup_numbers(number_array): driver = WhatsAPIDriver() print("Waiting for QR") driver.wait_for_login() print("Bot started") yield from lookup_numbers_sync(driver, number_array) print("done") driver.quit()
def init(): pathdir = Path(__file__).parent.absolute() profiledir = str(pathdir) + str("/firefox_cache") if not os.path.exists(profiledir): os.makedirs(profiledir) driver = WhatsAPIDriver(profile=profiledir, loadstyles=True) driver.driver.get(driver._URL) print("Waiting for QR") driver.wait_for_login() print("Saving session") driver.save_firefox_profile(remove_old=False) print("WhatsApp Ready") wabot_loop(driver)
def init_driver(client_id): """Initialises a new driver via webwhatsapi module @param client_id: ID of user client @return webwhatsapi object """ # Create profile directory if it does not exist profile_path = str(client_id) if not os.path.exists(profile_path): os.makedirs(profile_path) # Create a whatsapidriver object d = WhatsAPIDriver(username=client_id, profile=profile_path, client="remote", command_executor="selenium_driver:4444/wd/hub") return d
def __init__(self, bot, user): """ :param bot: The representation of this bot :param user: The command sender id :type bot: telegram.Bot :type user: telegram.User """ # Initialize all values self.bot = bot self.user = user self.driver = WhatsAPIDriver(client="firefox", username="******", chrome_options=[], loadstyles=True, headless=True) self.logged = False self.time = 0 self.chats = []
def run(): profiledir=os.path.join(".","firefox_cache") pic_path=os.path.join(".","marketing.jpeg") driver = WhatsAPIDriver(username="******", profile=profiledir) print("Waiting for QR") driver.wait_for_login() print("Bot started") driver.subscribe_new_messages(NewMessageObserver()) print("Waiting for new messages...") """ Locks the main thread while the subscription in running """ while True: time.sleep(60)
def run(): print("Environment", os.environ) driver = WhatsAPIDriver(username="******") print("Waiting for QR") driver.wait_for_login() print("Bot started") driver.subscribe_new_messages(NewMessageObserver()) print("Waiting for new messages...") """ Locks the main thread while the subscription in running """ while True: time.sleep(60)
def init_driver(client_id): """Initialises a new driver via webwhatsapi module @param client_id: ID of user client @return webwhatsapi object """ # Create profile directory if it does not exist # profile_path = CHROME_CACHE_PATH + str(client_id) # if not os.path.exists(profile_path): # os.makedirs(profile_path) # Create a whatsapidriver object d = WhatsAPIDriver( # executable_path='/app/vendor/firefox/firefox', username=client_id, # profile=profile_path, client='firefox', loadstyles=True, headless=IS_HEADLESS) return d
from orator import DatabaseManager, Model from webwhatsapi import WhatsAPIDriver wppDriver = WhatsAPIDriver(username="******") print("Waiting for QR") wppDriver.wait_for_login() print("Bot started") config = { 'postgres': { 'driver': 'postgres', 'host': '35.247.235.153', 'database': 'tbc_wpp', 'user': '******', 'password': '******', } } db = DatabaseManager(config) Model.set_connection_resolver(db) class Driver(Model): __table__ = 'drivers' pass drivers = Driver.all() print("Buscando motoristas...")
from webwhatsapi.objects.message import Message, MediaMessage print "Environment", os.environ try: os.environ["SELENIUM"] except KeyError: print "Please set the environment variable SELENIUM to Selenium URL" sys.exit(1) ##Save session on "/firefox_cache/localStorage.json". ##Create the directory "/firefox_cache", it's on .gitignore ##The "app" directory is internal to docker, it corresponds to the root of the project. ##The profile parameter requires a directory not a file. profiledir=os.path.join(".","firefox_cache") if not os.path.exists(profiledir): os.makedirs(profiledir) driver = WhatsAPIDriver(profile=profiledir, client='remote', command_executor=os.environ["SELENIUM"]) print("Waiting for QR") driver.wait_for_login() print("Saving session") driver.save_firefox_profile(remove_old=False) print("Bot started") while True: time.sleep(3) print 'Checking for more messages, status', driver.get_status() for contact in driver.get_unread(): for message in contact.messages: print(json.dumps(message.get_js_obj(), indent = 4)) print 'class', message.__class__.__name__ print 'message', message print 'id', message.id
import os import sys import time from webwhatsapi import WhatsAPIDriver driver = WhatsAPIDriver(username="******") for x in arr: chat = driver.get_chat_from_phone_number(x, True) driver.send_message_to_id(chat.id, "testando velocidade do envio")
from webwhatsapi.objects.message import Message, MediaMessage print "Environment", os.environ try: os.environ["SELENIUM"] except KeyError: print "Please set the environment variable SELENIUM to Selenium URL" sys.exit(1) ##Save session on "/firefox_cache/localStorage.json". ##Create the directory "/firefox_cache", it's on .gitignore ##The "app" directory is internal to docker, it corresponds to the root of the project. ##The profile parameter requires a directory not a file. profiledir=os.path.join(".","firefox_cache") if not os.path.exists(profiledir): os.makedirs(profiledir) driver = WhatsAPIDriver(profile=profiledir, client='remote', command_executor=os.environ["SELENIUM"]) print("Waiting for QR") driver.wait_for_login() print("Saving session") driver.save_firefox_profile(remove_old=False) print("Bot started") print("Bot started2") # while True: # time.sleep(3) # print 'Checking for more messages, status', driver.get_status() # for contact in driver.get_unread(): # for message in contact.messages: # print(json.dumps(message.get_js_obj(), indent = 4)) # print 'class', message.__class__.__name__ # print 'message', message
import time from webwhatsapi import WhatsAPIDriver from webwhatsapi.objects.message import Message driver = WhatsAPIDriver(username='******', client='C:\\Users\\raosa\\Desktop\\PROJECTS\\chromedriver.exe') print("Waiting for QR") driver.wait_for_login() print("Bot started") while True: time.sleep(3) print('Checking for more messages') for contact in driver.get_unread(): for message in contact.messages: if isinstance(message, Message): # Currently works for text messages only. contact.chat.send_message(message.safe_content)
# encoding=utf8 import os, sys, time, json, datetime from orator import DatabaseManager, Model from webwhatsapi import WhatsAPIDriver from time import sleep profiledir=os.path.join(".","firefox_cache") pic_path=os.path.join(".","marketing.jpeg") wppDriver = WhatsAPIDriver(username="******", profile=profiledir) print("Waiting for QR") wppDriver.wait_for_login() print("Bot started") wppDriver.save_firefox_profile() config = { 'postgres': { 'driver': 'postgres', 'host': '35.247.235.153', 'database': 'tbc_wpp', 'user': '******', 'password': '******', } } db = DatabaseManager(config) Model.set_connection_resolver(db)
from webwhatsapi import WhatsAPIDriver from webwhatsapi.objects.message import Message driver = WhatsAPIDriver(loadstyles=False) print("Waiting for QR") driver.wait_for_login() print("Bot started") try: phone_safe = "1122333333333" # Phone number with country code phone_whatsapp = "{}@c.us".format(phone_safe) # WhatsApp Chat ID image_path = "image.png" # Local path file caption = "Testing a media sender!" # The caption sent under the image, optional driver.send_media(image_path, phone_whatsapp, caption) # Expected send_media(self, path, chatid, caption) print("Media file was successfully sent to {}".format(phone_safe)) except: print("Error while trying to send the midia file.")