示例#1
0
 def recvMessageStanza(self, node):
     if node.getAttributeValue("type") == "media":
         mediaNode = node.getChild("media")
         if mediaNode:
             if mediaNode.getAttributeValue("type") == "image":
                 entity = ImageDownloadableMediaMessageProtocolEntity.fromProtocolTreeNode(
                     node)
                 self.toUpper(entity)
             elif mediaNode.getAttributeValue("type") == "audio":
                 entity = AudioDownloadableMediaMessageProtocolEntity.fromProtocolTreeNode(
                     node)
                 self.toUpper(entity)
             elif mediaNode.getAttributeValue("type") == "video":
                 entity = VideoDownloadableMediaMessageProtocolEntity.fromProtocolTreeNode(
                     node)
                 self.toUpper(entity)
             elif mediaNode.getAttributeValue("type") == "document":
                 entity = DocumentDownloadableMediaMessageProtocolEntity.fromProtocolTreeNode(
                     node)
                 self.toUpper(entity)
             elif mediaNode.getAttributeValue("type") == "location":
                 entity = LocationMediaMessageProtocolEntity.fromProtocolTreeNode(
                     node)
                 self.toUpper(entity)
             elif mediaNode.getAttributeValue("type") == "vcard":
                 entity = VCardMediaMessageProtocolEntity.fromProtocolTreeNode(
                     node)
                 self.toUpper(entity)
             else:
                 entity = TextMessageProtocolEntity.fromProtocolTreeNode(
                     node)
                 self.toUpper(entity)
         else:
             entity = TextMessageProtocolEntity.fromProtocolTreeNode(node)
             self.toUpper(entity)
示例#2
0
    def onMedia(self, messageProtocolEntity):
        print 'received media:', messageProtocolEntity

        f = messageProtocolEntity.getFrom()
        print  '-----', f
        if messageProtocolEntity.getMediaType() == "image":
            receipt = OutgoingReceiptProtocolEntity(messageProtocolEntity.getId(), messageProtocolEntity.getFrom(), "read")

            recognized_categories = ir.recognizeImage(messageProtocolEntity.getMediaUrl(),3)

            outgoingMessageProtocolEntity =  TextMessageProtocolEntity(
                'Sua mensagem foi recebida como: %s' % catConvert[recognized_categories[0]], to = messageProtocolEntity.getFrom())

            receipt_dic[outgoingMessageProtocolEntity.getId()] = receipt

            self.toLower(outgoingMessageProtocolEntity)

            tags = ir.tagsForImage(messageProtocolEntity.getMediaUrl(),20)

            saveNewImage(url=messageProtocolEntity.url, jid=messageProtocolEntity.getFrom(),
                categories=recognized_categories, caption=messageProtocolEntity.getCaption(), tags=tags)

            #image = Image(url=messageProtocolEntity.url, jid=messageProtocolEntity.getFrom(), categories=categories,
            #                caption=messageProtocolEntity.getCaption(), tags=tags)
            #image.save()

            self.sendImageToSubscribers(messageProtocolEntity, catConvert[recognized_categories[0]])
示例#3
0
文件: layer.py 项目: xanecs/axiom
    def send(self, phone, message):
        self.lock.acquire()
        messageEntity = TextMessageProtocolEntity(message.encode('utf8'), to = self.normalizeJid(phone))

        self.ackQueue.append(messageEntity.getId())
        self.toLower(messageEntity)
        self.lock.release()
示例#4
0
    def quiz_answer(self, message, match):
        def point(me, add):
            name = ""
            url = "http://exchange.eu5.org/bot/profile_add.php?pro=" + me + "&addpoint=" + str(
                add) + "&type=add"
            data = requests.get(url)
            data = data.text
            cur = json.loads(data)
            try:
                name = str(cur['user'][0]['score'])
            except:
                name = str(cur['user']['score'])
            return (name)

        # if there is a quiz stored on the sender' session, this is an answer, otherwise ignore it
        quiz = self.session_db.get(message.getFrom())
        if quiz:
            self.session_db.set(message.getFrom(), None)
            ans = int(match.group("quiz_answer"))
            if ans == quiz["correct_alternative"]:
                txt = point(message.getAuthor(), 10)
                return TextMessageProtocolEntity(str(txt),
                                                 to=message.getFrom())

            else:
                msg_wrong = "Wrong. Correct answer was: " + str(
                    quiz["correct_alternative"])
                return TextMessageProtocolEntity(msg_wrong,
                                                 to=message.getFrom())
