Exemplo n.º 1
0
    def onMessage(self, messageProtocolEntity):

        print(messageProtocolEntity.getFrom())

        # send receipt otherwise we keep receiving the same message over and over
        receipt = OutgoingReceiptProtocolEntity(
            messageProtocolEntity.getId(), messageProtocolEntity.getFrom(),
            False, messageProtocolEntity.getParticipant())
        self.toLower(receipt)

        # route based on message type
        if messageProtocolEntity.getType() == 'text':
            self.onTextMessage(messageProtocolEntity)
        elif messageProtocolEntity.getType() == 'media':
            self.onMediaMessage(messageProtocolEntity)

        # to store in database, send grouped receipts later on when going online
        store = (messageProtocolEntity.getId(),
                 messageProtocolEntity.getFrom(),
                 messageProtocolEntity.getParticipant())
        time.sleep(randint(3, 5))
        self.toLower(AvailablePresenceProtocolEntity())
        receipt = OutgoingReceiptProtocolEntity(store[0], store[1], True,
                                                store[2])
        self.toLower(receipt)
        time.sleep(randint(3, 5))
        self.toLower(UnavailablePresenceProtocolEntity())
Exemplo n.º 2
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.º 3
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.º 4
0
    def onTextMessage(self, messageProtocolEntity):
        receipt = OutgoingReceiptProtocolEntity(
            messageProtocolEntity.getId(), messageProtocolEntity.getFrom())

        print("%s [%s]:%s" %
              (messageProtocolEntity.getFrom(False),
               datetime.datetime.fromtimestamp(
                   messageProtocolEntity.getTimestamp()).strftime(
                       '%d-%m-%Y %H:%M'), messageProtocolEntity.getBody()))

        outgoingMessageProtocolEntity = OutgoingReceiptProtocolEntity(
            messageProtocolEntity.getId(), messageProtocolEntity.getFrom())
        self.toLower(receipt)
        print("Sent delivered receipt Message %s" %
              messageProtocolEntity.getId())
Exemplo n.º 5
0
    def onMessage(self, messageProtocolEntity):
        receipt = OutgoingReceiptProtocolEntity(
            messageProtocolEntity.getId(), messageProtocolEntity.getFrom(),
            'read', messageProtocolEntity.getParticipant())

        # wait for the groups to be fetched before handling any incoming messages
        if not groups_ready:
            logger.info("Waiting with message delivery, groups not ready")
            self.offlineMsgQ.put(messageProtocolEntity)
            return

        if isinstance(messageProtocolEntity, MediaMessageProtocolEntity):
            self.onMediaMessage(messageProtocolEntity)
            return
        elif isinstance(messageProtocolEntity, TextMessageProtocolEntity):
            self.sendToTelegram(messageProtocolEntity,
                                messageProtocolEntity.getBody(),
                                isMedia=False)
            logging.info(
                "Received message from " +
                messageProtocolEntity.getNotify().encode('latin-1').decode() +
                ": " + messageProtocolEntity.getBody())
        else:
            logger.error("Unknown message type %s " %
                         str(messageProtocolEntity))
            return

        # confirm message received
        self.toLower(receipt)
Exemplo n.º 6
0
    def handleSenderKeyMessage(self, node):
        encMessageProtocolEntity = EncryptedMessageProtocolEntity.fromProtocolTreeNode(
            node)
        enc = encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_SKMSG)

        try:
            plaintext = self.manager.group_decrypt(
                groupid=encMessageProtocolEntity.getFrom(True),
                participantid=encMessageProtocolEntity.getParticipant(False),
                data=enc.getData())
            self.parseAndHandleMessageProto(encMessageProtocolEntity,
                                            plaintext)

            node = encMessageProtocolEntity.toProtocolTreeNode()
            node.addChild(
                (ProtoProtocolEntity(plaintext,
                                     enc.getMediaType())).toProtocolTreeNode())

            self.toUpper(node)

        except exceptions.NoSessionException:
            logger.warning("No session for %s, going to send a retry",
                           encMessageProtocolEntity.getAuthor(False))
            retry = RetryOutgoingReceiptProtocolEntity.fromMessageNode(
                node, self.manager.registration_id)
            self.toLower(retry.toProtocolTreeNode())
        except exceptions.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())
