Playing with Yowsup-cli 2.0 – Receive messages and do stuff

Hello geek people that  read these post, I bring a super post compared to Pandora’s box, well the truth that comparison with the Pandora’s box is just to give drama. But this post veeeeery be useful.

First of all, Yowsup is a Python library that allows developing applications to use the services and benefits of WhatsApp. If clone the github repo Repo Yowsup and install all its dependencies you can use a customer WhatsApp for Cli pretty good in his shows include the option of sending messages, Echo messages and other things.

Had already previously worked with Yowsup , but stop using it because of the change of architecture Whatsapp thank God included End to End encryption. A few days ago I have the task of performing a system for notifications and then WhatsApp uses worldwide, at least here in Mexico all cellular companies offer it free or by buying credit per month, so I felt good choice Whatsapp used as a means to send alerts and use Yowsup. You can also do with Pushbullet , but that’s another story and another post in the future.

Well, get to work, first of all we have to clone the repo Yowsup

git clone https://github.com/tgalal/yowsup.git

We supply a few depencias and packages necessary to correctly start Yowsup.

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install python-dateutil
sudo apt-get install python-setuptools
sudo apt-get install python-dev
sudo apt-get install libevent-dev
sudo apt-get install ncurses-dev

We must have a cell phone number available to register it in WhatsApp, and remember that we can not use WhatsApp on different devices -.- ‘.

Inside the directory where we have downloaded Yowsup we must run the following command to install yowsup.

sudo python setup.py install

With this we will have yowsup-cli as one command more linux, located in /usr/local/bin/yowsup-cli. Proceed to register our number on Whatsapp.

yowsup-cli registration –requestcode sms –phone 521xxxxxxxxxx –cc 52 –mcc 334 –mnc 030
yowsup-cli registration –register xxx-xxx –phone 521xxxxxxxxxx –cc 52

With this we will have Whatsapp for our mobile number password. We can save our data configuration in a file like the following example and name it as we want.

#############

cc=52
phone=521
password=

#######

And we can try sending a message to a number of Whatsapp with the following command

yowsup-cli demos –config yowsup/whatsapp_config.txt –send 5219999999999 “Your Butt”

Until this part all well, we can make a maaaaaany of things like notificaiones, alerts etc, buuuuutt putting hand python really will have a range of possibilities 😀

Whatsapp client to receive and execute Linux commands

If we are curious can see that Yowsup comes with several demos and one very important is the EchoClient, which when we run it, we can send a message to Whatsapp to the number that we are using with Yowsup. We will create a new folder inside the folder demos and call readclient.

folder

Well the code that we will make our client will be used in the demo EchoClient but we will modify it a little.

ReadClient-Yowsup

The code is as follows:


import os
from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback

class ReadEchoLayer(YowInterfaceLayer):

@ProtocolEntityCallback(“message”)
def onMessage(self, messageProtocolEntity):

if messageProtocolEntity.getType() == ‘text’:
self.onTextMessage(messageProtocolEntity)
elif messageProtocolEntity.getType() == ‘media’:
self.onMediaMessage(messageProtocolEntity)

self.toLower(messageProtocolEntity.ack())
self.toLower(messageProtocolEntity.ack(True))

@ProtocolEntityCallback(“receipt”)
def onReceipt(self, entity):
self.toLower(entity.ack())