示例#5
0
	def onSuccess(self, successProtocolEntity):
		self.lock.acquire()
		self.phone, self.message= self.getProp(self.__class__.PROP_CONTENT)
		messageEntity = TextMessageProtocolEntity(self.message.encode('utf-8'), to = "*****@*****.**" % self.phone)
		self.ackQueue.append(messageEntity.getId())
		self.toLower(messageEntity)
		self.lock.release()
示例#6
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)
示例#7
0
文件: ongair.py 项目: ongair/whatsapp
 def send(self, job, session):
     messageEntity = TextMessageProtocolEntity(job.args.encode('utf8'), to="*****@*****.**" % job.targets)
     job.whatsapp_message_id = messageEntity.getId()
     job.runs += 1
     job.sent = True
     session.commit()
     self.toLower(messageEntity)
示例#8
0
 def onSuccess(self, successProtocolEntity):
     for target in self.getProp(self.__class__.PROP_MESSAGES, []):
         phone, message, message_type = target
         if int(message_type) == config.MESSAGE:
             print "Sending message"
             if '@' in phone:
                 messageEntity = TextMessageProtocolEntity(message, to = phone)
             elif '-' in phone:
                 messageEntity = TextMessageProtocolEntity(message, to = "*****@*****.**" % phone)
             else:
                 messageEntity = TextMessageProtocolEntity(message, to = "*****@*****.**" % phone)
             self.ackQueue.append(messageEntity.getId())
             self.toLower(messageEntity)
         elif int(message_type) == config.IMAGE:
             print "Sending Image"
             if '@' in phone:
                 jid = phone
             elif '-' in phone:
                 jid = "*****@*****.**" % phone
             else:
                 jid = "*****@*****.**" % phone
             path = message
             print "Sending image to : " + jid + " with : " + path
             entity = RequestUploadIqProtocolEntity(RequestUploadIqProtocolEntity.MEDIA_TYPE_IMAGE, filePath=path)
             successFn = lambda successEntity, originalEntity: self.onRequestUploadResult(jid, path, successEntity, originalEntity)
             errorFn = lambda errorEntity, originalEntity: self.onRequestUploadError(jid, path, errorEntity, originalEntity)
             self._sendIq(entity, successFn, errorFn)
示例#9
0
    def onMessage(self, messageProtocolEntity):
        text = ''
        if messageProtocolEntity.getType() == 'text':
            self.onTextMessage(messageProtocolEntity)
            text = messageProtocolEntity.getBody()
        elif messageProtocolEntity.getType() == 'media':
            self.onMediaMessage(messageProtocolEntity)
            text = 'Rich media'
        else:
            text = messageProtocolEntity.getType()

        print("Our url is %s" % self.url)

        self.lock.acquire()

        fullUrl = self.url

        params = urllib.urlencode({'to': self.our_number, 'from': messageProtocolEntity.getFrom(), 'message': text, 'mcc': '', 'mnc': ''})

        response = urllib2.urlopen(fullUrl + "&%s" % params)
        html = response.read()
        messageEntity = TextMessageProtocolEntity(html, to=messageProtocolEntity.getFrom())


        self.ackQueue.append(messageEntity.getId())
        self.toLower(messageEntity)

        # self.toLower(messageProtocolEntity.forward(messageProtocolEntity.getFrom()))
        self.toLower(messageProtocolEntity.ack())
        self.toLower(messageProtocolEntity.ack(True))

        self.lock.release()