Exemplo n.º 7
0
    def onMessage(self, messageProtocolEntity):
        print "onMessage"

        # send receipt otherwise we keep receiving the same message over and over
        if True:
            receipt = OutgoingReceiptProtocolEntity(
                messageProtocolEntity.getId(), messageProtocolEntity.getFrom(),
                'read', messageProtocolEntity.getParticipant())

            jid = messageProtocolEntity.getFrom()
            sender = jid.split("-")[0]
            print "Message from: "
            print sender

            if sender not in self.session.senders and jid not in self.session.sub2gid.values(
            ):
                if len(self.session.senders) % 5 == 0:
                    # Create a new group - JBG
                    self.session.group = "lavalab2-" + str(
                        int(round(time.time())))
                    entity = CreateGroupsIqProtocolEntity(
                        self.session.group,
                        participants=[self.aliasToJid(sender)])
                    self.toLower(entity)
                    # This will re-fetch subject to group id mappings, get new group id - JBG
                    self.toLower(ListGroupsIqProtocolEntity())
                else:
                    # Invite user to group - JBG
                    gid = self.session.sub2gid[self.session.group]
                    jids = [self.aliasToJid(sender)]
                    entity = AddParticipantsIqProtocolEntity(
                        self.aliasToJid(gid), jids)
                    self.toLower(entity)
                self.session.senders.append(sender)
            self.toLower(receipt)
    def onMessage(self, messageProtocolEntity):
        #send receipt otherwise we keep receiving the same message over and over

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

            if messageProtocolEntity.getBody().lower() == message.lower() :
                response ="1. Type 'info' to get info about temperature, moisture and weather.\n 2. Type 'water' to irrigate.\n 3. Type 'stop '
                
             elif  messageProtocolEntity.getBody().lower() == message1.lower() :
                response = a

            elif messageProtocolEntity.getBody().lower() == message2.lower() :
                response = "enter"

            elif  messageProtocolEntity.getBody().lower() == message3.lower() :

                response = "Enter your command stop water"

            else :
                response = "Enter your command"

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

            self.toLower(receipt)
            self.toLower(outgoingMessageProtocolEntity)
Exemplo n.º 9
0
    def recvMessageStanza(self, node):
        protoNode = node.getChild("proto")

        if protoNode:
            if protoNode and protoNode["mediatype"] is None:
                message = AttributesConverter.get().protobytes_to_message(
                    protoNode.getData())
                if message.conversation:
                    self.toUpper(
                        TextMessageProtocolEntity(
                            message.conversation,
                            MessageMetaAttributes.
                            from_message_protocoltreenode(node)))
                elif message.extended_text:
                    self.toUpper(
                        ExtendedTextMessageProtocolEntity(
                            message.extended_text,
                            MessageMetaAttributes.
                            from_message_protocoltreenode(node)))
                elif not message.sender_key_distribution_message:
                    # Will send receipts for unsupported message types to prevent stream errors
                    logger.warning(
                        "Unsupported message type: %s, will send receipts to "
                        "prevent stream errors" % message)
                    self.toLower(
                        OutgoingReceiptProtocolEntity(
                            messageIds=[node["id"]],
                            to=node["from"],
                            participant=node["participant"]).
                        toProtocolTreeNode())
Exemplo n.º 10
0
    def on_message(self, msg):

        print msg

        # accept only media vcard
        if msg.getType(
        ) == TextMessageProtocolEntity.MESSAGE_TYPE_MEDIA and msg.getMediaType(
        ) == MediaMessageProtocolEntity.MEDIA_TYPE_VCARD:
            user_info = self.on_contact(msg)
            # msg_reply = TextMessageProtocolEntity(
            #         "hang tight, setting up a transfer to " + user_info['n'],
            #         to=msg.getFrom())
            msg_reply = TextMessageProtocolEntity(
                "awesome, head over to " + PAY_URL +
                ", to complete the transaction for " + user_info['n'],
                to=msg.getFrom())

            self.toLower(msg_reply)

        else:
            # if it isn't a vcard return a message
            msg_reply = TextMessageProtocolEntity(
                "doesn't seem to be a valid message, try sending a contact ?",
                to=msg.getFrom())
            self.toLower(msg_reply)

        # send read receipt for message
        receipt = OutgoingReceiptProtocolEntity(msg.getId(), msg.getFrom(),
                                                'read', msg.getParticipant())

        self.toLower(receipt)
 def handleDocumentMessage(self, originalEncNode, documentMessage):
     try:
         messageNode = copy.deepcopy(originalEncNode)
         messageNode["type"] = "media"
         mediaNode = ProtocolTreeNode(
             "media", {
                 "type": "document",
                 "url": documentMessage.url,
                 "mimetype": documentMessage.mime_type,
                 "title": documentMessage.title,
                 "filehash": documentMessage.file_sha256,
                 "size": str(documentMessage.file_length),
                 "pages": str(documentMessage.page_count),
                 "mediakey": documentMessage.media_key
             },
             data=documentMessage.jpeg_thumbnail)
         messageNode.addChild(mediaNode)
         self.toUpper(messageNode)
     except:
         if PROP_IGNORE_UNHANDLED:
             self.toLower(
                 OutgoingReceiptProtocolEntity(
                     originalEncNode["id"],
                     originalEncNode["from"],
                     participant=originalEncNode["participant"]).
                 toProtocolTreeNode())
             logger.warning("Unhandled message, sending delivery receipt")
         else:
             print(m)
             raise ValueError("Unhandled")
