Exemplo n.º 1
0
    def onMessage(self, messageProtocolEntity):
        is_admin = 0
        global send_next
        send_next_ = send_next
        admin_number = '*****@*****.**'
        message = 'Whatsbot'
        Demo_Message = "*WhatsBot*: \nSend Whatsapp messages by chatting with our WhatsBot."
        receipt = OutgoingReceiptProtocolEntity(
            messageProtocolEntity.getId(), messageProtocolEntity.getFrom(),
            'read', messageProtocolEntity.getParticipant())
        time.sleep(0.5)
        self.toLower(receipt)
        print("Message from " + messageProtocolEntity.getFrom())
        if (messageProtocolEntity.getFrom() == (admin_number)):
            print("IS admin number")
            if send_next_ == 1:
                list_cont = {'919417290392', '917508377911'}
                if messageProtocolEntity.getType() == 'text':
                    try:
                        if ((messageProtocolEntity.getBody()
                             ).index('WhatsBot --end') == 0):
                            send_next = 0
                            print("Sending Disabled")
                        else:
                            print("Sending Message")
                    except:
                        for contact_member in list_cont:
                            entity = OutgoingChatstateProtocolEntity(
                                ChatstateProtocolEntity.STATE_TYPING,
                                contact_member + '@s.whatsapp.net')
                            self.toLower(entity)
                            self.toLower(
                                messageProtocolEntity.forward(
                                    contact_member + '@s.whatsapp.net'))
                            print("Sending to :", contact_member)

                else:
                    print("Is media")
                    #for contact_member in list_cont:
                    #self.toLower(messageProtocolEntity.forward(contact_member+'@s.whatsapp.net'))
                    #print ("Sending to :", contact_member)

            if messageProtocolEntity.getType() == 'text':
                print("Is Text")
                message = messageProtocolEntity.getBody()
                try:
                    if ((messageProtocolEntity.getBody()
                         ).index('WhatsBot --send') == 0):
                        send_next = 1
                        print("Send Next ")
                except:
                    print("Message Passed")

        else:
            outgoingMessageProtocolEntity = TextMessageProtocolEntity(
                Demo_Message, to=messageProtocolEntity.getFrom())
            self.toLower(outgoingMessageProtocolEntity)
Exemplo n.º 2
0
    def onMessage(self, messageProtocolEntity):
        if messageProtocolEntity.getType() == 'text':
            recv_msg.append((messageProtocolEntity.getFrom(),
                             messageProtocolEntity.getBody()))

        #send receipt otherwise we keep receiving the same message over and over
        receipt = OutgoingReceiptProtocolEntity(
            messageProtocolEntity.getId(), messageProtocolEntity.getFrom())
        self.toLower(receipt)