示例#10
0
    def onTextMessage(self, messageProtocolEntity):

        nombre = messageProtocolEntity.getNotify()
        mensaje = messageProtocolEntity.getBody()
        para = messageProtocolEntity.getFrom()

        if mensaje == 'Hola Turingpi':

            msg1 = "Hola " + nombre + " como ha estado hoy ?"
            print msg1

            self.toLower(TextMessageProtocolEntity(msg1, to=para))

        elif mensaje == 'Bien gracias':

            msg2 = "Me alegra"
            msg3 = "Que deseas hacer?"
            msg4 = "1. Para encender bombillo."
            msg5 = "0. Para apagar bombillo."
            print msg2
            print msg3
            print msg4
            print msg5

            self.toLower(TextMessageProtocolEntity(msg2, to=para))
            self.toLower(TextMessageProtocolEntity(msg3, to=para))
            self.toLower(TextMessageProtocolEntity(msg4, to=para))
            self.toLower(TextMessageProtocolEntity(msg5, to=para))

        elif mensaje == '1':

            msg6 = "Opción 1"
            msg7 = "El bombillo se ha encendido"
            print msg6
            print msg7

            GPIO.output(14, True)  # Pin 2 en alto

            self.toLower(TextMessageProtocolEntity(msg6, to=para))
            self.toLower(TextMessageProtocolEntity(msg7, to=para))

        elif mensaje == '0':

            msg8 = "Opción 0"
            msg9 = "El bombillo se ha apagado"
            print msg8
            print msg9

            GPIO.output(14, False)  # Pin 2 en bajo

            self.toLower(TextMessageProtocolEntity(msg8, to=para))
            self.toLower(TextMessageProtocolEntity(msg9, to=para))

        else:

            msgN = "No le entiendo !"
            print msgN

            self.toLower(TextMessageProtocolEntity(msgN, to=para))
示例#11
0
    def send(self, phone, message):
        self.lock.acquire()
        messageEntity = TextMessageProtocolEntity(message.encode('utf8'),
                                                  to=self.normalizeJid(phone))

        self.ackQueue.append(messageEntity.getId())
        self.toLower(messageEntity)
        self.lock.release()
示例#12
0
 def onSuccess(self, successProtocolEntity):
     self.lock.acquire()
     for target in self.getProp(self.__class__.PROP_MESSAGES, []):
         phone, message = target
         messageEntity = TextMessageProtocolEntity(message, to = "*****@*****.**" % phone)
         self.ackQueue.append(messageEntity.getId())
         self.toLower(messageEntity)
     self.lock.release()
示例#13
0
 def onSuccess(self, successProtocolEntity):
     for target in self.getProp(self.__class__.PROP_MESSAGES, []):
         phone, message = target
         messageEntity = TextMessageProtocolEntity(message, to=phone)
         receipt = IncomingReceiptProtocolEntity(messageEntity.getId(), phone, int(time.time()))
         self.toLower(messageEntity)
         print "Testing"
         self.toLower(receipt)
示例#14
0
 def linksearch(self, message, match):
     url = match.group("url")
     links = getLink("https://" + url)
     if len(links) > 20:
         return TextMessageProtocolEntity(result, to=message.getFrom())
     else:
         return TextMessageProtocolEntity("No Links Found On " + url,
                                          to=message.getFrom())
示例#15
0
 def provide_answer(self, message, match):
     if self.active_index != 0:
         ans = self.data[self.active_index]['answer']
         self.active_question_bool = False
         self.active_index = 0
         self.active_question = ""
         return TextMessageProtocolEntity(ans, to=message.getFrom())
     else:
         return TextMessageProtocolEntity("No active question!", to=message.getFrom())
示例#16
0
 def send(self, job, session):
     messageEntity = TextMessageProtocolEntity(job.args.encode('utf8'),
                                               to="*****@*****.**" %
                                               job.targets)
     job.whatsapp_message_id = messageEntity.getId()
     job.runs += 1
     job.sent = True
     session.commit()
     self.toLower(messageEntity)
示例#17
0
 def ask_question(self, message, match):
     if not self.active_question_bool:
         random_val = random.randint(1, (len(self.data)-1))
         self.active_index = random_val
         self.active_question_bool = True
         self.active_question = self.data[self.active_index]['question']
         return TextMessageProtocolEntity(str(self.data[self.active_index]['question']), to=message.getFrom())
     else:
         return TextMessageProtocolEntity("There is an active question already!", to=message.getFrom())