Exemplo n.º 12
0
    def on_message(self, message):
        """Received a message."""
        # Parse information
        sender = message.getFrom(full=False)

        logger.debug('received message from %s' % sender)

        # Send receipt
        receipt = OutgoingReceiptProtocolEntity(
            message.getId(),
            message.getFrom(),
            'read',
            message.getParticipant()
        )

        self.toLower(receipt)

        # Ignore non-text messages
        if message.getType() != 'text':
            logger.info('not a text message, ignoring')
            return

        # Do stuff
        if is_blacklisted(sender):
            logger.debug('phone is blacklisted: %s' % sender)
            return

        body = message.getBody()

        # Relay to Telegram
        logger.info('relaying message to Telegram')
        SIGNAL_TG.send('wabot', phone=sender, message=body)
Exemplo n.º 13
0
    def fromProtocolTreeNode(node):
        entity = OutgoingReceiptProtocolEntity.fromProtocolTreeNode(node)
        entity.__class__ = RetryOutgoingReceiptProtocolEntity
        retryNode = node.getChild("retry")
        entity.setRetryData(ResultGetKeysIqProtocolEntity._bytesToInt(node.getChild("registration").data), retryNode["v"], retryNode["count"], retryNode["t"])

        return entity
Exemplo n.º 14
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)
Exemplo n.º 15
0
    def onMediaMessage(self, mEntity):
        if mEntity.getMediaType() == "image":
            print("Echoing image %s to %s" %
                  (mEntity.url, mEntity.getFrom(False)))
        elif mEntity.getMediaType() == "location":
            print("Echoing location (%s, %s) to %s" %
                  (mEntity.getLatitude(), mEntity.getLongitude(),
                   mEntity.getFrom(False)))
        elif mEntity.getMediaType() == "vcard":
            print("Echoing vcard (%s, %s) to %s" %
                  (mEntity.getName(), mEntity.getCardData(),
                   mEntity.getFrom(False)))

        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)
        self.toLower(receipt)
Exemplo n.º 16
0
    def onMessage(self, messageProtocolEntity):
        #send receipt otherwise we keep receiving the same message over and over

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

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

            #self.toLower(receipt)
            #self.toLower(outgoingMessageProtocolEntity)
            t = messageProtocolEntity.getBody()
            f = messageProtocolEntity.getFrom(False)
            print("From: %s" % f)
            if f == WA_NUMBER:
                print("Message from myself!")
            s = f.split('-')[0]
            print("Split: %s" % s)
            alias = self.jidToAlias(s)
            print("Alias: %s" % alias)
            if messageProtocolEntity.isGroupMessage():
                print("Is group message")
                g = f.split('-')[1]
                g_alias = self.gidToAlias(g)
                alias += '@' + g_alias
            print("From: %s\nMessage: %s" % (alias, t))
            sink_sms.send(IDENTIFIER, t, f)
