0
votes

I want to tweet an image saved on a model's ImageField. I'm using tweepy, but I'm open to anything that works.

This is what I've tried:

First:

api = tweepy.API(auth)
api.update_with_media(filename=model_object.image.name, status=text, file=model_object.image)

error: TweepError: Invalid file type for image: None

Then:

from PIL import Image

api = tweepy.API(auth)
image_file = Image.open(model_object.image)
api.update_with_media(filename=model_object.image.name, status=text, file=image_file)

219, in update_with_media headers, post_data = API._pack_image(filename, 3072, form_field='media[]', f=f) File "/home/alejandro/Proyectos/criptohisoka/local/lib/python2.7/site-packages/tweepy/api.py", line 1311, in _pack_image f.seek(0, 2) # Seek to end of file TypeError: seek() takes exactly 2 arguments (3 given)

Finally:

from PIL import Image
from StringIO import StringIO

api = tweepy.API(auth)
image_file = Image.open(model_object.image)
stringio_obj = StringIO()
image_file.save(stringio_obj, format="JPEG")
api.update_with_media(filename=model_object.image.name, status=text, file=stringio_obj)

TweepError: Invalid file type for image: None

I'm not sure what the update_with_media method expects as a file. Here is the relevanttweepy source code and here are the docs.

1
It looks like it's looking for a File object, so your 2nd example should work. Could you expand on the stacktrace with the TypeError? It looks like the problem may not lie with the actual call. - lonewaft
@lonewaft Just added some more traceback ... but there ain't much to add. Looks like a bug to me. - Alejandro Veintimilla

1 Answers

1
votes

Since the upload_with_media endpoint has been deprecated, see here, I'm going to suggest you to use the following method:

Use the absolute path to the file

media_ids = api.media_upload(filename=model_object.image.file.name)

Twitter API will respond with a long integer cached in the media_ids variable.

Finally, use the update_status endpoint:

params = {'status': 'chop chop chop', 'media_ids': [media_ids.media_id_string]}
response = api.update_status(**params)

For reference, see the method definitions in tweepy, and their correspondence in Twitter api:

  1. Tweepy: media_upload
  2. Tweepy: update_status
  3. Twitter API: update endpoint
  4. Twitter API: media_upload endpoint