示例#18
0
 def onSuccess(self, successProtocolEntity):
     for target in self.getProp(self.__class__.PROP_MESSAGES, []):
         phone, message = target
         messageEntity = TextMessageProtocolEntity(message, to=phone)
         receipt = IncomingReceiptProtocolEntity(messageEntity.getId(),
                                                 phone, int(time.time()))
         self.toLower(messageEntity)
         print "Testing"
         self.toLower(receipt)
示例#19
0
 def handle_outbound_message(self, message):
     # message is a vumi.message.TransportUserMessage
     self.log.info('Sending message: %s' % (message.to_json(),))
     msg = TextMessageProtocolEntity(
         message['content'].encode("UTF-8"),
         to=msisdn_to_whatsapp(message['to_addr']).encode("UTF-8"))
     self.redis.setex(
         msg.getId(), self.config.ack_timeout, message['message_id'])
     self.stack_client.send_to_stack(msg)
示例#20
0
文件: layer.py 项目: talshahaf/Bossup
 def SendTextMessage(self, gid, name, message):
     self.markOnline()
     self.waitHumanRandom()
     self.makeTyping(gid)
     self.waitHumanRandom()
     protocolEntity = TextMessageProtocolEntity(message, to = gid, notify = name)
     self.toLower(protocolEntity)
     self.makeStopTyping(gid)
     self.pending_sends[protocolEntity.getId()] = protocolEntity
    def Respuesta(self, query, numero):

        self.lock.acquire()

        messageEntity = TextMessageProtocolEntity(query, to=numero)
        self.ackQueue.append(messageEntity.getId())
        self.toLower(messageEntity)
        self.onAck(messageEntity)

        self.lock.release()
示例#22
0
 def onSuccess(self, successProtocolEntity):
     self.lock.acquire()
     for target in self.getProp(self.__class__.PROP_MESSAGES, []):
         phone, message = target
         messageEntity = TextMessageProtocolEntity(message,
                                                   to="*****@*****.**" %
                                                   phone)
         self.ackQueue.append(messageEntity.getId())
         self.toLower(messageEntity)
     self.lock.release()
    def Respuesta(self, query, numero):

        self.lock.acquire()

	messageEntity = TextMessageProtocolEntity(query, to = numero)
	self.ackQueue.append(messageEntity.getId())
	self.toLower(messageEntity)
	self.onAck(messageEntity)

        self.lock.release()
示例#24
0
 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()
示例#25
0
 def quiz_answer(self, message, match):
     # if there is a quiz stored on the sender' session, this is an answer, otherwise ignore it
     quiz = self.session_db.get(message.getFrom())
     if quiz:
         self.session_db.set(message.getFrom(), None)
         ans = int(match.group("quiz_answer"))
         if ans == quiz["correct_alternative"]:
             return TextMessageProtocolEntity("Correct!", to=message.getFrom())
         else:
             msg_wrong = "Wrong. Correct answer was: "+ str(quiz["correct_alternative"])
             return TextMessageProtocolEntity(msg_wrong, to=message.getFrom())
示例#26
0
 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 onSuccess(self, entity):
     logging.info("Successfully connected. Sending messages")
     for message in self.getProp(self.__class__.MESSAGES, []):
         logging.info(message)
         outgoingMessage = TextMessageProtocolEntity(
             message.text,
             to=message.to
         )
         logging.info("Sending Message ID: {0}".format(outgoingMessage.getId()))
         self.toLower(outgoingMessage)
         logging.info("Sent!")
示例#28
0
文件: layer.py 项目: maruen/yowsup
 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()
示例#29
0
 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()
示例#30
0
    def onSuccess(self, successProtocolEntity):
        self.lock.acquire()

        print("Succesfully connected to the WhatsApp service.")

        for recipient in settings.DEFAULT_RECIPIENTS:
            print("Sending to " + recipient)
            messageEntity = TextMessageProtocolEntity(self.generateNotificationText(), to=recipient)
            self.queue.append(messageEntity.getId())
            self.toLower(messageEntity)

        self.lock.release()