def onTextMessage(self,messageProtocolEntity):
# just print info
print(“Llego el mensaje %s” % (messageProtocolEntity.getBody()))
os.system(“notify-send ‘Mensaje de Whatsapp’ ‘{mensje}'”.format(mensje=messageProtocolEntity.getBody()))
os.system(“espeak -ves ‘%s'” % (messageProtocolEntity.getBody()))

def onMediaMessage(self, messageProtocolEntity):
# just print info
if messageProtocolEntity.getMediaType() == “image”:
print(“Echoing image %s to %s” % (messageProtocolEntity.url, messageProtocolEntity.getFrom(False)))

elif messageProtocolEntity.getMediaType() == “location”:
print(“Echoing location (%s, %s) to %s” % (messageProtocolEntity.getLatitude(), messageProtocolEntity.getLongitude(), messageProtocolEntity.getFrom(False)))

elif messageProtocolEntity.getMediaType() == “vcard”:
print(“Echoing vcard (%s, %s) to %s” % (messageProtocolEntity.getName(), messageProtocolEntity.getCardData(), messageProtocolEntity.getFrom(False)))

As shown in the code do an import os to run linux commands from python:D. In the original example of EchoClient contains the line

self.toLower(messageProtocolEntity.forward(messageProtocolEntity.getFrom()))

For purposes of our client we will erase that line, since this is the order forwardar to the message he received the customer.

Modify the onTextMessage function and it will be in the following way

onTestMessage

Where the first line prints the screen a message rimmed the contents of the message that came, in the second line, run the function os.system () and we have to pass the linux command to execute, in this case notify-send to launch a notification on your desktop.

TestMensaje

The third line also runs the function os.system () which for a command as a parameter so the console talk, a type loquendo, but we passed the content that I get Whatsapp message so that the system reads it, a Jarvis type;).

It’s alive alive !!!!!

Vídeo demo.

Well, this can be many things, a brilliant implementation would be tcp over Whatsapp to have a proxy anywhere :D. I hope you make it useful :D.

 

17 comentarios en “Playing with Yowsup-cli 2.0 – Receive messages and do stuff

  1. Hi Rafa,

    Very cool your last post using yowsup 2.0. I am not expert on python, but can u explain me a simple tutorial to create a new demo (such as readclient) and invoke with a comman-line (like in ur post yowsip … -f )

    I have modified my layer.py in te readclient folder and in the echoclient folder and nothing happens.

    I suspect tha i am missing to rebuild the proyect but i dont know how to. I would appreciete any feedback you can deliver

    1. Hi Juan, Thanks for read and comment this post.

      I think you’re right, I missed to include the part where this new demo is added to the start menu and recompiling.

      I miss the part where re adds the new demo to the file yowsup-cli in the class DemosArgParser add.

      When I have time I’ll update this post

  2. Hi,
    Sorry to be so impatient, but i have to solve this for mi company as soon as possible.

    I do not need a very extensive explanation, i have been trying to change the code by myself and I only to need to know if i am doing correctly.

    I have modified the file yowsup-cli, the class DemosArgParser acording to my knowledge, and i have invoke the command python setup.py again.

    So..two little questions Is there any other file i have to change?.. and which would be the perfect procedure to recompile the code?

    I would be very pleased if you can find time and answer these two questions.

    Thanks

    1. def startSyncContacts(self):
      from yowsup.demos import contacts
      credentials = self._getCredentials()
      if not credentials:
      print(“Error: You must specify a configuration method”)
      sys.exit(1)
      try:
      stack = contacts.YowsupSyncStack(credentials,self.args[“sync”].split(‘,’), not self.args[“unmoxie”])
      stack.start()
      except KeyboardInterrupt:
      print(“\nYowsdown”)
      sys.exit(0)

      def readMessage(self):
      from yowsup.demos import readmessages
      credentials = self._getCredentials()
      if not credentials:
      print(“Error: You must specify a configuration method”)
      sys.exit(1)
      try:
      stack = readmessages.YowsupEchoStack(credentials, not self.args[“unmoxie”])
      stack.start()
      except KeyboardInterrupt:
      print(“\nPROCESO TERMINA”)
      sys.exit(0)

    2. syncContacts = self.add_argument_group(“Sync contacts”)
      syncContacts.add_argument(‘-S’,’–sync’, action = “store” , help = “Sync ( check valid ) whatsapp contacts”,metavar =(“contacts”))

      readmessOpts = self.add_argument_group(“readmess client exec”)
      readmessOpts.add_argument(‘-f’, ‘–readmess’, action = “store_true”, help = “Start the Yowsup Echo client”)

      1. Jose Todo eso que comentaste que es? yo estoy tratando de hacer que el Yowsup reciba mensajes. cosa que todavia no he podido. solamente logro enviar mensajes de txt. necesito 1er lograr recibir texto y luego mi 2nd paso seria poder hacer que envie imagenes o videos. podrias ayudarme en algo

  3. RAFA necesito ayuda no me funciona el ejemplo podrias porfavor explicar lo que hace falta?

    RAFA i need your help please. the example not working fine. can you explain me better.

  4. Nice work Raffa! I’m using the EchoClient to pipe incoming messages out to a file, then STDIN to a bash script which feeds it via JQuery/JSON to a ridiculously argumentative/aggressive AMIL python chatbox I’m hosting on my local server. The chatbot’s responses are then fed back through J/bash to the person who sent the yowsup message via yowsup CLi-demo. the result thus far are HILLARIOUS. Oh and yes person that asked still woking in 2017…

Deja una respuesta:

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión /  Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s