tgalal / yowsup

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

How to upload image & send? #178

Closed Wiku5 closed 9 years ago

Wiku5 commented 10 years ago

What is the way to upload an image?

I understand how to send it, but I need to be able to send the URL that is located on WhatsApp's server.

Is there any documentation to send via Uploader.py under media? For the life of me, i can't get it to work regardless of any workarounds.

Many thanks!

CODeRUS commented 10 years ago

Media.uploader is here

Wiku5 commented 10 years ago

I know, but how do I use it? I've tried everything. Is it possible for you to please post an example?

Wiku5 commented 10 years ago

I keep getting:

Traceback (most recent call last): File "/home/wikus/Dropbox/projects/whatsapp/Yowsup/Media/uploader.py", line 1, in from ..Common.Http.warequest import WARequest ValueError: Attempted relative import in non-package

in Media.Uploader

CODeRUS commented 10 years ago

you can check wazapp sources

Wiku5 commented 10 years ago

I've tried that already.

Is there any way possible for you to pastebin what you have to uploading images? Or even a PHP script?

I've google'd for days trying to find a way to upload correctly.

Wiku5 commented 10 years ago

Also, Wazapp uses this in their code: Yowsup.Media.downloader import MediaDownloader

But does not include the Yowsup fork in their source, so it's redundant to try and find a working implementation of it unfortunatley.

CODeRUS commented 10 years ago

you should fill and send media upload request before, and then upload media :)

Wiku5 commented 10 years ago

Could you please post an example?

xiaojxiao commented 10 years ago

Here is the upload process: Step 1. Call 'media_requestUpload' method (in YowsupConnectionManager) to get the upload path. Step 2. Upload image to the path from step 1 via 'Media.uploader'.

Wazapp has the best example for uploader.

siddharth7815 commented 10 years ago

how can we get upload path using media_requestUpload method?

5263 commented 10 years ago

It doesn't work for me and i have no clue how to debug it.

DEBUG:BinTreeNodeWriter:Outgoing
DEBUG:BinTreeNodeWriter:
<iq to="s.whatsapp.net" type="set" id="upload_1">
<media type="image" xmlns="w:m" hash="dOBuL1lRvwUeeGRTnkvG3vWITPMGLd0+egOtGU2gyyg=" size="116">
</media>
</iq>

DEBUG:BinTreeNodeReader:Incoming
DEBUG:BinTreeNodeReader:
<iq type="error" from="s.whatsapp.net" id="upload_1">
<error text="bad-request" code="400">
</error>
</iq>

Has anybody set uploading up successfully?

siddharth7815 commented 10 years ago

you are passing wrong parameter while calling message_imageSend. here type of file size is string.

self.methodsInterface.call("message_imageSend",self.jids[i],uploaded_url,self.filename,str(self.filesize),self.message))

5263 commented 10 years ago

It seems WA is rejecting media below a certain size. I bypassed this problem. But now i get File "./src/Yowsup/Media/uploader.py", line 77, in upload self._d(POST) AttributeError: 'MediaUploader' object has no attribute '_d'

SamsonBox commented 10 years ago

Hello together,

I modified the Example/CmdClient.py so it can send and receive images. Here are the modifications:

