skip to Main Content

I’m trying to write a script that will post two images to Twitter using the API, any idea why this doesn’t work? It only posts the first image. New to this, thanks!

from TwitterAPI import TwitterAPI
import urllib

api = TwitterAPI('','','','')

x = []

file = open('im1.png', 'rb')
data = file.read()
r = api.request('media/upload', None, {'media': data})
media_id = r.json()['media_id']
print('UPLOAD MEDIA SUCCESS' if r.status_code == 200 else 'UPLOAD MEDIA FAILURE')
x.append(str(media_id))


file = open('im2.png', 'rb')
data1 = file.read()
r = api.request('media/upload', None, {'media': data1})
media_id = r.json()['media_id']
print('UPLOAD MEDIA SUCCESS' if r.status_code == 200 else 'UPLOAD MEDIA FAILURE')
x.append(str(media_id))


if r.status_code == 200:
    media_id = r.json()['media_id']
    r = api.request('statuses/update', {'status':'Test', 'media_ids':media_id})
    print('UPDATE STATUS SUCCESS' if r.status_code == 200 else 'UPDATE STATUS FAILURE')

2

Answers


  1. Chosen as BEST ANSWER

    Use tweepy (much easier);

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    
    api = tweepy.API(auth)
    
    Im1 = urllib.urlretrieve('http://www.meteociel.fr/cartes_obs/temp_uk.png','im1.png')
    
    images = ('im1.png', 'im1.png')
    media_ids = [api.media_upload(i).media_id_string for i in images]
    api.update_status(status='msg', media_ids=media_ids)
    

  2. You are almost there. You just forgot to use your array of ids x. Make the following change to the last part of your code.

    if r.status_code == 200:
        media_id = ','.join(x)
        r = api.request('statuses/update', {'status':'Test', 'media_ids':media_id})
        print('UPDATE STATUS SUCCESS' if r.status_code == 200 else 'UPDATE STATUS FAILURE')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search