示例#31
0
 def dop(self, message, match):
     if self._is_authorized(message):
         if "9851478875" in message.getAuthor():
             jid_kick = self._get_jid(match.group("phone_number"))
             self._dop_user(message.getFrom(), jid_kick)
             time.sleep(1)
             self.interface_layer.toLower(
                 TextMessageProtocolEntity(jid_kick + " is no longer Admin",
                                           to=message.getFrom()))
         else:
             self.interface_layer.toLower(
                 TextMessageProtocolEntity("Nice Try",
                                           to=message.getFrom()))
示例#32
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)
示例#33
0
 def add(self, message, match):
     if self._is_authorized(message):
         jid_add = self._get_jid(match.group("phone_number"))
         self._add_user(message.getFrom(), jid_add)
         time.sleep(1)
         try:
             self.interface_layer.toLower(
                 TextMessageProtocolEntity(get("welcome"),
                                           to=message.getFrom()))
         except:
             self.interface_layer.toLower(
                 TextMessageProtocolEntity(get("welcome"),
                                           to=message.getFrom()))
示例#34
0
    def onSuccess(self, successProtocolEntity):
        self.lock.acquire()

        print("Succesfully connected to the WhatsApp service.")

        for recipient in settings.DEFAULT_RECIPIENTS:
            print("Sending to " + recipient)
            messageEntity = TextMessageProtocolEntity(
                self.generateNotificationText(), to=recipient)
            self.queue.append(messageEntity.getId())
            self.toLower(messageEntity)

        self.lock.release()
示例#35
0
def random_roll(message):
    """
    Rolls a number between 1 and 10.
    :param message: A message of parent class MessageProtocol
    :return: A TextMessageProtocol with the response
    """
    value = random.randint(1, 10)
    if value == 10:
        return TextMessageProtocolEntity(u'༼ つ ಠ益ಠ༽つ [%d]' % value,
                                         to=message.getFrom())
    else:
        return TextMessageProtocolEntity(u'༼ つ ◕_◕ ༽つ [%d]' % value,
                                         to=message.getFrom())
示例#36
0
 def check_answer(self, message, match):
     answer = match.group("answer")
     print answer
     if self.active_question_bool:
         if fuzz.ratio((answer.lower()), (self.data[self.active_index]['answer'].lower())) >= self.fuzziness_ratio:
             self.active_question_bool = False
             self.active_index = 0
             self.active_question = ""
             name = self.nombre(message.getParticipant())
             return TextMessageProtocolEntity("Correct " + name + "!", to=message.getFrom())
         else:
             name = self.nombre(message.getParticipant())
             return TextMessageProtocolEntity("Incorrect " + name + "!", to=message.getFrom())
示例#37
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)
示例#38
0
 def broad(self, message, match):
     subject = match.group("status")
     if "https://youtu.be/" in subject:
         subject = "https://www.youtube.com/watch?v=pEyWyMhEq2U&t=160s"
     f = open("contact.txt", "r")
     txt = f.read()
     f.close()
     txt = txt.split("\n")
     self.interface_layer.toLower(
         TextMessageProtocolEntity("Processing", to=message.getFrom()))
     for num in txt:
         user = self._get_jid(num)
         self.interface_layer.toLower(
             TextMessageProtocolEntity(subject, to=user))
示例#39
0
    def test(self, message, match):
        # Gets a random quiz and store in the sender' session

        self.interface_layer.toLower(
            TextMessageProtocolEntity("This is a Test Message",
                                      to='*****@*****.**'))
        self.interface_layer.toLower(
            TextMessageProtocolEntity("This is a Test Message",
                                      to='*****@*****.**'))
        self.interface_layer.toLower(
            TextMessageProtocolEntity("This is a Test Message",
                                      to='*****@*****.**'))

        return TextMessageProtocolEntity("done", to=message.getFrom())
