def onMessage(self, messageProtocolEntity): if messageProtocolEntity.getType() == "text": time.sleep(0.5) self.toLower(messageProtocolEntity.ack()) # Set received (double v) time.sleep(0.5) self.toLower(PresenceProtocolEntity(name=name)) # Set name Presence time.sleep(0.5) self.toLower(AvailablePresenceProtocolEntity()) # Set online time.sleep(0.5) self.toLower(messageProtocolEntity.ack(True)) # Set read (double v blue) time.sleep(0.5) self.toLower( OutgoingChatstateProtocolEntity( OutgoingChatstateProtocolEntity.STATE_TYPING, Jid.normalize(messageProtocolEntity.getFrom(False)) ) ) # Set is writing time.sleep(1) self.toLower( OutgoingChatstateProtocolEntity( OutgoingChatstateProtocolEntity.STATE_PAUSED, Jid.normalize(messageProtocolEntity.getFrom(False)) ) ) # Set no is writing time.sleep(1) self.onTextMessage(messageProtocolEntity) # Send the answer time.sleep(1) self.toLower(UnavailablePresenceProtocolEntity()) # Set offline
def onIq(self, entity): self.lock.acquire() for alert in self.alertQueue: message = alert['alert_text'] messageEntity = TextMessageProtocolEntity(message, to = Jid.normalize(self.admin_phone)) ack_id = messageEntity.getId() self.ackQueue.append(ack_id) self.sentQueue[ack_id] = alert; print(alert) self.lock.release()
def onSuccess(self, successProtocolEntity): # self.lock.acquire() for target in self.getProp(self.__class__.PROP_MESSAGES, []): #getProp() is trying to retreive the list of (jid, message) tuples, if none exist, use the default [] phone, message = target messageEntity = TextMessageProtocolEntity(message, to = Jid.normalize(phone)) #append the id of message to ackQueue list #which the id of message will be deleted when ack is received. # self.ackQueue.append(messageEntity.getId()) self.toLower(messageEntity)
def handleEncNode(self, node): recipient_id = node["to"].split('@')[0] v2 = node["to"] if node.getChild("enc"): # media enc is only for v2 messsages if '-' in recipient_id: ## Handle Groups def getResultNodes(resultNode, requestEntity): groupInfo = InfoGroupsResultIqProtocolEntity.fromProtocolTreeNode( resultNode) jids = list(groupInfo.getParticipants().keys() ) #keys in py3 returns dict_keys jids.remove( self.getLayerInterface( YowAuthenticationProtocolLayer).getUsername(True)) jidsNoSession = [] for jid in jids: if not self.store.containsSession( jid.split('@')[0], 1): jidsNoSession.append(jid) if len(jidsNoSession): self.getKeysFor( jidsNoSession, lambda successJids, b: self. sendToGroupWithSessions(node, successJids)) else: self.sendToGroupWithSessions(node, jids) groupInfoIq = InfoGroupsIqProtocolEntity( Jid.normalize(node["to"])) self._sendIq(groupInfoIq, getResultNodes) else: messageData = self.serializeToProtobuf(node) if messageData: if not self.store.containsSession(recipient_id, 1): def on_get_keys(successJids, b): print(successJids) if len(successJids) == 1: self.sendToContact(node) else: self.toLower(node) self.getKeysFor([node["to"]], on_get_keys, lambda: self.toLower(node)) else: sessionCipher = self.getSessionCipher(recipient_id) messageData = messageData.SerializeToString( ) + self.getPadding() ciphertext = sessionCipher.encrypt(messageData) mediaType = node.getChild( "enc")["type"] if node.getChild("enc") else None encEntity = EncryptedMessageProtocolEntity( [ EncProtocolEntity( EncProtocolEntity.TYPE_MSG if ciphertext.__class__ == WhisperMessage else EncProtocolEntity.TYPE_PKMSG, 2 if v2 else 1, ciphertext.serialize(), mediaType) ], "text" if not mediaType else "media", _id=node["id"], to=node["to"], notify=node["notify"], timestamp=node["timestamp"], participant=node["participant"], offline=node["offline"], retry=node["retry"]) self.toLower(encEntity.toProtocolTreeNode()) else: # case of unserializable messages (audio, video) ? self.toLower(node) else: self.toLower(node)
def alarmHandler(): self.sendMsg("1pm Alarm!!", to=Jid.normalize('447760333610')) # set tomorrows alarm setAlarm()
def doSubscribe(self, numbers): for number in numbers: self.toLower(SubscribePresenceProtocolEntity( Jid.normalize(number))) time.sleep(0.1)
def media_send(self, number, path, mediaType, caption = None): jid = Jid.normalize(number) entity = RequestUploadIqProtocolEntity(mediaType, filePath=path) successFn = lambda successEntity, originalEntity: self.onRequestUploadResult(jid, mediaType, path, successEntity, originalEntity, caption) errorFn = lambda errorEntity, originalEntity: self.onRequestUploadError(jid, path, errorEntity, originalEntity) self._sendIq(entity, successFn, errorFn)
def start_typing(self, conversation): self.toLower( OutgoingChatstateProtocolEntity( OutgoingChatstateProtocolEntity.STATE_TYPING, Jid.normalize(conversation)))
def contact_picture_from(number, success_fn=None, preview=False): jid = Jid.normalize(number) contact_picture(jid, success_fn, preview)
def send_video_to(path, phone_number, caption=None): jid = Jid.normalize(phone_number) send_video(path, jid, caption)
def make_message(msg, conversation): outgoing_message_enity = TextMessageProtocolEntity( msg, to=Jid.normalize(conversation)) return outgoing_message_enity
def onMessage(self, messageProtocolEntity): try: if messageProtocolEntity.getType() == 'text': self.onTextMessage(messageProtocolEntity) elif messageProtocolEntity.getType() == 'media': self.onMediaMessage(messageProtocolEntity) #self.toLower(messageProtocolEntity.forward(messageProtocolEntity.getFrom())) self.toLower(messageProtocolEntity.ack()) self.toLower(messageProtocolEntity.ack(True)) phone = messageProtocolEntity.getFrom() messageBody = messageProtocolEntity.getBody() messageToBeSent = "" print phone print "**************"; print messageProtocolEntity.getNotify() if messageProtocolEntity.getType() == 'text': #if isQuizActive(Jid.normalize(phone)): # currentAnswer = getCurrentAnswer(Jid.normalize(phone)); # if currentAnswer == messageBody.lower(): # sender = messageProtocolEntity.getNotify(); # updateScore(Jid.normalize(phone), sender); # messageToBeSent = getScore(); # messageEntity = TextMessageProtocolEntity(messageToBeSent, to = Jid.normalize(phone)); # self.toLower(messageEntity); # updateQuestionCount(Jid.normalize(phone)); # if(wasLastQuestion): # messageToBeSent = getFinalMessage(Jid.normalize(phone)); # messageEntity = TextMessageProtocolEntity(messageToBeSent, to = Jid.normalize(phone)); # self.toLower(messageEntity); # else: # messageToBeSent = getQuestion(Jid.normalize(phone)); # messageEntity = TextMessageProtocolEntity(messageToBeSent, to = Jid.normalize(phone)); # self.toLower(messageEntity); # #if 'start quiz' in messageBody.lower(): # if(startQuiz(Jid.normalize(phone)) == True): # messageToBeSent = getIntroMessage(); # messageEntity = TextMessageProtocolEntity(messageToBeSent, to = Jid.normalize(phone)); # self.toLower(messageEntity) # #wait 30 seconds # messageToBeSent = getQuestion(); # messageEntity = TextMessageProtocolEntity(messageToBeSent, to = Jid.normalize(phone)); # self.toLower(messageEntity); # else: # messageToBeSent = "Quiz already in progress..."; # messageEntity = TextMessageProtocolEntity(messageToBeSent, to = Jid.normalize(phone)) # self.toLower(messageEntity) if 'happy' in messageBody.lower() or 'congrats' in messageBody.lower(): sendmessage = sendwish(messageBody) if sendmessage == True: self.toLower(messageProtocolEntity.forward(messageProtocolEntity.getFrom())) if 'meaning?' in messageBody.lower(): messageToBeSent = getmeaningfromapi(messageBody) messageEntity = TextMessageProtocolEntity(messageToBeSent, to = Jid.normalize(phone)) self.toLower(messageEntity) if '#' in messageBody.lower(): messageToBeSent = gettweetsfromapi(messageBody) messageEntity = TextMessageProtocolEntity(messageToBeSent, to = Jid.normalize(phone)) self.toLower(messageEntity) print (messageToBeSent) except Exception, e: print (e)
def aliasToJid(self, calias): return Jid.normalize(calias)
def aliasToJid(self, calias): for alias, ajid in self.jidAliases.items(): if calias.lower() == alias.lower(): return Jid.normalize(ajid) return Jid.normalize(calias)
def stop_typing(self, message_entity): self.toLower( OutgoingChatstateProtocolEntity( OutgoingChatstateProtocolEntity.STATE_PAUSED, Jid.normalize(message_entity.getFrom(False))))
def send_message_to(str_message, phone_number, disconnect_after=True): jid = Jid.normalize(phone_number) send_message(str_message, jid)
def onMessage(self, messageProtocolEntity): if messageProtocolEntity.getType() == 'text': time.sleep(0.5) self.toLower(messageProtocolEntity.ack()) #Set received (double v) time.sleep(0.5) self.toLower(PresenceProtocolEntity(name = name)) #Set name Presence time.sleep(0.5) self.toLower(AvailablePresenceProtocolEntity()) #Set online time.sleep(0.5) self.toLower(messageProtocolEntity.ack(True)) #Set read (double v blue) time.sleep(0.5) self.toLower(OutgoingChatstateProtocolEntity(OutgoingChatstateProtocolEntity.STATE_TYPING, Jid.normalize(messageProtocolEntity.getFrom(False)) )) #Set is writing time.sleep(1) self.toLower(OutgoingChatstateProtocolEntity(OutgoingChatstateProtocolEntity.STATE_PAUSED, Jid.normalize(messageProtocolEntity.getFrom(False)) )) #Set no is writing time.sleep(1) self.onTextMessage(messageProtocolEntity) #Send the answer time.sleep(1) self.toLower(UnavailablePresenceProtocolEntity()) #Set offline
def send_audio_to(path, phone_number): jid = Jid.normalize(phone_number) send_audio(path, jid)
def send_document_to(path, phone_number): jid = Jid.normalize(phone_number) send_document(path, jid)
def contact_status_from(number, fn=None): jid = Jid.normalize(number) contact_status(jid, fn)
def onMessage(self, messageProtocolEntity): if messageProtocolEntity.getType() == 'text': time.sleep(random.randrange(Cfg.RAND_MIN,Cfg.RAND_MAX)) #Devine mensagem como enviada self.toLower(messageProtocolEntity.ack()) time.sleep(random.randrange(Cfg.RAND_MIN,Cfg.RAND_MAX)) self.toLower(AvailablePresenceProtocolEntity()) time.sleep(random.randrange(Cfg.RAND_MIN,Cfg.RAND_MAX)) self.toLower(PresenceProtocolEntity(name = name)) time.sleep(random.randrange(Cfg.RAND_MIN,Cfg.RAND_MAX)) #Devine mensagem como visualisada self.toLower(messageProtocolEntity.ack(True)) time.sleep(random.randrange(Cfg.RAND_MIN,Cfg.RAND_MAX)) self.toLower(OutgoingChatstateProtocolEntity(OutgoingChatstateProtocolEntity.STATE_TYPING, Jid.normalize(messageProtocolEntity.getFrom(False))))#Set esta escribiendo time.sleep(random.randrange(Cfg.RAND_MIN,Cfg.RAND_MAX)) #Envia a resposta self.onTextMessage(messageProtocolEntity) time.sleep(random.randrange(Cfg.RAND_MIN,Cfg.RAND_MAX)) self.toLower(OutgoingChatstateProtocolEntity(OutgoingChatstateProtocolEntity.STATE_PAUSED, Jid.normalize(messageProtocolEntity.getFrom(False))))#Set pausa time.sleep(random.randrange(Cfg.RAND_MIN,Cfg.RAND_MAX)) #Fica offline self.toLower(UnavailablePresenceProtocolEntity()) elif messageProtocolEntity.getType() == 'media': time.sleep(random.randrange(Cfg.RAND_MIN,Cfg.RAND_MAX)) self.toLower(AvailablePresenceProtocolEntity()) time.sleep(random.randrange(Cfg.RAND_MIN,Cfg.RAND_MAX)) self.toLower(PresenceProtocolEntity(name = name))#Set presencia self.onMediaMessage(messageProtocolEntity) self.toLower(messageProtocolEntity.ack()) self.toLower(messageProtocolEntity.ack(True)) time.sleep(random.randrange(Cfg.RAND_MIN,Cfg.RAND_MAX)) self.toLower(UnavailablePresenceProtocolEntity())#Set offline else: pass
def stop_typing(self, conversation): self.toLower( OutgoingChatstateProtocolEntity( OutgoingChatstateProtocolEntity.STATE_PAUSED, Jid.normalize(conversation)))
def sendMsg(self, text, to=Jid.normalize('447760333610-1485190753')): logging.info('Sent %s to %s', text, to) messageEntity = TextMessageProtocolEntity(text, to=to) self.toLower(messageEntity)
def handleEncMessage(self, node): encMessageProtocolEntity = EncryptedMessageProtocolEntity(node) isGroup = node["participant"] is not None senderJid = node["participant"] if isGroup else node["from"] if node.getChild( "enc")["v"] == "2" and node["from"] not in self.v2Jids: self.v2Jids.append(node["from"]) try: if encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_PKMSG): self.handlePreKeyWhisperMessage(node) elif encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_MSG): self.handleWhisperMessage(node) if encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_SKMSG): self.handleSenderKeyMessage(node) except (InvalidMessageException, InvalidKeyIdException): logger.warning( "InvalidMessage or InvalidKeyIdException for %s, would to send a retry", Jid.denormalize(encMessageProtocolEntity.getAuthor())) if node["count"] is not None: logger.warning("This is the second retry forget it") return from yowsup.layers.axolotl.protocolentities.iq_key_get import GetKeysIqProtocolEntity logger.info("Trying GetKeys for %s, getting keys now", Jid.denormalize(encMessageProtocolEntity.getAuthor())) # entity = GetKeysIqProtocolEntity([Jid.denormalize(encMessageProtocolEntity.getAuthor())]) retry = RetryOutgoingReceiptProtocolEntity.fromMessageNode( node, self.store.getLocalRegistrationId()) self.toLower(retry.toProtocolTreeNode()) except NoSessionException: logger.warning( "No session for %s, getting their keys now", Jid.denormalize(encMessageProtocolEntity.getAuthor())) conversationIdentifier = (node["from"], node["participant"]) if conversationIdentifier not in self.pendingIncomingMessages: self.pendingIncomingMessages[conversationIdentifier] = [] self.pendingIncomingMessages[conversationIdentifier].append(node) def successFn(successJids, _): return self.processPendingIncomingMessages( *conversationIdentifier) if len(successJids) else None self.getKeysFor([senderJid], successFn) except DuplicateMessageException: logger.warning( "Received a message that we've previously decrypted, goint to send the delivery receipt myself" ) self.toLower( OutgoingReceiptProtocolEntity( node["id"], node["from"], participant=node["participant"]).toProtocolTreeNode()) except UntrustedIdentityException as e: if self.getProp(PROP_IDENTITY_AUTOTRUST, False): logger.warning("Autotrusting identity for %s", e.getName()) self.store.saveIdentity(e.getName(), e.getIdentityKey()) return self.handleEncMessage(node) else: logger.error("Ignoring message with untrusted identity")