Exemplo n.º 3
0
    def handleEncMessage(self, node):
        encMessageProtocolEntity = EncryptedMessageProtocolEntity.fromProtocolTreeNode(
            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 as e:
            logger.error('InvalidMessageException %s' % e)
            # DEBUG SET RECEIPT
            # self.toLower(OutgoingReceiptProtocolEntity(node["id"], node["from"], 'read', participant=node["participant"]).toProtocolTreeNode())

        except InvalidKeyIdException as e:
            logger.warning("InvalidKeyId for %s, going to send a retry",
                           encMessageProtocolEntity.getAuthor(False))
            retry = RetryOutgoingReceiptProtocolEntity.fromMessageNode(
                node, self.store.getLocalRegistrationId())
            self.toLower(retry.toProtocolTreeNode())
        except NoSessionException as e:
            logger.warning("No session for %s, getting their keys now",
                           encMessageProtocolEntity.getAuthor(False))

            conversationIdentifier = (node["from"], node["participant"])

            if conversationIdentifier not in self.pendingIncomingMessages:
                self.pendingIncomingMessages[conversationIdentifier] = []
            self.pendingIncomingMessages[conversationIdentifier].append(node)

            successFn = lambda successJids, b: self.processPendingIncomingMessages(
                *conversationIdentifier) if len(successJids) else None

            self.getKeysFor([senderJid], successFn)

        except DuplicateMessageException as e:
            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")
Exemplo n.º 4
0
    def onText(self, messageProtocolEntity):
        if not messageProtocolEntity.isGroupMessage():
            receipt = OutgoingReceiptProtocolEntity(
                messageProtocolEntity.getId(), messageProtocolEntity.getFrom())
            self.toLower(receipt)

            #registrar mensagem recebida no BD
            username = self.getStack().getProp(
                YowAuthenticationProtocolLayer.PROP_CREDENTIALS)[0]
            jid = messageProtocolEntity.getFrom()

            cnx = mysql.connector.connect(user='******',
                                          password='',
                                          database='zapserver',
                                          use_unicode=True)

            cursor = cnx.cursor()
            cursor.execute('SET NAMES utf8mb4')
            cursor.execute("SET CHARACTER SET utf8mb4")
            cursor.execute("SET character_set_connection=utf8mb4")

            cursor.execute(
                "insert into Queue(jidServer, jidClient, url, message, extension, imageLabel, status, dateTime) "
                "values (%s,%s,%s,convert (%s using utf8mb4),'txt','',%s,%s)",
                [
                    username,
                    jid.split('@')[0],
                    jid.split('@')[1],
                    messageProtocolEntity.getBody(), "R",
                    datetime.datetime.now()
                ])

            cursor.execute(
                "insert into Log(jidServer, jidClient, url, message, extension, status, dateTime)"
                "values (%s,%s,%s,convert (%s using utf8mb4),'txt',%s,%s)", [
                    username,
                    jid.split('@')[0],
                    jid.split('@')[1],
                    messageProtocolEntity.getBody(), "R",
                    datetime.datetime.now()
                ])

            cnx.commit()

            cursor.close()
            cnx.close()

            print("Text %s received from %s" %
                  (messageProtocolEntity.getBody(),
                   messageProtocolEntity.getFrom(False)))

            f = open(username + ".log", 'a')
            f.write(
                jid.split('@')[0] + ": " + messageProtocolEntity.getBody() +
                " (" + str(datetime.datetime.now()) + ")\n")
            f.close()
Exemplo n.º 5
0
    def onTextMessage(self, mEntity):
        print("Echoing %s to %s" % (mEntity.getBody(), mEntity.getFrom(False)))
        receipt = OutgoingReceiptProtocolEntity(mEntity.getId(),
                                                mEntity.getFrom())
        src = mEntity.getFrom()
        print("<= WhatsApp: <- %s Message" % (src))

        content = mEntity.getBody()
        self.sendEmail(mEntity, content, content)
        self.toLower(receipt)
Exemplo n.º 6
0
    def respond(self, messageProtocolEntity, msg):
        receipt = OutgoingReceiptProtocolEntity(
            messageProtocolEntity.getId(), messageProtocolEntity.getFrom(),
            'read', messageProtocolEntity.getParticipant())

        outgoingMessageProtocolEntity = TextMessageProtocolEntity(
            msg, to=messageProtocolEntity.getFrom())

        self.toLower(receipt)
        self.toLower(outgoingMessageProtocolEntity)
Exemplo n.º 7
0
    def onMessage(self, messageProtocolEntity):
        if not messageProtocolEntity.isGroupMessage():
            if messageProtocolEntity.getType() == 'text':
                self.onTextMessage(messageProtocolEntity)
            elif messageProtocolEntity.getType() == 'media':
                self.onMediaMessage(messageProtocolEntity)

        receipt = OutgoingReceiptProtocolEntity(
            messageProtocolEntity.getId(), messageProtocolEntity.getFrom())
        #send receipt otherwise we keep receiving the same message over and over
        self.toLower(receipt)
Exemplo n.º 8
0
    def onMessage(self, messageProtocolEntity):
        receipt = OutgoingReceiptProtocolEntity(
            messageProtocolEntity.getId(), messageProtocolEntity.getFrom(),
            'read', messageProtocolEntity.getParticipant())

        outgoingMessageProtocolEntity = TextMessageProtocolEntity(
            messageProtocolEntity.getBody(),
            to=messageProtocolEntity.getFrom())

        self.toLower(receipt)
        self.toLower(outgoingMessageProtocolEntity)
Exemplo n.º 9
0
    def onTextMessage(self, mEntity):
        receipt = OutgoingReceiptProtocolEntity(mEntity.getId(),
                                                mEntity.getFrom())

        src = mEntity.getFrom()
        print("<= WhatsApp: <- %s Message" % (src))

        content = mEntity.getBody()
        self.sendEmail(mEntity, content, content)
        if not args.dry:
            self.toLower(receipt)
Exemplo n.º 10
0
 def onMessage(self, messageProtocolEntity):
     if True:
         self.toLower(
             OutgoingReceiptProtocolEntity(
                 messageProtocolEntity.getId(),
                 messageProtocolEntity.getFrom(), 'read',
                 messageProtocolEntity.getParticipant()))
         self.toLower(
             TextMessageProtocolEntity(c.input(
                 self.out(messageProtocolEntity)),
                                       to=messageProtocolEntity.getFrom()))
Exemplo n.º 11
0
 def onMessage(self, messageProtocolEntity):
     #send receipt otherwise we keep receiving the same message over and over
     
     if True:
         receipt = OutgoingReceiptProtocolEntity(messageProtocolEntity.getId(), messageProtocolEntity.getFrom(), 'read', messageProtocolEntity.getParticipant())
         
         outgoingMessageProtocolEntity = TextMessageProtocolEntity(
             messageProtocolEntity.getBody(),
             to = messageProtocolEntity.getFrom())
         
         self.toLower(receipt)
         self.toLower(outgoingMessageProtocolEntity)
Exemplo n.º 12
0
    def onTextMessage(self, messageProtocolEntity):
        receipt = OutgoingReceiptProtocolEntity(
            messageProtocolEntity.getId(), messageProtocolEntity.getFrom())
        self.toLower(receipt)
        line = [
            messageProtocolEntity.getFrom(), '=',
            messageProtocolEntity.getBody()
        ]

        if not hasattr(ListenLayer, 'queue'):
            raise NonQueueException()
        ListenLayer.queue.put(line)
Exemplo n.º 13
0
    def onMessage(self, messageProtocolEntity):
        #send receipt otherwise we keep receiving the same message over and over
        logger.info("Received Message: ID {}  From {}  Body {}".format(
            messageProtocolEntity._id, messageProtocolEntity._from,
            messageProtocolEntity.body))

        logger.info("Sending Receipt")
        receipt = OutgoingReceiptProtocolEntity(
            messageProtocolEntity.getId(), messageProtocolEntity.getFrom())
        self.toLower(receipt)
        self._plugin.message_received(messageProtocolEntity.getBody(),
                                      messageProtocolEntity.getFrom())
Exemplo n.º 14
0
    def parseAndHandleMessageProto(self, encMessageProtocolEntity,
                                   serializedData):
        node = encMessageProtocolEntity.toProtocolTreeNode()
        m = Message()
        handled = False
        try:
            m.ParseFromString(serializedData)
        except:
            print("DUMP:")
            print(serializedData)
            print([s for s in serializedData])
            print([ord(s) for s in serializedData])
            raise
        if not m or not serializedData:
            raise ValueError("Empty message")

        if m.HasField("sender_key_distribution_message"):
            handled = True
            axolotlAddress = AxolotlAddress(
                encMessageProtocolEntity.getParticipant(False), 0)
            self.handleSenderKeyDistributionMessage(
                m.sender_key_distribution_message, axolotlAddress)

        if m.HasField("conversation"):
            handled = True
            self.handleConversationMessage(node, m.conversation)
        elif m.HasField("contact_message"):
            handled = True
            self.handleContactMessage(node, m.contact_message)
        elif m.HasField("url_message"):
            handled = True
            self.handleUrlMessage(node, m.url_message)
        elif m.HasField("location_message"):
            handled = True
            self.handleLocationMessage(node, m.location_message)
        elif m.HasField("image_message"):
            handled = True
            self.handleImageMessage(node, m.image_message)
        elif m.HasField("document_message"):
            handled = True
            self.handleDocumentMessage(node, m.document_message)
        elif m.HasField("video_message"):
            handled = True
            self.handleVideoMessage(node, m.video_message)
        elif m.HasField("audio_message"):
            handled = True
            self.handleAudioMessage(node, m.audio_message)
        if not handled:
            logging.warning("Unhandled Message Type")
            self.toLower(
                OutgoingReceiptProtocolEntity(
                    node["id"], node["from"],
                    participant=node["participant"]).toProtocolTreeNode())
Exemplo n.º 15
0
 def recvCall(self, node):
     entity = CallProtocolEntity.fromProtocolTreeNode(node)
     if entity.getType() == "offer":
         receipt = OutgoingReceiptProtocolEntity(node["id"],
                                                 node["from"],
                                                 callId=entity.getCallId())
         self.toLower(receipt.toProtocolTreeNode())
     else:
         ack = OutgoingAckProtocolEntity(node["id"], "call", None,
                                         node["from"])
         self.toLower(ack.toProtocolTreeNode())
     self.toUpper(entity)
Exemplo n.º 16
0
    def onMessage(self, messageProtocolEntity):
        print "[WA]: chat_id=%s, from=%s, nick=%s, text=%s" % (
            messageProtocolEntity.getFrom(), messageProtocolEntity.getAuthor(),
            messageProtocolEntity.getNotify(), messageProtocolEntity.getBody())
        # import ipdb; ipdb.set_trace()
        receipt = OutgoingReceiptProtocolEntity(messageProtocolEntity.getId(), messageProtocolEntity.getFrom(), \
                                                'read', messageProtocolEntity.getParticipant())

        self.toLower(receipt)
        tg_message = "[%s][%s] %s" % (messageProtocolEntity.getFrom(),
                                      messageProtocolEntity.getNotify(),
                                      messageProtocolEntity.getBody())
        self.getProp('telegram').sendMessage(chat_id=tg_chat, text=tg_message)
Exemplo n.º 17
0
    def onMessage(self, inmessageProtocolEntity):
        #send receipt otherwise we keep receiving the same message over and over

        if True:
            receipt = OutgoingReceiptProtocolEntity(inmessageProtocolEntity.getId(), inmessageProtocolEntity.getFrom(),
                                                    'read', inmessageProtocolEntity.getParticipant())

            mediaobj=mediaview(self)

            if inmessageProtocolEntity.getType()=='text':
                threading.Thread(target=self.handle_callback, args=(mediaobj.callback,inmessageProtocolEntity)).start()

            self.toLower(receipt)
Exemplo n.º 18
0
 def sendMsg(self, messageProtocolEntity, message):
     receipt = OutgoingReceiptProtocolEntity(
         messageProtocolEntity.getId(), messageProtocolEntity.getFrom(),
         'read', messageProtocolEntity.getParticipant())
     if message == "":
         outgoingMessageProtocolEntity = TextMessageProtocolEntity(
             "Welcome to hacker news bot, try sending *_hn_* for *hacker-news for the day*\n To search hackernews try sending *_hn<space><search-keyword>_*",
             to=messageProtocolEntity.getFrom())
     else:
         outgoingMessageProtocolEntity = TextMessageProtocolEntity(
             message, to=messageProtocolEntity.getFrom())
     self.toLower(receipt)
     self.toLower(outgoingMessageProtocolEntity)
Exemplo n.º 19
0
 def sendMsg(self,messageProtocolEntity,message):
     receipt = OutgoingReceiptProtocolEntity(messageProtocolEntity.getId(),
      messageProtocolEntity.getFrom(), 'read', messageProtocolEntity.getParticipant())
     if message=="":
         outgoingMessageProtocolEntity = TextMessageProtocolEntity(
             "Welcome to hacker news bot, try sending *_hn_* for *hacker-news for the day*\n To search hackernews try sending *_hn<space><search-keyword>_* \n\nOn another note, search Kerala beverages for all available brands and prices \n *bevco<space><brand-name/type>* 😉🍻🍻 \n ex:\n 1. *hn* \n 2. *hn javascript* \n 3. *bevco beer* \n 4. *bevco 8 pm*",
             to = messageProtocolEntity.getFrom())
     else:
         outgoingMessageProtocolEntity = TextMessageProtocolEntity(
                 message,
             to = messageProtocolEntity.getFrom())
     self.toLower(receipt)
     self.toLower(outgoingMessageProtocolEntity)
Exemplo n.º 20
0
    def onMediaMessage(self, messageProtocolEntity):
        if messageProtocolEntity.getMediaType() == "image":
            
            receipt = OutgoingReceiptProtocolEntity(messageProtocolEntity.getId(), messageProtocolEntity.getFrom())

            outImage = ImageDownloadableMediaMessageProtocolEntity(
                messageProtocolEntity.getMimeType(), messageProtocolEntity.fileHash, messageProtocolEntity.url, messageProtocolEntity.ip,
                messageProtocolEntity.size, messageProtocolEntity.fileName, messageProtocolEntity.encoding, messageProtocolEntity.width, messageProtocolEntity.height,
                messageProtocolEntity.getCaption(),
                to = messageProtocolEntity.getFrom(), preview = messageProtocolEntity.getPreview())

            print("Echoing image %s to %s" % (messageProtocolEntity.url, messageProtocolEntity.getFrom(False)))

            #send receipt otherwise we keep receiving the same message over and over
            self.toLower(receipt)
            self.toLower(outImage)

        elif messageProtocolEntity.getMediaType() == "location":

            receipt = OutgoingReceiptProtocolEntity(messageProtocolEntity.getId(), messageProtocolEntity.getFrom())

            outLocation = LocationMediaMessageProtocolEntity(messageProtocolEntity.getLatitude(),
                messageProtocolEntity.getLongitude(), messageProtocolEntity.getLocationName(),
                messageProtocolEntity.getLocationURL(), messageProtocolEntity.encoding,
                to = messageProtocolEntity.getFrom(), preview=messageProtocolEntity.getPreview())

            print("Echoing location (%s, %s) to %s" % (messageProtocolEntity.getLatitude(), messageProtocolEntity.getLongitude(), messageProtocolEntity.getFrom(False)))

            #send receipt otherwise we keep receiving the same message over and over
            self.toLower(outLocation)
            self.toLower(receipt)
        elif messageProtocolEntity.getMediaType() == "vcard":
            receipt = OutgoingReceiptProtocolEntity(messageProtocolEntity.getId(), messageProtocolEntity.getFrom())
            outVcard = VCardMediaMessageProtocolEntity(messageProtocolEntity.getName(),messageProtocolEntity.getCardData(),to = messageProtocolEntity.getFrom())
            print("Echoing vcard (%s, %s) to %s" % (messageProtocolEntity.getName(), messageProtocolEntity.getCardData(), messageProtocolEntity.getFrom(False)))
            #send receipt otherwise we keep receiving the same message over and over
            self.toLower(outVcard)
            self.toLower(receipt)
Exemplo n.º 21
0
 def onMessage(self, messageProtocolEntity):
     receipt = OutgoingReceiptProtocolEntity(
         messageProtocolEntity.getId(), messageProtocolEntity.getFrom(),
         'read', messageProtocolEntity.getParticipant())
     #outgoingMessageProtocolEntity = TextMessageProtocolEntity(
     #    "Your message was: " + messageProtocolEntity.getBody(),
     #    to = messageProtocolEntity.getFrom())
     #logging.info(messageProtocolEntity.getFrom() + ":" + messageProtocolEntity.getBody())
     #print(messageProtocolEntity.getFrom() + ":" + messageProtocolEntity.getBody())
     print("msg from: " + messageProtocolEntity.getFrom())
     self.toLower(receipt)
     #self.toLower(outgoingMessageProtocolEntity)
     self.toLower(
         SubscribePresenceProtocolEntity(messageProtocolEntity.getFrom()))
Exemplo n.º 22
0
    def onTextMessage(self, messageProtocolEntity):
        receipt = OutgoingReceiptProtocolEntity(
            messageProtocolEntity.getId(), messageProtocolEntity.getFrom())

        outgoingMessageProtocolEntity = TextMessageProtocolEntity(
            messageProtocolEntity.getBody(),
            to=messageProtocolEntity.getFrom())

        print("Echoing %s to %s" % (messageProtocolEntity.getBody(),
                                    messageProtocolEntity.getFrom(False)))

        #send receipt otherwise we keep receiving the same message over and over
        self.toLower(receipt)
        self.toLower(outgoingMessageProtocolEntity)
Exemplo n.º 23
0
    def onMessage(self, msgProtocolEntity):
        """Called when received a message."""
        rcp = OutgoingReceiptProtocolEntity(msgProtocolEntity.getId(),
                                            msgProtocolEntity.getFrom(),
                                            'read',
                                            msgProtocolEntity.getParticipant())

        outgoingMessageProtocolEntity = TextMessageProtocolEntity(
            msgProtocolEntity.getBody(),
            to=msgProtocolEntity.getFrom())

        print(msgProtocolEntity.getBody())
        print(msgProtocolEntity.getFrom())
        self.toLower(rcp)
Exemplo n.º 24
0
    def onMessage(self, messageProtocolEntity):
        #responses =  [{ 'responseText' : 'responsetext'}, {'responseText' : 'responsetext'} ]
        responses = self.responseBuilder.getResponsesForMessage(
            messageProtocolEntity)

        for response in responses:
            outgoingMessageProtocolEntity = TextMessageProtocolEntity(
                response['responseText'], to=messageProtocolEntity.getFrom())
            self.toLower(outgoingMessageProtocolEntity)

        receipt = OutgoingReceiptProtocolEntity(
            messageProtocolEntity.getId(), messageProtocolEntity.getFrom(),
            'read', messageProtocolEntity.getParticipant())
        self.toLower(receipt)
Exemplo n.º 25
0
    def onMessage(self, messageProtocolEntity):

        # print("%s: %s" % (messageProtocolEntity.getFrom(), messageProtocolEntity.getBody()))

        if messageProtocolEntity.getType() == 'text':
            recv_msg.append((messageProtocolEntity.getFrom(),
                             messageProtocolEntity.getBody()))

        if True:
            receipt = OutgoingReceiptProtocolEntity(
                messageProtocolEntity.getId(), messageProtocolEntity.getFrom(),
                'read', messageProtocolEntity.getParticipant())

            self.toLower(receipt)
Exemplo n.º 26
0
    def handleEncMessage(self, node):
        encMessageProtocolEntity = EncryptedMessageProtocolEntity.fromProtocolTreeNode(node)
        isGroup =  node["participant"] is not None
        senderJid = node["participant"] if isGroup else node["from"]
        encNode = None
        if node.getChild("enc")["v"] == "2" and senderJid not in self.v2Jids:
            self.v2Jids.append(senderJid)
        try:
            if encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_PKMSG):
                self.handlePreKeyWhisperMessage(node)
            if encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_MSG):
                self.handleWhisperMessage(node)
            if encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_SKMSG):
                self.handleSenderKeyMessage(node)

            self.retryDel(node)
            self.recoverKeyClean(senderJid)

        except NoSessionException as e:
            logger.error(e)
            entity = GetKeysIqProtocolEntity([senderJid])
            if senderJid not in self.pendingIncomingMessages:
                self.pendingIncomingMessages[senderJid] = []
            self.pendingIncomingMessages[senderJid].append(node)

            self._sendIq(entity, lambda a, b: self.onGetKeysResult(a, b, self.processPendingIncomingMessages), self.onGetKeysError)
        except DuplicateMessageException as e:
            logger.error(e)
            logger.warning("Going to send the delivery receipt myself !")
            self.toLower(OutgoingReceiptProtocolEntity(node["id"], node["from"], read=False, participant = node["participant"], t=node["t"]).toProtocolTreeNode())

        except UntrustedIdentityException as e:
            if(self.getProp(self.__class__.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(e)
                logger.warning("Ignoring message with untrusted identity")

        except (NoPrekeyRecordException, InvalidKeyIdException) as e:
            logger.warning(e)
            if(self.getProp(self.__class__.PROP_RECOVER_KEYS_MSG, True)):
                self.recoverKey(senderJid)
            self.retryAdd(node)

        except (InvalidMessageException) as e:
            logger.warning(e)
            self.retryAdd(node)
Exemplo n.º 27
0
    def onMessage(self, messageProtocolEntity):

        if messageProtocolEntity.getType() == 'text':

            #print (messageProtocolEntity.getBody())
            #if messageProtocolEntity.getFrom() == "*****@*****.**":
            receipt = OutgoingReceiptProtocolEntity(
                messageProtocolEntity.getId(), messageProtocolEntity.getFrom(),
                'read', messageProtocolEntity.getParticipant())
            self.toLower(receipt)

            recvqueue.put({
                "from": messageProtocolEntity.getFrom(),
                "data": messageProtocolEntity.getBody()
            })
Exemplo n.º 28
0
    def onMessage(self, message):
        ''' Handles incoming messages and responds to them if needed. '''
        # pylint: disable=invalid-name
        logging.debug('Message %s from %s received, content: %s',
                      message.getId(), message.getFrom(), message.getBody())

        receipt = OutgoingReceiptProtocolEntity(message.getId(),
                                                message.getFrom(), 'read',
                                                message.getParticipant())
        self.toLower(receipt)

        time.sleep(0.2)
        self.react(message)

        registry.fire_event(registry.BOT_MSG_RECEIVE, self, message)
Exemplo n.º 29
0
    def onMediaMessage(self, mEntity):
        id = mEntity.getId()
        src = mEntity.getFrom()
        tpe = mEntity.getMediaType()
        url = getattr(mEntity, 'url', None)

        print("<= WhatsApp: <- Media %s (%s)" % (tpe, src))

        content = "Received a media of type: %s\n" % (tpe)
        content += "URL: %s\n" % (url)
        content += str(mEntity)
        self.sendEmail(mEntity, "Media: %s" % (tpe), content)

        receipt = OutgoingReceiptProtocolEntity(id, src)
        if not args.dry:
            self.toLower(receipt)
Exemplo n.º 30
0
    def parseAndHandleMessageProto(self, encMessageProtocolEntity, serializedData):
        node = encMessageProtocolEntity.toProtocolTreeNode()
        m = Message()
        try:
            if sys.version_info >= (3,0):
                serializedData = serializedData.encode()
        except AttributeError:
            logger.error("AttributeError: 'bytes' object has no attribute 'encode'. Skipping 'encode()'")
            pass
        handled = False
        try:
            m.ParseFromString(serializedData)
        except:
            print("DUMP:")
            print(serializedData)
            print([s for s in serializedData])
            # print([ord(s) for s in serializedData])
            raise
        if not m or not serializedData:
            raise ValueError("Empty message")

        if m.HasField("sender_key_distribution_message"):
            handled = True
            axolotlAddress = AxolotlAddress(encMessageProtocolEntity.getParticipant(False), 0)
            self.handleSenderKeyDistributionMessage(m.sender_key_distribution_message, axolotlAddress)

        if m.HasField("conversation"):
            handled = True
            self.handleConversationMessage(node, m.conversation)
        elif m.HasField("contact_message"):
            handled = True
            self.handleContactMessage(node, m.contact_message)
        elif m.HasField("url_message"):
            handled = True
            self.handleUrlMessage(node, m.url_message)
        elif m.HasField("location_message"):
            handled = True
            self.handleLocationMessage(node, m.location_message)
        elif m.HasField("image_message"):
            handled = True
            self.handleImageMessage(node, m.image_message)

        if not handled:
            # raise ValueError("Unhandled")
            logger.error("Unhandled message. Skipping...")
            self.toLower(OutgoingReceiptProtocolEntity(node["id"], node["from"], read= True, participant=node["participant"]).toProtocolTreeNode())
            return