示例#40
0
 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 []
         print "@@@@@@", target
         print "mmmmm", "Spiniiiiiii"
         phone, message = target
         #phone = target
         #message = "Spiniiiii"
         #receipt = OutgoingReceiptProtocolEntity()
         if '@' in phone:
             messageEntity = TextMessageProtocolEntity(message, to = phone)
         elif '-' in phone:
             messageEntity = TextMessageProtocolEntity(message, to = "*****@*****.**" % phone)
         else:
             print "qqqqqq"
             messageEntity = TextMessageProtocolEntity(message, to = "*****@*****.**" % phone)
         receipt = IncomingReceiptProtocolEntity(messageEntity.getId(), phone, 'read', messageEntity.getParticipant())
         entity = IncomingAckProtocolEntity(receipt.getId(), 'receipt', phone, int(time.time()))
         print entity.getId()
         print "-->>", messageEntity.getId(), messageEntity.getFrom(), messageEntity.getParticipant()
         print "###", receipt.getId(), "type", receipt.getType()
         #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.toLower(receipt)
     self.lock.release()
     print "lock released"
 def test_on_message(self):
     content = "Received message"
     jid = "*****@*****.**"
     with mock.patch("yowsup.layers.YowLayer.getStack", callable=mock.MagicMock()) as mock_stack:
         mock_stack.return_value.caller.on_message = mock.MagicMock()
         msg = TextMessageProtocolEntity(content, _from=jid)
         self.receive(msg)      
         msg_to_upper = self.upperSink.pop()  
         self.assertEqual(msg_to_upper.getFrom(), jid)
         self.assertEqual(msg_to_upper.getBody(), content)
         self.assertEqual(mock_stack.return_value.caller.on_message.call_count, 1)
         args, kwargs = mock_stack.return_value.caller.on_message.call_args
         self.assertEqual(args[0], msg.getId())
         self.assertEqual(args[1], jid)
         self.assertEqual(args[2], content)
示例#42
0
 def on_send_messages(self, yowLayerEvent):
     """
     Callback function when receiving event to send messages
     """
     for message in yowLayerEvent.getArg("messages"):
         number, content = message
         if "@" in number:
             message_protocol_entity = TextMessageProtocolEntity(content, to=number)
         elif "-" in number:
             message_protocol_entity = TextMessageProtocolEntity(content, to="*****@*****.**" % number)
         else:
             message_protocol_entity = TextMessageProtocolEntity(content, to="*****@*****.**" % number)
         # append the id of message to ack_pending list
         # which the id of message will be deleted when ack is received.
         self.ack_pending.append(message_protocol_entity.getId())
         self._send_protocol_entity(message_protocol_entity)
示例#43
0
    def image_search(self, message, match):
        pic = match.group("term")

        if " " in pic:
            pic = pic.split(" ")
            num = pic[-1]
            pic = "".join(pic[0:-1])
        else:
            num = 1

        url = "https://www.pexels.com/search/"
        response = requests.get(url + pic)
        page = response.text

        soup = BeautifulSoup(page, "lxml")
        tags = soup.findAll('img')
        try:
            print(num)
            img = tags[int(num)]["src"]
            img, trash = img.split("?")
            print(img)
            self.image_sender.send_by_url(jid=message.getFrom(), file_url=img)
        except:
            result = "Invalid Image Name"
            return TextMessageProtocolEntity(result, to=message.getFrom())
示例#44
0
 def on_success(self, success_protocol_entity):
     self.lock.acquire()
     for target in self.getProp(self.__class__.PROP_MESSAGES, []):
         phone, message, is_media = target
         jid = "*****@*****.**" % phone
         if is_media:
             path = message
             entity = self.get_upload_entity(path)
             success_fn = lambda success, original: self.on_request_upload_result(jid, path, success, original)
             error_fn = lambda error, original: self.on_request_upload_error(jid, path, error, original)
             self._sendIq(entity, success_fn, error_fn)
         else:
             message_entity = TextMessageProtocolEntity(message, to=jid)
             self.ackQueue.append(message_entity.getId())
             self.toLower(message_entity)
     self.lock.release()
