Get the text in the image description of a tweet using rtweet

89 Views Asked by At

Is there a way to get the text used as the image description of tweets? I'm using the package, which allows one to get several pieces of information about a tweet (text, links, hashtags etc) but I can't get this info.

{rtweet} allows one to post a tweet with rtweet::post_tweet and add the image descriptio through the parameter media_alt_text but I can't find this information when I download a tweet using the rtweet::get_timeline function.

reprex

library(rtweet)

# parsing the tweet data
last_tweet_parsed <- rtweet::get_timeline(user = 'esquinadobrasil', 
                                          n = 1, 
                                          parse = T)

head(last_tweet_parsed)

# not parsing the tweet data
last_tweet_unparsed <- rtweet::get_timeline(user = 'esquinadobrasil', 
                                   n = 1, 
                                   parse = F)

temp_df <- as.data.frame(last_tweet_unparsed)
head(temp_df)
1

There are 1 best solutions below

0
Bench Vue On

Using v2 API is much more flexible and sync. with documentation.

Demo Tweet. one of tweet from esquinadobrasil I will shows how to get image alt text.

https://twitter.com/esquinadobrasil/status/1615009611186069504

I will get red box text (alt_text of image)

sort 893

enter image description here

Demo

require(httr)
require(jsonlite)
require(dplyr)

bearer_token <- "***** your bearer_token *****"
headers <- c(`Authorization` = sprintf('Bearer %s', bearer_token))

params <- list(`expansions` = 'attachments.media_keys',
               `media.fields` = 'public_metrics,url,alt_text')

tweet_id <- "1615009611186069504"
url_handle <-
  sprintf('https://api.twitter.com/2/tweets/%s', tweet_id)

response <-
  httr::GET(url = url_handle,
            httr::add_headers(.headers = headers),
            query = params)
obj <- httr::content(response, as = "text")
print(obj)

Run & Result

$ rscript get-image.R

[1] "{\"data\":{\"attachments\":{\"media_keys\":[\"3_1615009514297729024\"]},\"text\":\"Municipio: Santo Antônio Da
Platina - PR\\nSetor censitário: 412410305000028\\nPopulação: 718\\nÁrea (Km2): 1.31\\nDensidade (hab/Km2): 548.06\\
nZona: urbana\\n\\uD83D\\uDDFA https://xxx/KagyCLHLrM https://xxx/z1YDyTJArx\",\"id\":\"1615009611186069504\",\"ed
it_history_tweet_ids\":[\"1615009611186069504\"]},\"includes\":{\"media\":[{\"media_key\":\"3_1615009514297729024\",
\"url\":\"https://pbs.twimg.com/media/FmmqmLiXoAAdEmw.jpg\",\"alt_text\":\"sort 893\",\"type\":\"photo\"}]}}"

enter image description here

Main Idea

V2 Get Tweet by ID

GET /2/tweets/:id

enter image description here

One of query parameter media.fields can get the alt_text from documentation. enter image description here

I tested the same API by Postman.

https://api.twitter.com/2/tweets/1615009611186069504/?expansions=attachments.media_keys&media.fields=url,alt_text

I can get the same Result

enter image description here