from Yowsup.Media.downloader import MediaDownloader
from Yowsup.Media.uploader import MediaUploader
from sys import stdout
import os
import hashlib 
import base64
self.signalsInterface.registerListener("media_uploadRequestSuccess", self.onmedia_uploadRequestSuccess)
self.signalsInterface.registerListener("media_uploadRequestFailed", self.onmedia_uploadRequestFailed)
self.signalsInterface.registerListener("media_uploadRequestDuplicate", self.onmedia_uploadRequestDuplicate)
self.path = ""
self.gotMediaReceipt = False
self.done = False
     def runCommand(self, command):
                splitstr = command.split(' ')
        if splitstr[0] == "/pic" and len(splitstr) == 2:
            self.path = splitstr[1]

            if not os.path.isfile(splitstr[1]):
                print("File %s does not exists" % splitstr[1])
                return 1

            statinfo = os.stat(self.path)
            name=os.path.basename(self.path)
            print("Sending picture %s of size %s with name %s" %(self.path, statinfo.st_size, name))
            mtype = "image"

            sha1 = hashlib.sha256()
            fp = open(self.path, 'rb')
            try:
                sha1.update(fp.read())
                hsh = base64.b64encode(sha1.digest())
                print("Sending media_requestUpload")
                self.methodsInterface.call("media_requestUpload", (hsh, mtype, os.path.getsize(self.path)))
            finally:
                fp.close()

            timeout = 100
            t = 0;
            while t < timeout and not self.gotMediaReceipt:
                time.sleep(0.5)
                t+=1

            if not self.gotMediaReceipt:
                print("MediaReceipt print timedout!")
            else:
                print("Got request MediaReceipt")

            return 1
        elif command[0] == "/":

    def onImageReceived(self, messageId, jid, preview, url, size, wantsReceipt, isBroadcast):
        print("Image received: Id:%s Jid:%s Url:%s size:%s" %(messageId, jid, url, size))
        downloader = MediaDownloader(self.onDlsuccess, self.onDlerror, self.onDlprogress)
        downloader.download(url)
        if wantsReceipt and self.sendReceipts:
            self.methodsInterface.call("message_ack", (jid, messageId))

        timeout = 10
        t = 0;
        while t < timeout:
            time.sleep(0.5)
            t+=1

    def onDlsuccess(self, path):
        stdout.write("\n")
        stdout.flush()
        print("Image downloded to %s"%path)
        print(self.getPrompt())

    def onDlerror(self):
        stdout.write("\n")
        stdout.flush()
        print("Download Error")
        print(self.getPrompt())

    def onDlprogress(self, progress):
        stdout.write("\r Progress: %s" % progress)
        stdout.flush()

    def onmedia_uploadRequestSuccess(self,_hash, url, resumeFrom):
        print("Request Succ: hash: %s url: %s resume: %s"%(_hash, url, resumeFrom))
        self.uploadImage(url)
        self.gotMediaReceipt = True

    def onmedia_uploadRequestFailed(self,_hash):
        print("Request Fail: hash: %s"%(_hash))
        self.gotReceipt = True

    def onmedia_uploadRequestDuplicate(self,_hash, url):
            print("Request Dublicate: hash: %s url: %s "%(_hash, url))
            self.doSendImage(url)
            self.gotMediaReceipt = True

    def uploadImage(self, url):
        uploader = MediaUploader(self.jid, self.username, self.onUploadSuccess, self.onError, self.onProgressUpdated)
        uploader.upload(self.path,url)

    def onUploadSuccess(self, url):
        stdout.write("\n")
        stdout.flush()
        print("Upload Succ: url: %s "%( url))
        self.doSendImage(url)

    def onError(self):
        stdout.write("\n")
        stdout.flush()
        print("Upload Fail:")

    def onProgressUpdated(self, progress):
        stdout.write("\r Progress: %s" % progress)
        stdout.flush()

    def doSendImage(self, url):
          print("Sending message_image")
          statinfo = os.stat(self.path)
          name=os.path.basename(self.path)
          msgId = self.methodsInterface.call("message_imageSend", (self.jid, url, name,str(statinfo.st_size), "yes"))
          self.sentCache[msgId] = [int(time.time()), self.path]

hope that helps

dhthuerta commented 10 years ago

Great SamsonBox! I'm begginer in python developer (I use java), can I use these code to send an image? is it possible to do this in a windows command line? (if not, please, tell me how in linux, eclipse + python, etc)

Edit: I've managed to send a picture, but on reaching the target image does not show the preview, and forcé closes . someone have some solution ?

thvvieira commented 10 years ago

SamsonBox! This code isnt sending preview... its a bug of yowsup?

shirioko commented 10 years ago

Hahaha sorry this made me laugh

msgId = self.methodsInterface.call("message_imageSend", (self.jid, url, name,str(statinfo.st_size), "yes"))

