Extracting images from received DMs over twitter API has proven to be rather tricky and there aren’t enough information on how to do it. In this entry I’m going to explain how to achieve that programatically, using both curl as well as twitter4j.
*Note: you have to make sure that the app you are using has “Read, Write and Access direct messages” permission, other wise you’ll get a “HTTP/1.1 401 Authorization Required” error.
Step 1: Get the Image ton URL
Within DMs images are represented as media entities, the media entity has several links, the one you need is “media_url”. the https://ton.* link
Step2 : Use the link to download the image
Call twitter.getDMImageAsStream(“TON URL“), this will return an input stream of the image.