Saltar al contenido
Underc0de /foro

WhatsApp Bot in Python

🌐 This is an automatic translation of a topic from Underc0de, the largest Spanish-speaking hacking and IT community. Read the original (Spanish) and reply →
ANTRAX ·
Los enlaces son solo para miembros. Registrate o iniciá sesión
<br /><br />Hi, I wanted to share a project I've had for a while related to WhatsApp. Lately it's getting really difficult because of the blocks and the updates WhatsApp releases to fight this, plus it doesn't have an API. The ones that were created or exist unofficially are having problems.<br /><br />Some time ago, APIs for WhatsApp appeared on GitHub. One of the first I used was WhatsAPI, later called Los enlaces son solo para miembros. Registrate o iniciá sesión, which is in PHP. If I'm not mistaken, it was the first one to come out. Based on it, its Python equivalent was created, called Los enlaces son solo para miembros. Registrate o iniciá sesión.<br /><br />To use this API, you first have to install it, then we use its classes in Python.<br /><br />The code I'm going to share is basic. It replies based on some keywords, and it also includes some page scrapers, one of them is Los enlaces son solo para miembros. Registrate o iniciá sesión. It also has an inpres monitor that has certain parameters defined to send alerts. In the new work I'm doing, I'm trying to implement Los enlaces son solo para miembros. Registrate o iniciá sesión as the response engine.<br /><br />Let's start, first install the API.<br /><br />
Código: bash
git clone https://github.com/tgalal/yowsup.git
<br /><br />Go to the env folder and edit the file Los enlaces son solo para miembros. Registrate o iniciá sesión. On GitHub it isn't updated yet, I don't know why, but it doesn't have the correct values and it breaks because of the token, so if you don't edit it you won't be able to use the API. Los enlaces son solo para miembros. Registrate o iniciá sesión.<br /><br />Here are the correct tokens<br /><br />Los enlaces son solo para miembros. Registrate o iniciá sesión<br /><br />Edit the variables in that file<br /><br />
Código: text
_VERSION = "2.16.9"<br /><br />_TOKEN_STRING = "PdA2DJyKoUrwLw1Bg6EIhzh502dF9noR9uFCllGk1471306425030{phone}"
<br /><br />To<br /><br />
Código: text
_VERSION = "2.16.11"<br /><br />_TOKEN_STRING = "PdA2DJyKoUrwLw1Bg6EIhzh502dF9noR9uFCllGk1478194306452{phone}"
<br /><br />And with this it should work, now we need to build it again.<br /><br />
Código: bash
sudo python setup.py build
<br /><br />Install<br /><br />
Código: bash
sudo python setup.py install
<br /><br />I recommend buying a disposable or prepaid SIM to register on WhatsApp and use the API, because of the blocks, we don't want to lose our line on WhatsApp.<br /><br />We proceed to register our line, all of it from Los enlaces son solo para miembros. Registrate o iniciá sesión. The goal is to register and get the key that is encoded in base64.<br /><br />We request the OTP<br /><br />
Código: bash
yowsup-cli registration --requestcode sms --phone 549XXXXXXXXXX --cc 54 --mcc 722 --mnc XX
<br /><br />mcc and mnc by country<br /><br />Los enlaces son solo para miembros. Registrate o iniciá sesión<br /><br />Example<br /><br />
Código: bash
yowsup-cli registration --requestcode sms --phone 5493804651130 --cc 54 --mcc 722 --mnc 341
<br /><br />It should show status: sent<br />mcc 722 corresponds to ARG<br />mnc 341 corresponds to PERSONAL<br /><br />Before requesting the OTP, put the SIM in any phone, we only care about the SMS with the activation code.<br />Once it arrives<br /><br />
Código: bash
yowsup-cli registration --register XXXXX --phone 549XXXXXXXXXX --cc 54 -d
<br /><br />Example:<br /><br />
Código: bash
yowsup-cli registration --register 542301 --phone 5493804651130 --cc 54 -d
<br /><br />If everything goes well, it will return the key.<br />Now we create a file with the configuration or credentials.<br /><br />
Código: bash
nano 5493804651130.cfg
<br /><br />Inside it<br /><br />cc=54<br />phone=549XXXXXXX<br />id=549XXXXXXX<br />password=b64pw<br /><br />Example<br /><br />cc=54<br />phone=5493804651130<br />id=5493804651130<br />password=m+S232dtFUfghljjKS12325pZmNELasdas=<br /><br />Let's test everything in the cli.<br /><br />
Código: bash
yowsup-cli demos -c 5493804651130.cfg -e
<br /><br />-c = configuration file created earlier<br />-e = echo mode.<br /><br />Echo mode replies to everything we send it.<br /><br />Now let's try sending a WhatsApp that says hello world to that number, it should reply with hello world.<br /><br />If everything goes well, we're ready to use the script.<br /><br />DOWNLOAD CODE: Los enlaces son solo para miembros. Registrate o iniciá sesión<br /><br />Edit the CREDENTIALS array with your data in run.py<br /><br />
Código: python
#!/usr/bin/python<br /># -*- coding: utf-8 -*-<br />from yowsup.stacks                             import YowStackBuilder<br />from yowsup.common                             import YowConstants<br />from yowsup.layers                             import YowLayerEvent<br />from layer                                     import EchoLayer<br />from yowsup.layers.auth                        import YowAuthenticationProtocolLayer<br />from yowsup.layers.coder                       import YowCoderLayer<br />from yowsup.layers.network                     import YowNetworkLayer<br />from yowsup.env                                import YowsupEnv<br />from scrapers.inpres                           import SCinpres<br />import threading, os, subprocess, time, sys<br /> <br />CREDENTIALS = ("549XXXXXXXXX", "pwB64")<br />laye = EchoLayer()<br /> <br />def workerinpress():<br />	inpre = SCinpres()<br />	print "Monitor inpres start\n"<br />	while (True):<br />		al = inpre.monitor()<br />		if (al and al.strip() and al !='Error en consulta'):<br />			print al<br />			laye.envialertainpres(al)<br />		time.sleep(1)<br /> <br />def workerwhatsapp():<br />	stackBuilder = YowStackBuilder()<br />	stack = stackBuilder.pushDefaultLayers(True).push(laye).build()<br />	stack.setCredentials(CREDENTIALS)<br />	stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))<br />	stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])<br />	stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)<br />	stack.setProp(YowCoderLayer.PROP_RESOURCE, YowsupEnv.getCurrent().getResource())<br />	stack.loop( timeout = 0.5, discrete = 0.5 )<br /> <br />if __name__==  "__main__":<br />	threads = list()<br />	moninp = threading.Thread(target=workerinpress)<br />	threads.append(moninp)<br />	wasa = threading.Thread(target=workerwhatsapp)<br />	threads.append(wasa)<br />	moninp.start()<br />	wasa.start()
<br /><br />In layer.py edit<br /><br />permitidos=['5493834621141′,'5493834654414']   #Add the numbers you want to reply to only<br /><br />name = "Bort" #user name<br />ALERTAN = ("[email protected]")  #number to which we want to send the inpres alerts<br /><br />
Código: python
#!/usr/bin/python<br /># -*- coding: utf-8 -*-<br />import os, subprocess, time, sys<br />from sys import exit<br />from yowsup.layers.interface                           import YowInterfaceLayer,ProtocolEntityCallback     <br />import mimetypes<br />from yowsup.layers.protocol_messages.protocolentities  import TextMessageProtocolEntity  <br />from yowsup.layers.protocol_presence.protocolentities  import AvailablePresenceProtocolEntity   <br />from yowsup.layers.protocol_presence.protocolentities  import UnavailablePresenceProtocolEntity <br />from yowsup.layers.protocol_presence.protocolentities  import PresenceProtocolEntity            <br />from yowsup.layers.protocol_chatstate.protocolentities import OutgoingChatstateProtocolEntity   <br />from yowsup.common.tools                               import Jid<br />from yowsup.layers.protocol_media.mediadownloader      import MediaDownloader<br />from yowsup.layers.protocol_media.protocolentities     import *<br />from respuesta                                     	   import Respuesta                              <br />import sys, shutil<br /> <br />permitidos=['5493834621141']<br />ac = set(permitidos)<br /> <br />name = "Bort"<br />ALERTAN = ("[email protected]")<br /> <br />class EchoLayer(YowInterfaceLayer):<br /> <br />	@ProtocolEntityCallback("message")<br />	def envialertainpres(self, al):<br />		self.toLower(AvailablePresenceProtocolEntity())<br />		time.sleep(0.5)<br />		self.toLower(PresenceProtocolEntity(name = name))#Set presence<br />		time.sleep(0.5)<br />		textmsg = TextMessageProtocolEntity<br />		for tel in ALERTAN:<br />			self.toLower(textmsg(al, to = tel))<br />			time.sleep(0.4)<br />		time.sleep(1)<br />		self.toLower(UnavailablePresenceProtocolEntity())#Set offline<br /> <br />	@ProtocolEntityCallback("message")<br />	def onMessage(self, messageProtocolEntity):<br />		if messageProtocolEntity.getType() == 'text':<br />			time.sleep(0.5)<br />			self.toLower(messageProtocolEntity.ack())#Set seen<br />			time.sleep(0.5)<br />			self.toLower(AvailablePresenceProtocolEntity())<br />			time.sleep(0.5)<br />			self.toLower(PresenceProtocolEntity(name = name))#Set presence<br />			time.sleep(0.5)<br />			self.toLower(messageProtocolEntity.ack(True))#Set double seen<br />			time.sleep(0.5)<br />			self.toLower(OutgoingChatstateProtocolEntity(OutgoingChatstateProtocolEntity.STATE_TYPING, Jid.normalize(messageProtocolEntity.getFrom(False))))#Set typing<br />			time.sleep(1)<br />			self.onTextMessage(messageProtocolEntity)#send the reply<br />			time.sleep(0.5)<br />			self.toLower(OutgoingChatstateProtocolEntity(OutgoingChatstateProtocolEntity.STATE_PAUSED, Jid.normalize(messageProtocolEntity.getFrom(False))))#Set paused<br />			time.sleep(1)<br />			self.toLower(UnavailablePresenceProtocolEntity())#Set offline<br />		elif messageProtocolEntity.getType() == 'media':<br />			time.sleep(0.5)<br />			self.toLower(AvailablePresenceProtocolEntity())<br />			time.sleep(0.5)<br />			self.toLower(PresenceProtocolEntity(name = name))#Set presence<br />			#self.onMediaMessage(messageProtocolEntity)<br />			self.toLower(messageProtocolEntity.ack())<br />			self.toLower(messageProtocolEntity.ack(True))<br />			time.sleep(1)<br />			self.toLower(UnavailablePresenceProtocolEntity())#Set offline<br />		else:<br />			pass<br /> <br />	@ProtocolEntityCallback("receipt")<br />	def onReceipt(self, entity):<br />		print entity.ack()<br />		self.toLower(entity.ack())<br /> <br />	def onTextMessage(self,messageProtocolEntity):<br />		namemitt   = messageProtocolEntity.getNotify()<br />		message    = messageProtocolEntity.getBody()<br />		recipient  = messageProtocolEntity.getFrom()<br />		textmsg    = TextMessageProtocolEntity<br />		if messageProtocolEntity.getFrom(False) in ac:<br />			resp = Respuesta()<br />			answer = resp.obtener(message,namemitt,recipient)<br />			if answer and answer.strip():<br />				if recipient.lower().find("-") == -1:<br />					self.toLower(textmsg(answer, to = recipient ))<br />					print answer+"\n Personal"<br />				else:<br />					self.toLower(textmsg(answer, to = recipient ))<br />					print answer+"\n Group"<br />		else:<br />			answer = "Hello "+namemitt+", you are not on the reply list\n"<br />			print recipient + "\n"<br />			print message + "\n"<br />			if recipient.lower().find("-") == -1:<br />				time.sleep(1)<br />				self.toLower(textmsg(answer, to = recipient))<br />				print answer<br />			else:<br />				print answer<br /> <br />	def onMediaMessage(self, messageProtocolEntity):<br />		if messageProtocolEntity.getFrom(False) in ac:<br />			if messageProtocolEntity.getMediaType() == "image":<br />				url = messageProtocolEntity.url<br />				self.extension = self.getExtension(messageProtocolEntity.getMimeType())<br />				return self.downloadMedia(url)<br /> <br />	def downloadMedia(self, url):<br />		print("Downloading %s" % url)<br />		downloader = MediaDownloader(self.onSuccess, self.onError, self.onProgress)<br />		downloader.download(url)<br /> <br />	def onError(self):<br />		print "Error downloading file"<br /> <br />	def onSuccess(self, path):<br />		outPath = "/home/yowsup/imgs/%s%s" % (os.path.basename(path), self.extension)<br />		shutil.copyfile(path, outPath)<br />		print("\nImage downloaded to %s" % outPath)<br /> <br />	def onProgress(self, progress):<br />		sys.stdout.write("Download progress => %d%% \r" % progress)<br />		sys.stdout.flush()<br /> <br />	def getExtension(self, mimetype):<br />		type = mimetypes.guess_extension(mimetype.split(';')[0])<br />		if type is None:<br />			raise Exception("Unsupported/unrecognized mimetype: "+mimetype);<br />		return type
<br /><br />Finally, inside scrapers in inpres.py, edit as you like<br /><br />provincias = ['CATAMARCA','LA RIOJA','CORDOBA']#The provinces that matter<br />mgtmax= 4.3 #equal or greater earthquake magnitude for which the alert is sent to the defined number<br /><br />
Código: python
#!/usr/bin/python<br /># -*- coding: utf-8 -*-<br /> <br />import urllib2<br />import datetime<br />import time<br />from bs4 import BeautifulSoup<br />from controladores import Cinpresdb<br /> <br />class SCinpres:<br /> <br />    def __init__(self):<br />        pass<br /> <br />    def extraer(self):<br />		url = 'http://www.inpres.gov.ar/desktop/'<br />		formateado = ''<br />		try:<br />			respuesta = urllib2.urlopen(url)<br />			datos = respuesta.read().decode('utf-8')<br />			scrapsismo = BeautifulSoup(datos, "lxml")<br />			tabla = scrapsismo.find("table", {"id" : "sismos"})<br />			formateado = ''<br />			registros = tabla.find_all('tr')<br />			cantidadr = len(registros)<br />			i=0<br />			for reg in registros:<br />				if (i>1 and i<cantidadr-3):<br />					sctd = BeautifulSoup(str(reg), "lxml")<br />					tds = sctd.find_all('td')<br />					fecha = tds[1].text<br />					hora = tds[2].text<br />					mntud = tds[4].text<br />					lugar = tds[7].text<br />					formateado = formateado+"Fecha: "+fecha+" H: "+hora+" magnitud: "+mntud+" lugar: "+lugar+ "\n"<br />				i += 1<br />		except:<br />			formateado = 'Error en consulta'<br />		return formateado<br /> <br />    def monitor(self):<br />		url = 'http://www.inpres.gov.ar/desktop/'<br />		provincias = ['CATAMARCA','LA RIOJA','CORDOBA']<br />		mgtmax= 4.3<br />		hoyhora = datetime.datetime.now()<br />		controlador = Cinpresdb()<br />		i=0<br />		tdin=0<br />		ale=False<br />		formateado = ''<br />		try:<br />			respuesta = urllib2.urlopen(url)<br />			datos = respuesta.read().decode('utf-8')<br />			scrapsismo = BeautifulSoup(datos, "lxml")<br />			tabla = scrapsismo.find("table", {"id" : "sismos"})<br />			registros = tabla.find_all('tr')<br />			cantidadr = len(registros)<br />			for reg in registros:<br />				if (i>1 and i<cantidadr-3):<br />					sctd = BeautifulSoup(str(reg), "lxml")<br />					tds = sctd.find_all('td')<br />					fechat = tds[1].text<br />					horat = tds[2].text<br />					proft = tds[3].text<br />					mntud = float(tds[4].text)<br />					magnitudt = tds[4].text<br />					latt = tds[5].text<br />					longt = tds[6].text<br />					lugart = tds[7].text<br />					h = datetime.datetime.strptime(fechat.strip()+" "+horat.strip(), '%d/%m/%Y %H:%M:%S')<br />					ds_ts = time.mktime(hoyhora.timetuple())<br />					dr_ts = time.mktime(h.timetuple())<br />					diff = int(ds_ts-dr_ts) / 60<br />					ck = controlador.checkdb(h,lugart)<br />					if (lugart in provincias and ck==False):<br />						controlador.inserta(h,proft,magnitudt,latt,longt,lugart)<br />						if (mntud>mgtmax):<br />							tdin = i<br />							ale=True<br />							formateado = "Alerta Temblor!!\nHace "+str(diff)+" min\n"<br />				i += 1<br />			if (ale==True):<br />				formateado = formateado + registros[tdin].text<br />		except:<br />			formateado = 'Error en consulta'<br />		return formateado
<br /><br />It also stores in a DB the values it collects from inpres, for the provinces we define. This is optional and can be removed.<br /><br />Anyway, the zip contains the .sql with the table structure.<br /><br />If you want to use it, in the controladores.py file inside the scrapers folder, edit the database connection.<br /><br />If you don't want to store anything, edit inpres.py inside the scrapers folder with this code<br /><br />
Código: python
#!/usr/bin/python<br /># -*- coding: utf-8 -*-<br /> <br />import urllib2<br />import datetime<br />import time<br />from bs4 import BeautifulSoup<br /> <br />class SCinpres:<br /> <br />    def __init__(self):<br />        pass<br /> <br />    def extraer(self):<br />		url = 'http://www.inpres.gov.ar/desktop/'<br />		formateado = ''<br />		try:<br />			respuesta = urllib2.urlopen(url)<br />			datos = respuesta.read().decode('utf-8')<br />			scrapsismo = BeautifulSoup(datos, "lxml")<br />			tabla = scrapsismo.find("table", {"id" : "sismos"})<br />			formateado = ''<br />			registros = tabla.find_all('tr')<br />			cantidadr = len(registros)<br />			i=0<br />			for reg in registros:<br />				if (i>1 and i<cantidadr-3):<br />					sctd = BeautifulSoup(str(reg), "lxml")<br />					tds = sctd.find_all('td')<br />					fecha = tds[1].text<br />					hora = tds[2].text<br />					mntud = tds[4].text<br />					lugar = tds[7].text<br />					formateado = formateado+"Fecha: "+fecha+" H: "+hora+" magnitud: "+mntud+" lugar: "+lugar+ "\n"<br />				i += 1<br />		except:<br />			formateado = 'Error en consulta'<br />		return formateado<br /> <br />    def monitor(self):<br />		url = 'http://www.inpres.gov.ar/desktop/'<br />		provincias = ['CATAMARCA','LA RIOJA','CORDOBA']<br />		mgtmax= 4.3<br />		hoyhora = datetime.datetime.now()<br />		i=0<br />		tdin=0<br />		ale=False<br />		formateado = ''<br />		try:<br />			respuesta = urllib2.urlopen(url)<br />			datos = respuesta.read().decode('utf-8')<br />			scrapsismo = BeautifulSoup(datos, "lxml")<br />			tabla = scrapsismo.find("table", {"id" : "sismos"})<br />			registros = tabla.find_all('tr')<br />			cantidadr = len(registros)<br />			for reg in registros:<br />				if (i>1 and i<cantidadr-3):<br />					sctd = BeautifulSoup(str(reg), "lxml")<br />					tds = sctd.find_all('td')<br />					fechat = tds[1].text<br />					horat = tds[2].text<br />					proft = tds[3].text<br />					mntud = float(tds[4].text)<br />					magnitudt = tds[4].text<br />					latt = tds[5].text<br />					longt = tds[6].text<br />					lugart = tds[7].text<br />					h = datetime.datetime.strptime(fechat.strip()+" "+horat.strip(), '%d/%m/%Y %H:%M:%S')<br />					ds_ts = time.mktime(hoyhora.timetuple())<br />					dr_ts = time.mktime(h.timetuple())<br />					diff = int(ds_ts-dr_ts) / 60<br />					if (lugart in provincias):<br />						if (mntud>mgtmax):<br />							tdin = i<br />							ale=True<br />							formateado = "Alerta Temblor!!\nHace "+str(diff)+" min\n"<br />				i += 1<br />			if (ale==True):<br />				formateado = formateado + registros[tdin].text<br />		except:<br />			formateado = 'Error en consulta'<br />		return formateado
<br /><br />Finally, run the script<br /><br />
Código: bash
python run.py &
<br /><br />If you have a VPS or dedicated server you can use tmux, so it keeps running after you close the SSH session.<br /><br />
Código: bash
tmux<br />python run.py &
<br /><br />ctrl+b and then press d<br />to return to the tmux session<br /><br />
Código: bash
tmux attach
<br /><br />to exit again ctrl+b and then press d<br />To see the list of bot commands, send the word:<br /><br />ayuda<br /><br />
Los enlaces son solo para miembros. Registrate o iniciá sesión/blog.elfsystems.pro/wp-content/uploads/2017/02/Screenshot_2017-02-21-14-34-34-180x300.Los enlaces son solo para miembros. Registrate o iniciá sesión
<br /><br />The code may fail the first time since it has some dependencies that don't come installed with Python by default. The scrapers use BeautifulSoup, MySQLdb and others, which you'll have to install with pip install<br /><br />
Código: bash
pip install MySQLdb<br />pip install beautifulsoup
<br /><br />If it fails, stop the script with ctrl + z, since it uses threads.<br />In conclusion, you can automate queries and processes, and answer queries for companies, all using WhatsApp as a gateway.<br /><br />
<br /><br />Fix Update 22/02/2017<br /><br />The API is having problems receiving contacts and audio, so the script stops.<br /><br />Replace the code in /usr/lib/python2.7/site-packages/yowsup2-2.5.0-py2.7.egg/yowsup/layers/axolotl/layer_receive.py<br /><br />
Código: python
from .layer_base import AxolotlBaseLayer<br /> <br />from yowsup.layers.protocol_receipts.protocolentities import OutgoingReceiptProtocolEntity<br />from yowsup.layers.protocol_messages.proto.wa_pb2 import *<br />from yowsup.layers.axolotl.protocolentities import *<br />from yowsup.structs import ProtocolTreeNode<br />from yowsup.layers.axolotl.props import PROP_IDENTITY_AUTOTRUST<br /> <br />from axolotl.protocol.prekeywhispermessage import PreKeyWhisperMessage<br />from axolotl.protocol.whispermessage import WhisperMessage<br />from axolotl.sessioncipher import SessionCipher<br />from axolotl.groups.groupcipher import GroupCipher<br />from axolotl.invalidmessageexception import InvalidMessageException<br />from axolotl.duplicatemessagexception import DuplicateMessageException<br />from axolotl.invalidkeyidexception import InvalidKeyIdException<br />from axolotl.nosessionexception import NoSessionException<br />from axolotl.untrustedidentityexception import UntrustedIdentityException<br />from axolotl.axolotladdress import AxolotlAddress<br />from axolotl.groups.senderkeyname import SenderKeyName<br />from axolotl.groups.groupsessionbuilder import GroupSessionBuilder<br />from axolotl.protocol.senderkeydistributionmessage import SenderKeyDistributionMessage<br /> <br />import logging<br />import copy<br />logger = logging.getLogger(__name__)<br />#/usr/lib/python2.7/site-packages/yowsup2-2.5.0-py2.7.egg/yowsup/layers/axolotl path fix<br />class AxolotlReceivelayer(AxolotlBaseLayer):<br />    def __init__(self):<br />        super(AxolotlReceivelayer, self).__init__()<br />        self.v2Jids = [] #people we're going to send v2 enc messages<br />        self.sessionCiphers = {}<br />        self.groupCiphers = {}<br />        self.pendingIncomingMessages = {} #(jid, participantJid?) => message<br /> <br />    def receive(self, protocolTreeNode):<br />        """<br />        :type protocolTreeNode: ProtocolTreeNode<br />        """<br />        if not self.processIqRegistry(protocolTreeNode):<br />            if protocolTreeNode.tag == "message":<br />                self.onMessage(protocolTreeNode)<br />            elif not protocolTreeNode.tag == "receipt":<br />                #receipts will be handled by send layer<br />                self.toUpper(protocolTreeNode)<br /> <br />            # elif protocolTreeNode.tag == "iq":<br />            #     if protocolTreeNode.getChild("encr_media"):<br />            #         protocolTreeNode.addChild("media", {<br />            #             "url": protocolTreeNode["url"],<br />            #             "ip": protocolTreeNode["ip"],<br />            #         })<br />            #         self.toUpper(protocolTreeNode)<br />            #         return<br /> <br />    ######<br /> <br />    def onEncrMediaResult(self, resultNode):<br />        pass<br /> <br /> <br />    def processPendingIncomingMessages(self, jid, participantJid = None):<br />        conversationIdentifier = (jid, participantJid)<br />        if conversationIdentifier in self.pendingIncomingMessages:<br />            for messageNode in self.pendingIncomingMessages[conversationIdentifier]:<br />                self.onMessage(messageNode)<br /> <br />            del self.pendingIncomingMessages[conversationIdentifier]<br /> <br />    ##### handling received data #####<br /> <br />    def onMessage(self, protocolTreeNode):<br />        encNode = protocolTreeNode.getChild("enc")<br />        if encNode:<br />            self.handleEncMessage(protocolTreeNode)<br />        else:<br />            self.toUpper(protocolTreeNode)<br /> <br />    def handleEncMessage(self, node):<br />        encMessageProtocolEntity = EncryptedMessageProtocolEntity.fromProtocolTreeNode(node)<br />        isGroup =  node["participant"] is not None<br />        senderJid = node["participant"] if isGroup else node["from"]<br />        if node.getChild("enc")["v"] == "2" and node["from"] not in self.v2Jids:<br />            self.v2Jids.append(node["from"])<br />        try:<br />            if encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_PKMSG):<br />                self.handlePreKeyWhisperMessage(node)<br />            elif encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_MSG):<br />                self.handleWhisperMessage(node)<br />            if encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_SKMSG):<br />                self.handleSenderKeyMessage(node)<br />        except (InvalidMessageException, InvalidKeyIdException) as e:<br />            logger.warning("InvalidMessage or KeyId for %s, going to send a retry", encMessageProtocolEntity.getAuthor(False))<br />            retry = RetryOutgoingReceiptProtocolEntity.fromMessageNode(node, self.store.getLocalRegistrationId())<br />            self.toLower(retry.toProtocolTreeNode())<br />        except NoSessionException as e:<br />            logger.warning("No session for %s, getting their keys now", encMessageProtocolEntity.getAuthor(False))<br /> <br />            conversationIdentifier = (node["from"], node["participant"])<br /> <br />            if conversationIdentifier not in self.pendingIncomingMessages:<br />                self.pendingIncomingMessages[conversationIdentifier] = []<br />            self.pendingIncomingMessages[conversationIdentifier].append(node)<br /> <br />            successFn = lambda successJids, b: self.processPendingIncomingMessages(*conversationIdentifier) if len(successJids) else None<br /> <br />            self.getKeysFor([senderJid], successFn)<br /> <br />        except DuplicateMessageException as e:<br />            logger.warning("Received a message that we've previously decrypted, goint to send the delivery receipt myself")<br />            self.toLower(OutgoingReceiptProtocolEntity(node["id"], node["from"], participant=node["participant"]).toProtocolTreeNode())<br /> <br />        except UntrustedIdentityException as e:<br />            if self.getProp(PROP_IDENTITY_AUTOTRUST, False):<br />                logger.warning("Autotrusting identity for %s", e.getName())<br />                self.store.saveIdentity(e.getName(), e.getIdentityKey())<br />                return self.handleEncMessage(node)<br />            else:<br />                logger.error("Ignoring message with untrusted identity")<br /> <br />    def handlePreKeyWhisperMessage(self, node):<br />        pkMessageProtocolEntity = EncryptedMessageProtocolEntity.fromProtocolTreeNode(node)<br />        enc = pkMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_PKMSG)<br />        preKeyWhisperMessage = PreKeyWhisperMessage(serialized=enc.getData())<br />        sessionCipher = self.getSessionCipher(pkMessageProtocolEntity.getAuthor(False))<br />        plaintext = sessionCipher.decryptPkmsg(preKeyWhisperMessage)<br />        if enc.getVersion() == 2:<br />            paddingByte = plaintext[-1] if type(plaintext[-1]) is int else ord(plaintext[-1])<br />            padding = paddingByte & 0xFF<br />            self.parseAndHandleMessageProto(pkMessageProtocolEntity, plaintext[:-padding])<br />        else:<br />            self.handleConversationMessage(node, plaintext)<br /> <br />    def handleWhisperMessage(self, node):<br />        encMessageProtocolEntity = EncryptedMessageProtocolEntity.fromProtocolTreeNode(node)<br /> <br />        enc = encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_MSG)<br />        whisperMessage = WhisperMessage(serialized=enc.getData())<br />        sessionCipher = self.getSessionCipher(encMessageProtocolEntity.getAuthor(False))<br />        plaintext = sessionCipher.decryptMsg(whisperMessage)<br /> <br />        if enc.getVersion() == 2:<br />            paddingByte = plaintext[-1] if type(plaintext[-1]) is int else ord(plaintext[-1])<br />            padding = paddingByte & 0xFF<br />            self.parseAndHandleMessageProto(encMessageProtocolEntity, plaintext[:-padding])<br />        else:<br />            self.handleConversationMessage(encMessageProtocolEntity.toProtocolTreeNode(), plaintext)<br /> <br />    def handleSenderKeyMessage(self, node):<br />        encMessageProtocolEntity = EncryptedMessageProtocolEntity.fromProtocolTreeNode(node)<br />        enc = encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_SKMSG)<br /> <br />        senderKeyName = SenderKeyName(encMessageProtocolEntity.getFrom(True), AxolotlAddress(encMessageProtocolEntity.getParticipant(False), 0))<br />        groupCipher = GroupCipher(self.store, senderKeyName)<br />        try:<br />            plaintext = groupCipher.decrypt(enc.getData())<br />            padding = ord(plaintext[-1]) & 0xFF<br />            plaintext = plaintext[:-padding]<br />            plaintext = plaintext.encode() if sys.version_info >= (3, 0) else plaintext<br />            self.parseAndHandleMessageProto(encMessageProtocolEntity, plaintext)<br /> <br />        except NoSessionException as e:<br />            logger.warning("No session for %s, going to send a retry", encMessageProtocolEntity.getAuthor(False))<br />            retry = RetryOutgoingReceiptProtocolEntity.fromMessageNode(node, self.store.getLocalRegistrationId())<br />            self.toLower(retry.toProtocolTreeNode())<br /> <br />    def parseAndHandleMessageProto(self, encMessageProtocolEntity, serializedData):<br />        node = encMessageProtocolEntity.toProtocolTreeNode()<br />        m = Message()<br />        handled = False<br />        try:<br />            m.ParseFromString(serializedData)<br />        except:<br />            print("DUMP:")<br />            print(serializedData)<br />            print([s for s in serializedData])<br />            print([ord(s) for s in serializedData])<br />            raise<br />        if not m or not serializedData:<br />            raise ValueError("Empty message")<br /> <br />        if m.HasField("sender_key_distribution_message"):<br />            handled = True<br />            axolotlAddress = AxolotlAddress(encMessageProtocolEntity.getParticipant(False), 0)<br />            self.handleSenderKeyDistributionMessage(m.sender_key_distribution_message, axolotlAddress)<br /> <br />        if m.HasField("conversation"):<br />            handled = True<br />            self.handleConversationMessage(node, m.conversation)<br />        elif m.HasField("contact_message"):<br />            handled = True<br />            self.handleContactMessage(node, m.contact_message)<br />        elif m.HasField("url_message"):<br />            handled = True<br />            self.handleUrlMessage(node, m.url_message)<br />        elif m.HasField("location_message"):<br />            handled = True<br />            #self.handleLocationMessage(node, m.location_message)<br />        elif m.HasField("image_message"):<br />            handled = True<br />            self.handleImageMessage(node, m.image_message)<br /> <br />        if not handled:<br />            print(m)<br />            #raise ValueError("Unhandled")<br /> <br />    def handleSenderKeyDistributionMessage(self, senderKeyDistributionMessage, axolotlAddress):<br />        groupId = senderKeyDistributionMessage.groupId<br />        axolotlSenderKeyDistributionMessage = SenderKeyDistributionMessage(serialized=senderKeyDistributionMessage.axolotl_sender_key_distribution_message)<br />        groupSessionBuilder = GroupSessionBuilder(self.store)<br />        senderKeyName = SenderKeyName(groupId, axolotlAddress)<br />        groupSessionBuilder.process(senderKeyName, axolotlSenderKeyDistributionMessage)<br /> <br />    def handleConversationMessage(self, originalEncNode, text):<br />        messageNode = copy.deepcopy(originalEncNode)<br />        messageNode.children = []<br />        messageNode.addChild(ProtocolTreeNode("body", data = text))<br />        self.toUpper(messageNode)<br /> <br />    def handleImageMessage(self, originalEncNode, imageMessage):<br />        messageNode = copy.deepcopy(originalEncNode)<br />        messageNode["type"] = "media"<br />        mediaNode = ProtocolTreeNode("media", {<br />            "type": "image",<br />            "filehash": imageMessage.file_sha256,<br />            "size": str(imageMessage.file_length),<br />            "url": imageMessage.url,<br />            "mimetype": imageMessage.mime_type,<br />            "width": imageMessage.width,<br />            "height": imageMessage.height,<br />            "caption": imageMessage.caption,<br />            "encoding": "raw",<br />            "file": "enc",<br />            "ip": "0"<br />        }, data = imageMessage.jpeg_thumbnail)<br />        messageNode.addChild(mediaNode)<br /> <br />        self.toUpper(messageNode)<br /> <br />    def handleUrlMessage(self, originalEncNode, urlMessage):<br />        #convert to ??<br />        pass<br /> <br />    def handleDocumentMessage(self, originalEncNode, documentMessage):<br />        #convert to ??<br />        pass<br /> <br />    def handleLocationMessage(self, originalEncNode, locationMessage):<br />        messageNode = copy.deepcopy(originalEncNode)<br />        messageNode["type"] = "media"<br />        mediaNode = ProtocolTreeNode("media", {<br />            "latitude": locationMessage.degrees_latitude,<br />            "longitude": locationMessage.degress_longitude,<br />            "name": "%s %s" % (locationMessage.name, locationMessage.address),<br />            "url": locationMessage.url,<br />            "encoding": "raw",<br />            "type": "location"<br />        }, data=locationMessage.jpeg_thumbnail)<br />        messageNode.addChild(mediaNode)<br />        self.toUpper(messageNode)<br /> <br />    def handleContactMessage(self, originalEncNode, contactMessage):<br />        messageNode = copy.deepcopy(originalEncNode)<br />        messageNode["type"] = "media"<br />        mediaNode = ProtocolTreeNode("media", {<br />            "type": "vcard"<br />        }, [<br />            ProtocolTreeNode("vcard", {"name": contactMessage.display_name}, data = contactMessage.vcard)<br />        ] )<br />        messageNode.addChild(mediaNode)<br />        self.toUpper(messageNode)<br /> <br />    def getSessionCipher(self, recipientId):<br />        if recipientId in self.sessionCiphers:<br />            sessionCipher = self.sessionCiphers[recipientId]<br />        else:<br />            sessionCipher = SessionCipher(self.store, self.store, self.store, self.store, recipientId, 1)<br />            self.sessionCiphers[recipientId] = sessionCipher<br /> <br />        return sessionCipher<br /> <br />    def getGroupCipher(self, groupId, senderId):<br />        senderKeyName = SenderKeyName(groupId, AxolotlAddress(senderId, 1))<br />        if senderKeyName in self.groupCiphers:<br />            groupCipher = self.groupCiphers[senderKeyName]<br />        else:<br />            groupCipher = GroupCipher(self.store, senderKeyName)<br />            self.groupCiphers[senderKeyName] = groupCipher<br />        return groupCipher
<br /><br />
<br />Author: Jorge T<br />Source: Los enlaces son solo para miembros. Registrate o iniciá sesión<br />
<br /><br />Hope it helps!<br />ANTRAX
VinC90 ·
Congrats! Great work!
Leo_Al ·
Hi, in the commands that say "sudo", how would I do that on Windows?
kid_goth ·
Cita de: Leo_ en Febrero 26, 2017, 01:02:58 AM<br />Hi, in the commands that say "sudo", how would I do that on Windows?<br />
<br /><br />You don't have to... and if it gives you permission problems, open that cmd with right click "Run as administrator"
Leo_Al ·
Hi, I have a problem: when I run the command
Código: bash
yowsup-cli registration --requestcode sms --phone 549XXXXXXXXXX --cc 54 --mcc 722 --mnc XX
it says the message is being sent but it never arrives. I already tried with another number and it's the same.
ANTRAX ·
Cita de: Leo_ en Marzo 02, 2017, 09:01:42 AM<br />Hi, I have a problem: when I run the command
Código: bash
yowsup-cli registration --requestcode sms --phone 549XXXXXXXXXX --cc 54 --mcc 722 --mnc XX
it says the message is being sent but it never arrives. I already tried with another number and it's the same.<br />
<br /><br />Well, I talked with the author of the post about your problem. Apparently since February 28 WhatsApp changed its policies and bans numbers that try to be bots.<br />On the script's GitHub several people commented that the same happened to them.<br /><br />What you could do is try a number that has been using WhatsApp for a long time to see what happens... But you run the risk of it being banned too.<br /><br />For now the safest option is to make bots for Telegram. I'll soon post about how to make them.<br /><br />Regards,<br />ANTRAX
Leo_Al ·
Cita de: ANTRAX en Marzo 02, 2017, 12:08:30 PM<br />
Cita de: Leo_ en Marzo 02, 2017, 09:01:42 AM<br />Hi, I have a problem: when I run the command
Código: bash
yowsup-cli registration --requestcode sms --phone 549XXXXXXXXXX --cc 54 --mcc 722 --mnc XX
it says the message is being sent but it never arrives. I already tried with another number and it's the same.<br />
<br /><br />Well, I talked with the author of the post about your problem. Apparently since February 28 WhatsApp changed its policies and bans numbers that try to be bots.<br />On the script's GitHub several people commented that the same happened to them.<br /><br />What you could do is try a number that has been using WhatsApp for a long time to see what happens... But you run the risk of it being banned too.<br /><br />For now the safest option is to make bots for Telegram. I'll soon post about how to make them.<br /><br />Regards,<br />ANTRAX<br />
<br />Ah ok, thanks a lot for replying!
kendex ·
Hello everyone and thanks for the content for the bot,<br /><br />Now, I have a question: will you have the tokens corresponding to WhatsApp version 2.17.52? Because I tried the ones posted on the site, but it throws the following:<br /><br />
Código: text
<br />yowsup-cli  v2.0.15<br />yowsup      v2.5.2<br /><br />Copyright (c) 2012-2016 Tarek Galal<br />http://www.openwhatsapp.org<br /><br />This software is provided free of charge. Copying and redistribution is<br />encouraged.<br /><br />If you appreciate this software and you would like to support future<br />development please consider donating:<br />http://openwhatsapp.org/yowsup/donate<br /><br /><br />INFO:yowsup.common.http.warequest:b'{"login":"XXXXXXXXXX","status":"fail","reason":"bad_token"}\n'<br />status: b'fail'<br />reason: b'bad_token'<br />login: b'XXXXXXXXXX'<br /><br />
<br /><br />Regards.
RickHunterEc ·
:) good work
leomontilla ·
Excellent work, I find the code exceptional. It's great that people are interested in innovating with technology.
Grupo de WhatsApp