Image thumbnail is not a boolean, it's a raw image. You need to take the original image and resize it to max 100px to create a thumbnail: https://github.com/venomous0x/WhatsAPI/blob/master/src/php/func.php#L95

itsari commented 10 years ago

Ive replaced the whole runCommand part with the one listed up. im getting this error: def onMessageReceived(self, messageId, jid, messageContent, timestamp, wantsReceipt, pushName, isBroadcast): ^ IndentationError: expected an indented block

anyone have a clue?

Creamers158 commented 10 years ago

same indentationError with me. )-: Any change someone could help out here with SamsonBox example? Maybe a tiny 'noob' howto python send / receive picture? Would be greatly appreciated :+1:

mgp25 commented 10 years ago

IndentationError: expected an indented block its because the spaces/tabs. Use google for that, its not an API related error

Creamers158 commented 10 years ago

I've managed to send a picture using the Sir Poot Blog (google), but....an interactive chat session with a group seems not possible ? Maybe someone can confirm ? Just receiving messages -> oke, also from group Broadcasting to a group using jids -> oke Interactive with a group chat -> FALSE

Also the ack (-a) seems not to be working. (A ack is not send to the server considering the group messages.)

emmnx commented 9 years ago

Dirty trick in order to receive images in url form (allowing download them by any other mean):

                if mediaType == "image":
                    mediaPreview = messageNode.getChild("media").data

 ### Modified by me:
 #                  if encoding == "raw" and mediaPreview:
 #                      mediaPreview = base64.b64encode(mediaPreview) if sys.version_info < (3, 0) else base64.b64encode(mediaPreview.encode('latin-1')).decode()
 #                  if isGroup:
 #                      self.signalInterface.send("group_imageReceived", (msgId, fromAttribute, author, mediaPreview, mediaUrl, mediaSize, wantsReceipt))
 #                  else:
 #                  self.signalInterface.send("image_received", (msgId, fromAttribute, mediaPreview, mediaUrl, mediaSize,  wantsReceipt, isBroadcast))
 ### Added:
                    self.signalInterface.send("message_received", (msgId, fromAttribute, msgData, timestamp, wantsReceipt, pushName, isBroadcast))
                    print mediaUrl 
 ### End of dirty trick.
                elif mediaType == "video":
vickynu2003 commented 9 years ago

Sir poot code really helped me a lot and send-image is working perfectly fine. http://sirpoot.blogspot.in/2014/08/using-yowsup-to-send-pictures-to-group.html

would be great if some one help in writing code for send-video and send-audio.

Creamers158 commented 9 years ago

Yup, but sending and receiving messages in a group conversation would be nice to. @Emmanux thx for your workaround!!

vickynu2003 commented 9 years ago

Hello SamsonBox, Pls extend your support for send video method also. send_image was really helpful to us. Thanks in advance

h1rule commented 9 years ago

Just getting this:

Sending picture 3146.jpg of size 310914 with name 3146.jpg Sending media_requestUpload Request Fail: hash: Wupcov2VxdVmkYdyol+nJjZfd9ChIlTrwZcUJ+bf8OM=

I've updated all .py Files. Do i need another PIP thing installed?

tgalal commented 9 years ago

See yowsup 2.0 wiki (when it goes out soon)

javiermor commented 9 years ago

Hi. I'm blocked trying to use Sir Poot modified code to send an image not to a group but to a single user. I haven't been able to identify what I do have to change to send the image to one phone number and not to a group.

Everything seems to be working but I get no message.

Thanks.

nautical commented 9 years ago

I am getting the URL generated but the image is not delivered on the client side , am using SirPoots functions .

awesomebytes commented 9 years ago

Same here, the image is not delivered.

nautical commented 9 years ago

Its working now

awesomebytes commented 9 years ago

Did you make any change @nautical? Because it's not working for me. In this Issue it's said it's legacy and it's not being fixed it seems https://github.com/tgalal/yowsup/issues/413

Then another issue was opened here: https://github.com/tgalal/yowsup/issues/581 Which has some explanation (which I'll try to use now) but does not seem to be resolved.