Exemplo n.º 17
0
    def on_message(self, message: MessageProtocolEntity):
        receipt = OutgoingReceiptProtocolEntity(
            messageIds=message.getId(),
            to=message.getFrom(),
            read=True,
            participant=message.getParticipant())

        today = datetime.datetime.now().isocalendar()

        target_dir = self.getProp(self.__class__.PROP_TARGET)
        target_file = f'{today[0]}-{today[1]}-{today[2]}.json'
        try:
            nice_message = self._jsonify(message)
            if nice_message:
                with open(os.path.join(target_dir, target_file),
                          'a',
                          encoding='utf-8') as file:
                    file.write(nice_message)
                    file.write(os.linesep)
            else:
                log.info(
                    f'Did not write non-text message with ID {message.getId()}'
                )
        except Exception as e:
            log.warning(f'Unable to write message: {str(e)}')

        self.toLower(receipt)
 def handleLocationMessage(self, originalEncNode, locationMessage):
     try:
         messageNode = copy.deepcopy(originalEncNode)
         messageNode["type"] = "media"
         mediaNode = ProtocolTreeNode("media", {
             "latitude":
             locationMessage.degrees_latitude,
             "longitude":
             locationMessage.degrees_longitude,
             "name":
             "%s %s" % (locationMessage.name, locationMessage.address),
             "url":
             locationMessage.url,
             "encoding":
             "raw",
             "type":
             "location"
         },
                                      data=locationMessage.jpeg_thumbnail)
         messageNode.addChild(mediaNode)
         self.toUpper(messageNode)
     except:
         if PROP_IGNORE_UNHANDLED:
             self.toLower(
                 OutgoingReceiptProtocolEntity(
                     originalEncNode["id"],
                     originalEncNode["from"],
                     participant=originalEncNode["participant"]).
                 toProtocolTreeNode())
             logger.warning("Unhandled message, sending delivery receipt")
         else:
             print(m)
             raise ValueError("Unhandled")
Exemplo n.º 19
0
 def onMessage(self, entity):
     self.toLower(
         OutgoingReceiptProtocolEntity(entity.getId(), entity.getFrom(),
                                       'read', entity.getParticipant()))
     self.vkApi.messages.send(user_id=self.userId,
                              message='from: {getFrom}\n{getBody}'.format(
                                  getFrom=entity.getFrom(),
                                  getBody=entity.getBody()))
Exemplo n.º 20
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):
                logger.debug("Handle preKey Whisper Message")
                self.handlePreKeyWhisperMessage(node)
            elif encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_MSG):
                logger.debug("Handle sender key message")
                self.handleWhisperMessage(node)
            if encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_SKMSG):
                logger.debug("Handle Sender KeyMessage")
                self.handleSenderKeyMessage(node)
        except (InvalidMessageException, InvalidKeyIdException) as e:
            logger.warning(
                "InvalidMessage or KeyId 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")
        except:
            pass
Exemplo n.º 21
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.º 22
0
    def processResponse(self, entity):
        """Marks the message as delivered and read."""

        # mark as delivered
        receipt = OutgoingReceiptProtocolEntity(entity.getId(),
                                                entity.getFrom())
        self.toLower(receipt)

        # formated_response = "Hello world! This is a response message."

        # mark as read
        receipt = OutgoingReceiptProtocolEntity(entity.getId(),
                                                entity.getFrom(), "read")
        self.toLower(receipt)

        # self.toLower(formated_response)
        self.toLower(entity.ack())
        self.toLower(entity.ack(True))
Exemplo n.º 23
0
 def retryAdd(self, node):
     self.retryIncomingMessages[node["id"]] = (self.retryIncomingMessages[node["id"]] + 1) if node["id"] in self.retryIncomingMessages else 1
     if self.retryIncomingMessages[node["id"]] > 5:
          logger.warning("Too many retries!! Going to send the delivery receipt myself!")
          self.toLower(OutgoingReceiptProtocolEntity(node["id"], node["from"], read=False, participant = node["participant"], t=node["t"]).toProtocolTreeNode())
     else:
          retry = RetryOutgoingReceiptProtocolEntity.fromMessageNode(node)
          retry.setRegData(self.store.getLocalRegistrationId())
          self.toLower(retry.toProtocolTreeNode())
Exemplo n.º 24
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.º 25
0
 def onNotification(self, notification):
     self.output(
         "From :%s, Type: %s" %
         (self.jidToAlias(notification.getFrom()), notification.getType()),
         tag="Notification")
     if self.sendReceipts:
         receipt = OutgoingReceiptProtocolEntity(notification.getId(),
                                                 notification.getFrom())
         self.toLower(receipt)
Exemplo n.º 26
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.º 27
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.º 28
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.º 29
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.º 30
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.º 31
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.º 32
0
 def fromProtocolTreeNode(node):
     entity = OutgoingReceiptProtocolEntity.fromProtocolTreeNode(node)
     entity.__class__ = RetryOutgoingReceiptProtocolEntity
     retryNode = node.getChild("retry")
     entity.setRetryData(retryNode["t"], retryNode["v"], retryNode["count"], node.getChild("registration").data)