Python – API.media_upload() in Tweepy

Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.

API.media_upload()

The media_upload() method of the API class in Tweepy module is used to upload a media object to Twitter.

Syntax : API.media_upload(filename, file)

Parameters :

  • filename : path of the media file to be uplaoded.
  • file : a file object to be uploaded.

Returns : an object of class Media



Example 1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# import the module
import tweepy
  
# assign the values accordingly
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
  
# authorization of consumer key and consumer secret
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
  
# set access to user's access key and access secret 
auth.set_access_token(access_token, access_token_secret)
  
# calling the api 
api = tweepy.API(auth)
  
# the name of the media file
filename = "gfg.png"
  
# upload the file
media = api.media_upload(filename)
  
# printing the information
print("The media ID is : " + media.media_id_string)
print("The size of the file is : " + str(media.size) + " bytes")

chevron_right


Output :

The media ID is : 1270554007983910912
The size of the file is : 3346 bytes

Example 2 : Finding the dimensions of the image file using the media_upload() method.

filter_none

edit
close

play_arrow

link
brightness_4
code

# the name of the media file
filename = "gfg.png"
  
# upload the file
media = api.media_upload(filename)
  
# printing the dimensions
print("The width is : " + str(media.image['w']) + " pixels.")
print("The height is : " + str(media.image['h']) + " pixels.")

chevron_right


Output :

The width is : 225 pixels.
The height is : 225 pixels.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.