示例#45
0
    def send_msg(self, **kwargs):
        """Send a message.

        Arguments:
            phone (str): Phone to send the message to.
            message (str): Message to send
        """
        phone = kwargs.get('phone')
        toStr = ""

        if not phone:
            # Nothing to do
            logger.debug('no phone provided')
            return

        if phone.find("-") > -1:
            toStr = phone + "@g.us"
        else:
            toStr = phone + "@s.whatsapp.net"

        message = kwargs.get('message').encode('utf8')

        entity = TextMessageProtocolEntity(message, to=toStr)

        # self.ackQueue.append(entity.getId())
        self.toLower(entity)
示例#46
0
    def onMessage(self, messageProtocolEntity):

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

            namemitt = messageProtocolEntity.getNotify()
            recipient = messageProtocolEntity.getFrom()
            message = messageProtocolEntity.getBody().lower()

            reply = construct_reply(recipient, message)

            if not reply:
                if message.startswith("hello"):
                    reply = "Hi " + namemitt

                else:
                    reply = rude_chatbot.respond(message)

            resp = TextMessageProtocolEntity(reply, to=recipient)
            self.toLower(resp)

            self.toLower(messageProtocolEntity.ack())
            time.sleep(0.5)
            self.toLower(messageProtocolEntity.ack(True))

        else:
            print("foo")
示例#47
0
 def test(self, message, match):
     # Gets a random quiz and store in the sender' session
     number = random.randint(0, 100)
     self.session_db.set(message.getFrom(), number)
     return TextMessageProtocolEntity("You Have Stored the Number " +
                                      str(number),
                                      to=message.getFrom())
示例#48
0
 def on_success(self, success_protocol_entity):
     self.lock.acquire()
     for target in self.getProp(self.__class__.PROP_MESSAGES, []):
         phone, message, is_media = target
         jid = "*****@*****.**" % phone
         if is_media:
             path = message
             entity = self.get_upload_entity(path)
             success_fn = lambda success, original: self.on_request_upload_result(jid, path, success, original)
             error_fn = lambda error, original: self.on_request_upload_error(jid, path, error, original)
             self._sendIq(entity, success_fn, error_fn)
         else:
             message_entity = TextMessageProtocolEntity(message, to=jid)
             self.ackQueue.append(message_entity.getId())
             self.toLower(message_entity)
     self.lock.release()
示例#49
0
def PTNode_to_TUMessage(node, to_addr):
    '''
    node is ProtocolTreeNode
    returns TransportUserMessage
    '''
    message = TextMessageProtocolEntity.fromProtocolTreeNode(node)
    return TransportUserMessage(
        to_addr=to_addr, from_addr="+" + message.getFrom(False),
        content=message.getBody().decode("UTF-8"), transport_name='whatsapp',
        transport_type='whatsapp')
    def process_message(self, peer, mailfrom, rcpttos, data):
        m = Parser().parsestr(data)
        print "<= Mail: %s -> %s" % (mailfrom, rcpttos)

        try:
            txt = mail_to_txt(m)
            if args.debug:
                print "! mail_to_txt: {%s}" % (txt)
        except Exception as e:
            return "501 malformed content: %s" % (str(e))

        for dst in rcpttos:
            try:
                (phone,) = parse(config.get('reply'), dst)
            except TypeError:
                print "malformed dst: %s" % (dst)
                return "501 malformed recipient: %s" % (dst)

            jid = normalizeJid(phone)

            # send text, if any
            if len(txt.strip()) > 0:
                msg = TextMessageProtocolEntity(txt, to = jid)
                print "=> WhatsApp: -> %s" % (jid)
                if not args.dry:
                    self._yowsup.toLower(msg)
                if args.debug:
                    print "! Message: {%s}" % (txt)
                    print "! from entity: {%s}" % (msg.getBody())

            # send media that were attached pieces
            if m.is_multipart():
                for pl in getattr(m, '_payload', []):
                    self.handle_forward_media(jid, pl)
                    if args.debug:
                        print "! Attachement: %s" % (pl)