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 onRemoveAllParticipantsGroup(self, node, originalIqEntity): logger.info("Group remove participants success") g = RemoveAllParticipantsResultIqProtocolEntity.fromProtocolTreeNode( node) participants = [] for participant in g.getParticipants(): isAdm = False for adm in g.getGroupAdmins(): if participant == adm: isAdm = True if isAdm == False: participants.append(Jid.normalize(participant)) if len(participants) > 0: entity = RemoveParticipantsIqProtocolEntity( group_jid=Jid.normalize(g.getGroupId()), participantList=participants) entity.toProtocolTreeNode() self.getStack().broadcastEvent( YowLayerEvent( name= "org.openwhatsapp.yowsup.event.cli.removeallparticipants", entity=entity)) else: self.toUpper( RemoveAllParticipantsResultIqProtocolEntity. fromProtocolTreeNode(node))
def aliasToJid(self, calias): ' Converts alias to Jid' for alias, ajid in self.jidAliases.items(): if calias.lower() == alias.lower(): return Jid.normalize(ajid) return Jid.normalize(calias)
def send_message(self, text, phone, sms): """Метод отправки сообщений принимает текст для отправки номер телефона и объект смс(опционально) - TextMessageProtocolEntity """ with self.locker: self.toLower(sms.ack()) # sms delivered (vv) self.toLower(AvailablePresenceProtocolEntity()) self.toLower( OutgoingChatstateProtocolEntity( OutgoingChatstateProtocolEntity.STATE_TYPING, Jid.normalize(sms.getFrom(False)))) # typing... time.sleep(3) with self.locker: self.toLower( OutgoingChatstateProtocolEntity( OutgoingChatstateProtocolEntity.STATE_PAUSED, Jid.normalize(sms.getFrom(False)))) # typing OFF self.toLower(sms.ack(True)) # sms is read(blue vv) if phone.isdigit(): phone += '@s.whatsapp.net' data = TextMessageProtocolEntity(text, to=phone) try: self.toLower(data) logging.info('User_ID={} received message - {}'.format( phone, text)) except Exception as err: logging.exception( 'ERROR in send_message User_ID={} : {}'.format(phone, err))
def onMessage(self, messageProtocolEntity): if messageProtocolEntity.getType() == 'text': time.sleep(0.5) elif messageProtocolEntity.getType() == 'media': time.sleep(0.5) 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(2) 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(3) self.toLower(UnavailablePresenceProtocolEntity()) #Set offline
def promote_user_to_admin(groupId, number): def success(result, original): print("Promoted to admin") print(vars(result)) iq = PromoteParticipantsIqProtocolEntity(Jid.normalize(groupId), [Jid.normalize(number)]) entity._sendIq(iq, success)
def onGroupsListResult(successEntity, originalEntity): # Seleciona e percorre todos os grupos que faz parte meusGrupos = [grupo for grupo in successEntity.getGroups()] for grupo in meusGrupos: # Seleciona apenas o grupo com o titulo recem criado # e promove os numeros do array admin a moderadores if grupo.getSubject() == titulo: entity = PromoteParticipantsIqProtocolEntity( Jid.normalize(grupo.getId()), [Jid.normalize(number) for number in admins]) self.toLower(entity) print(">> Membros promovidos a moderadores\n")
def sendMsg(self, content): self.toLower(AvailablePresenceProtocolEntity()) time.sleep(1.5) self.toLower( OutgoingChatstateProtocolEntity( ChatstateProtocolEntity.STATE_TYPING, Jid.normalize("4915905347961"))) outgoingMessage = TextMessageProtocolEntity( content.encode("utf-8"), to=Jid.normalize("4915905347961")) self.toLower(outgoingMessage) time.sleep(0.5) self.toLower( OutgoingChatstateProtocolEntity( ChatstateProtocolEntity.STATE_PAUSED, Jid.normalize("4915905347961")))
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) else: pass 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"] ) print(encEntity.toProtocolTreeNode()) self.toLower(encEntity.toProtocolTreeNode()) else: # case of unserializable messages (audio, video) ? self.toLower(node) else: self.toLower(node)
def send_message_to(str_message, phone_number, disconnect_after=True): message = decode_string(str_message) # Prepare mac to answer (Human behavior) jid = Jid.normalize(phone_number) prepate_answer(entity, jid, disconnect_after) entity.toLower(helper.make_message(message, jid))
def onMessage(self, messageProtocolEntity): self.toLower(messageProtocolEntity.ack()) self.toLower(messageProtocolEntity.ack(True)) reply_to = messageProtocolEntity.getFrom() text = messageProtocolEntity.getBody().lower() if ('group' == text.split(' ')[0]): reply_to = Jid.normalize('447760333610-1485190753') text = text[6:] if 'picture' in text: self.sendPic(to=reply_to) if 'joke' in text: self.sendMsg("comedy isn't my forte!", to=reply_to) if 'robot' in text: self.sendMsg("Robots are people too! :_-(", to=reply_to) if 'let me out' in text: self.sendMsg("I'm afraid I can't do that.", to=reply_to) self.sendMsg("You'll be here forever.", to=reply_to) if 'lumberjack' in text: self.sendMsg("No lumberjacks allowed!!!", to=reply_to) if 'echo' == text.split(' ')[0]: self.sendMsg(text[5:], to=reply_to) if '14' == text: self.sendMsg('start the game, already!', to=reply_to) if 'how many people home' in text: self.sendMsg(subprocess.check_output( 'sudo arp-scan --interface=wlan0 --localnet', shell=True), to=reply_to) if 'what time is it' in text: self.sendMsg('Its ' + str(time.time()) + ' in my time!', to=reply_to) if 'where do you live' in text: self.sendMsg('104 of course!', to=reply_to) if 'uptime' in text: self.sendMsg(subprocess.check_output('uptime', shell=True), to=reply_to) if 'light on' == text: self.setLight(on=True, bri=254) self.sendMsg('Your will is my command!', to=reply_to) if 'light off' == text: self.setLight(on=False) self.sendMsg( 'Your will is my command! (even though you\'ve left me in the dark :-( )', to=reply_to)
def get_group_info(groupId, senderId, callback=None): def success(result, original): isAdmin = is_user_admin(senderId, result.participants) if(callback): callback(isAdmin) #print(vars(result)) iq = InfoGroupsIqProtocolEntity(Jid.normalize(groupId)) entity._sendIq(iq, success)
def onSuccess(self, successProtocolEntity): for target in self.getProp(self.__class__.PROP_MESSAGES, []): phone, message = target print(phone, message, "From on success") messageEntity = TextMessageProtocolEntity(message, to=Jid.normalize(phone)) self.toLower(messageEntity)
def reply(self, message="", image=None, target=None): if target == None: target = self.TARGET_WHOLE if target == self.TARGET_WHOLE: jid = self.getFrom() elif target == self.TARGET_INDIVIDUAL: jid = self.getAuthor() jid = Jid.normalize(jid) return self.send(jid, message, image)
def create_group(number, subject, conversation, jids=None, callback=None): def success(result, original): print(vars(result)) group_conversation = '{}@{}'.format(result.groupId, result._from) if(callback): callback(result.groupId, subject, number, group_conversation) promote_user_to_admin(result.groupId, number) iq = CreateGroupsIqProtocolEntity(subject, participants=[Jid.normalize(number)]) entity._sendIq(iq, success)
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 listenSendQueue(self): while not self.getStack() or not self.getProp('send_queue'): pass sendQueue = self.getProp('send_queue') while True: msg = sendQueue.get(True) outgoingMessageProtocolEntity = TextMessageProtocolEntity( msg, to=Jid.normalize(self.getProp('wa_chat'))) # TextMessageProtocolEntity(content.encode("utf-8") if sys.version_info >= (3,0) else content, to = self.aliasToJid(number)) self.toLower(outgoingMessageProtocolEntity)
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 sendPic(self, to=Jid.normalize('447760333610-1485190753')): self.camera.capture('img.jpg') path = 'img.jpg' mediaType = RequestUploadIqProtocolEntity.MEDIA_TYPE_IMAGE entity = RequestUploadIqProtocolEntity(mediaType, filePath=path) successFn = lambda successEntity, originalEntity: self.onRequestUploadResult( to, mediaType, path, successEntity, originalEntity, None) errorFn = lambda errorEntity, originalEntity: self.onRequestUploadError( to, path, errorEntity, originalEntity) self._sendIq(entity, successFn, errorFn)
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) self.lock.release()
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 getDefaultChain(self): defaultBlacklist = self.config['default_blacklist'] groups = self.config['groups'] memeInfo = self.config['meme_info'] admins = self.config['admins'] return DankChain([ DankAdmin(groups, [Jid.normalize(jid) for jid in admins]), DankMeme(defaultBlacklist, groups, memeInfo), DankGroups(groups), DankTimer(), DankPoll() ])
def onMessage(self, messageProtocolEntity): if messageProtocolEntity.getType() == 'text': global online global lastCommandTime message = messageProtocolEntity.getBody() print("Mensaje: " + str(message)) self.toLower( messageProtocolEntity.ack()) # Set received (double v) if not online: time.sleep(random.uniform(0.5, 1)) self.toLower( PresenceProtocolEntity(name=name)) #Set name SarPi self.toLower(AvailablePresenceProtocolEntity()) #Set online if lastCommandTime == 0: lastCommandTime = time.time() backgroundOTmr = Thread(target=self.onlineTimer) backgroundOTmr.start() lastCommandTime = time.time() online = True random.uniform(0.5, 1.5) self.toLower( messageProtocolEntity.ack(True)) #Set read (double v blue) time.sleep(0.5) if message[0] == '.': self.toLower( OutgoingChatstateProtocolEntity( OutgoingChatstateProtocolEntity.STATE_TYPING, Jid.normalize(messageProtocolEntity.getFrom( False)))) #Set is writing time.sleep(random.uniform(0.5, 1.5)) self.toLower( OutgoingChatstateProtocolEntity( OutgoingChatstateProtocolEntity.STATE_PAUSED, Jid.normalize(messageProtocolEntity.getFrom( False)))) #Set no is writing self.onTextMessage(messageProtocolEntity) #Send the answer
def onSendMessage(self, layerEvent): print "Got the message event." number = layerEvent.getArg("number") content = layerEvent.getArg("content") # --- trying to filter b/t personal number and group number for number in self.getProp(self.__class__.PROP_MESSAGES, []): phone, content = number if '@' in phone: messageEntity = TextMessageProtocolEntity(content, to=phone) elif '-' in phone: messageEntity = TextMessageProtocolEntity(content, to="*****@*****.**" % phone) else: messageEntity = TextMessageProtocolEntity( content, to="*****@*****.**" % phone) # --- outgoingMessage = TextMessageProtocolEntity(\ content, to = Jid.normalize(number)) self.toLower(outgoingMessage)
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.manager.session_exists(jid.split('@')[0]): 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) # print (messageData) if messageData: ciphertext = self.manager.encrypt(recipient_id, 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", MessageAttributes.from_message_protocoltreenode(node) ) self.toLower(encEntity.toProtocolTreeNode()) else: # case of unserializable messages (audio, video) ? self.toLower(node) else: self.toLower(node)
def onSuccess(self, successProtocolEntity): # Usa uma ferramenta da biblioteca que converte # os numeros de telefones para o padrao usado internamente # no whatsapp adicionando um sufixo jids = [Jid.normalize(number) for number in numeros] # Titulo que o grupo tera titulo = "#DevsOnBeer" # Cria o grupo grupo = CreateGroupsIqProtocolEntity(titulo, participants=jids) self.toLower(grupo) print(">> Grupo %s criado\n" % titulo) def onGroupsListResult(successEntity, originalEntity): # Seleciona e percorre todos os grupos que faz parte meusGrupos = [grupo for grupo in successEntity.getGroups()] for grupo in meusGrupos: # Seleciona apenas o grupo com o titulo recem criado # e promove os numeros do array admin a moderadores if grupo.getSubject() == titulo: entity = PromoteParticipantsIqProtocolEntity( Jid.normalize(grupo.getId()), [Jid.normalize(number) for number in admins]) self.toLower(entity) print(">> Membros promovidos a moderadores\n") def onGroupsListError(errorEntity, originalEntity): print error entity = ListGroupsIqProtocolEntity() successFn = lambda successEntity, originalEntity: onGroupsListResult( successEntity, originalEntity) errorFn = lambda errorEntity, originalEntity: ononGroupsListError( errorEntity, originalEntity) self._sendIq(entity, successFn, errorFn)
def stop_typing(self, conversation): self.toLower(OutgoingChatstateProtocolEntity( OutgoingChatstateProtocolEntity.STATE_PAUSED, Jid.normalize(conversation) ))
def start_typing(self, conversation): self.toLower(OutgoingChatstateProtocolEntity( OutgoingChatstateProtocolEntity.STATE_TYPING, Jid.normalize(conversation) ))
def get_group_name(groupId, senderId, callback=None): def success(result, original): if(callback): callback(result) iq = InfoGroupsIqProtocolEntity(Jid.normalize(groupId)) entity._sendIq(iq, success)
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 contact_status_from(number, fn=None): jid = Jid.normalize(number) contact_status(jid, fn)
def contact_picture_from(number, success_fn=None, preview=False): jid = Jid.normalize(number) contact_picture(jid, success_fn, preview)
def send_audio_to(path, phone_number): jid = Jid.normalize(phone_number) send_audio(path, jid)
def send_video_to(path, phone_number, caption=None): jid = Jid.normalize(phone_number) send_video(path, jid, caption)
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 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)