tgalal / yowsup

The WhatsApp lib
GNU General Public License v3.0
7.05k stars 2.23k forks source link

Have a Problem using Yowsup with simple application! #1707

Closed Elklund closed 8 years ago

Elklund commented 8 years ago

I have a big problem to run this Code. I copied it from the original Code/Page and it puts out some error Messages!! That's not good, please help me...

layer.py

from yowsup.layers.interface                           import YowInterfaceLayer, ProtocolEntityCallback
from yowsup.layers.protocol_messages.protocolentities  import TextMessageProtocolEntity
from yowsup.layers.protocol_receipts.protocolentities  import OutgoingReceiptProtocolEntity
from yowsup.layers.protocol_acks.protocolentities      import OutgoingAckProtocolEntity

class EchoLayer(YowInterfaceLayer):

    @ProtocolEntityCallback("message")
    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)

    @ProtocolEntityCallback("receipt")
    def onReceipt(self, entity):
        ack = OutgoingAckProtocolEntity(entity.getId(), "receipt", entity.getType(), entity.getFrom())
        self.toLower(ack)

layer.py isn't the original. I copied it from here: https://github.com/tgalal/yowsup/issues/1611 run.py

from yowsup.stacks import  YowStackBuilder
from layer import EchoLayer
from yowsup.layers.auth import AuthError
from yowsup.layers import YowLayerEvent
from yowsup.layers.network import YowNetworkLayer
from yowsup.env                                import YowsupEnv

credentials = ("phone", "password") # replace with your phone and password
#CREDENTIALS = DemosArgParser._getCredentials()

if __name__==  "__main__":
    stackBuilder = YowStackBuilder()

    stack = stackBuilder\
        .pushDefaultLayers(True)\
        .push(EchoLayer)\
        .build()

    stack.setCredentials(credentials)
    stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))   #sending the connect signal
    stack.loop() #this is the program mainloop

It puts out these error message:

Traceback (most recent call last):
  File "run.py", line 13, in <module>
    from yowsup.layers.axolotl                     import YowAxolotlLayer
ImportError: cannot import name YowAxolotlLayer

How can I fix that?


Acutually I tried to solve the problem. Deleting YowAxolotLayer from Script. But the it puts out this:

Traceback (most recent call last):
  File "run.py", line 34, in <module>
    stack.loop() #this is the program mainloop
  File "/home/pi/yowsup/yowsup/stacks/yowstack.py", line 196, in loop
    asyncore.loop(*args, **kwargs)
  File "/usr/lib/python2.7/asyncore.py", line 216, in loop
    poll_fun(timeout, map)
  File "/usr/lib/python2.7/asyncore.py", line 156, in poll
    read(obj)
  File "/usr/lib/python2.7/asyncore.py", line 87, in read
    obj.handle_error()
  File "/usr/lib/python2.7/asyncore.py", line 83, in read
    obj.handle_read_event()
  File "/usr/lib/python2.7/asyncore.py", line 449, in handle_read_event
    self.handle_read()
  File "/home/pi/yowsup/yowsup/layers/network/layer.py", line 102, in handle_read
    self.receive(data)
  File "/home/pi/yowsup/yowsup/layers/network/layer.py", line 110, in receive
    self.toUpper(data)
  File "/home/pi/yowsup/yowsup/layers/__init__.py", line 76, in toUpper
    self.__upper.receive(data)
  File "/home/pi/yowsup/yowsup/layers/stanzaregulator/layer.py", line 29, in receive
    self.processReceived()
  File "/home/pi/yowsup/yowsup/layers/stanzaregulator/layer.py", line 49, in processReceived
    self.toUpper(oneMessageData)
  File "/home/pi/yowsup/yowsup/layers/__init__.py", line 76, in toUpper
    self.__upper.receive(data)
  File "/home/pi/yowsup/yowsup/layers/auth/layer_crypt.py", line 65, in receive
    self.toUpper(payload)
  File "/home/pi/yowsup/yowsup/layers/__init__.py", line 76, in toUpper
    self.__upper.receive(data)
  File "/home/pi/yowsup/yowsup/layers/coder/layer.py", line 35, in receive
    self.toUpper(node)
  File "/home/pi/yowsup/yowsup/layers/__init__.py", line 76, in toUpper
    self.__upper.receive(data)
  File "/home/pi/yowsup/yowsup/layers/logger/layer.py", line 14, in receive
    self.toUpper(data)
  File "/home/pi/yowsup/yowsup/layers/__init__.py", line 76, in toUpper
    self.__upper.receive(data)
  File "/home/pi/yowsup/yowsup/layers/__init__.py", line 189, in receive
    s.receive(data)
  File "/home/pi/yowsup/yowsup/layers/__init__.py", line 125, in receive
    recv(node)
  File "/home/pi/yowsup/yowsup/layers/protocol_messages/layer.py", line 20, in recvMessageStanza
    entity = TextMessageProtocolEntity.fromProtocolTreeNode(node)
  File "/home/pi/yowsup/yowsup/layers/protocol_messages/protocolentities/message_text.py", line 38, in fromProtocolTreeNode
    entity.setBody(node.getChild("body").getData())
AttributeError: 'NoneType' object has no attribute 'getData'

Too much error Messages :(

jlguardi commented 8 years ago

Use run.py from https://github.com/tgalal/yowsup/blob/master/yowsup/demos/echoclient/stack.py

Elklund commented 8 years ago

@jlguardi One step further...But there comes this problem:

Traceback (most recent call last):
  File "run.py", line 2, in <module>
    from .layer import EchoLayer
ValueError: Attempted relative import in non-package

Your Code:

import logging
logging.basicConfig(level=logging.DEBUG)

from yowsup.stacks import  YowStackBuilder
from .layer import EchoLayer
from yowsup.layers.auth import AuthError
from yowsup.layers import YowLayerEvent
from yowsup.layers.network import YowNetworkLayer

class YowsupEchoStack(object):
    def __init__(self, credentials, encryptionEnabled = True):
        stackBuilder = YowStackBuilder()

        self.stack = stackBuilder\
            .pushDefaultLayers(encryptionEnabled)\
            .push(EchoLayer)\
            .build()

        self.stack.setCredentials(credentials)

    def start(self):
        self.stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
        try:
            self.stack.loop()
        except AuthError as e:
            print("Authentication Error: %s" % e.message)

How can I fix that? Is there a problem with my layer.py?

Also I updated the Code for home automation:

layer.py

# -*- coding: utf-8 -*-
import os, subprocess, time
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
from yowsup.layers                                     import YowLayer
from yowsup.layers.interface                           import YowInterfaceLayer, ProtocolEntityCallback
from yowsup.layers.protocol_messages.protocolentities  import TextMessageProtocolEntity
from yowsup.layers.protocol_receipts.protocolentities  import OutgoingReceiptProtocolEntity
from yowsup.layers.protocol_acks.protocolentities      import OutgoingAckProtocolEntity

allowedPersons=[000000000000000','NUMBER_ALLOWED2','NUMBER_ALLOWED3','NUMBER_ALLOWED4']
ap = set(allowedPersons)

class EchoLayer(YowInterfaceLayer):
    @ProtocolEntityCallback("message")
    def onMessage(self, messageProtocolEntity):
                if messageProtocolEntity.getType() == 'text':
                        self.onTextMessage(messageProtocolEntity)

    @ProtocolEntityCallback("receipt")
    def onReceipt(self, entity):
        ack = OutgoingAckProtocolEntity(entity.getId(), "receipt", "delivery")
        self.toLower(ack)

    def onTextMessage(self, messageProtocolEntity):
                receipt = OutgoingReceiptProtocolEntity(messageProtocolEntity.getId(), messageProtocolEntity.getFrom())

                if messageProtocolEntity.getFrom(False) in ap:
                        if 'Hi' in messageProtocolEntity.getBody():
                                antwort = 'Hello!'
                                self.toLower(receipt)
                                self.toLower(TextMessageProtocolEntity(antwort, to = messageProtocolEntity.getFrom()))
                        elif 'hi' in messageProtocolEntity.getBody():
                                antwort = 'Hello!'
                                self.toLower(receipt)
                                self.toLower(TextMessageProtocolEntity(antwort, to = messageProtocolEntity.getFrom()))
                        elif 'Temperature' in messageProtocolEntity.getBody():
                                 t=float(subprocess.check_output(["/opt/vc/bin/vcgencmd measure_temp | cut -c6-9"], shell=True)[:-1])
                                 ts=str(t)
                                 antwort = 'My temperature is  '+ts+' °C.'
                                 self.toLower(receipt)
                                 self.toLower(TextMessageProtocolEntity(antwort, to = messageProtocolEntity.getFrom()))
                        elif 'temperatura' in messageProtocolEntity.getBody():
                                 t=float(subprocess.check_output(["/opt/vc/bin/vcgencmd measure_temp | cut -c6-9"], shell=True)[:-1])
                                 ts=str(t)
                                 antwort = 'My temperature is '+ts+' °C.'
                                 self.toLower(receipt)
                                 self.toLower(TextMessageProtocolEntity(antwort, to = messageProtocolEntity.getFrom()))
                        elif 'Open' in messageProtocolEntity.getBody():      #open the door :D
                                 GPIO.setmode(GPIO.BCM)
                                 GPIO.setup(2, GPIO.OUT)
                                 GPIO.output(2, GPIO.LOW)
                                 time.sleep(0.5)
                                 GPIO.cleanup()
                                 antwort = 'Cancello aperto!'
self.toLower(receipt)
                                 self.toLower(TextMessageProtocolEntity(antwort, to = messageProtocolEntity.getFrom()))
                        elif 'open' in messageProtocolEntity.getBody():      #open the door :D
                                 GPIO.setmode(GPIO.BCM)
                                 GPIO.setup(2, GPIO.OUT)
                                 GPIO.output(2, GPIO.LOW)
                                 time.sleep(0.5)
                                 GPIO.cleanup()
                                 antwort = 'Cancello aperto!'
                                 self.toLower(receipt)
                                 self.toLower(TextMessageProtocolEntity(antwort, to = messageProtocolEntity.getFrom()))
                        else:
                                antwort = 'I dont understood.'
                                self.toLower(receipt)
                                self.toLower(TextMessageProtocolEntity(antwort, to = messageProtocolEntity.getFrom()))
                else:
                        antwort = 'You arent a valid sender.'
                        self.toLower(receipt)
                        self.toLower(TextMessageProtocolEntity(antwort, to = messageProtocolEntity.getFrom()))

It doesn't works yet. But why? Do you have a solution? Do I have to authentificate my number via run.py?

sowerkoku commented 8 years ago

There is a similar project here.

Elklund commented 8 years ago

Thanks. But there is an IdentationError:

run.py

from yowsup.stacks import YowStackBuilder
from yowsup.common import YowConstants
from yowsup.layers import YowLayerEvent
from layer import EchoLayer
from yowsup.layers.auth import YowAuthenticationProtocolLayer
from yowsup.layers.coder import YowCoderLayer
from yowsup.layers.network import YowNetworkLayer
from yowsup.env import YowsupEnv
#Uncomment to log import logging logging.basicConfig(level=logging.DEBUG)
CREDENTIALS = ("491634597567", "OQW5QeBwRBO/EqA/+FvWLUw+iSM=") #replace with your phone and password if __name__== "__main__":
    stackBuilder = YowStackBuilder()

    stack = stackBuilder\
        .pushDefaultLayers(True)\
        .push(EchoLayer)\
        .build()

    stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, CREDENTIALS) #setting credentials
    stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT)) #sending the connect signal
    stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0]) #whatsapp server address
    stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
    stack.setProp(YowCoderLayer.PROP_RESOURCE, YowsupEnv.getCurrent().getResource()) #info about us as WhatsApp client
    stack.loop( timeout = 0.5, discrete = 0.5 )     

When I run that it puts out this message:

  File "run.py", line 11
    stackBuilder = YowStackBuilder()
    ^
IndentationError: unexpected indent

Is it because I have only copied the content of the files? And not copied the files?

Elklund commented 8 years ago

OK. I fixed the IdentationError. Thank you very much :)