Search code examples
rtwittershiny

Embedded a specific tweet in a R Shiny app


I'm totally newbie in Web and all that stuff. I want to be able to display a specific tweet from a user input in a Shiny app. Here is my try from this post : How can i embed a twitter timeline in a shiny app? . I'm trying to display this tweet : https://twitter.com/AndrewYNg/status/894994683931148288

library(shiny)
runApp(list(ui = fluidPage(
  tags$head("<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)    [0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document,'script','twitter-wjs');</script>"),
  titlePanel(""),
  sidebarLayout(
    sidebarPanel()
    , mainPanel(
      a("Tweets by Andrew Ng", class="twitter-tweet"
        , href = "https://twitter.com/AndrewYNg/status/894994683931148288"
      )
    )
  )
)
, server = function(input, output, session){

}
)
)

It does not display the tweet but the link to the tweet. I guess the tag$head does not contain the good thing but I cannot figure out what it is supposed to be.


Solution

    1. Wrap the script in a shiny::HTML() so the content doesn't get HTML escaped. <script> is getting escaped to &lt;script&gt; in your example. Or better, use shiny::tags$script()

    2. Check the Twitter docs to see how to embed a Tweet and make sure the markup is correct: https://dev.twitter.com/web/embedded-tweets

    library(shiny)
    
    runApp(list(
      ui = fluidPage(
        tags$head(
          tags$script("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)    [0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document,'script','twitter-wjs');")
        ),
        titlePanel(""),
        sidebarLayout(
          sidebarPanel(),
          mainPanel(
            HTML('
            <blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">
              Want to break into AI? You can learn Deep Learning from new deeplearning.ai courses on Coursera:
              <a href="https://www.coursera.org/specializations/deep-learning">https://www.coursera.org/specializations/deep-learning</a></p>&mdash; Andrew Ng (@AndrewYNg)
              <a href="https://twitter.com/AndrewYNg/status/894994683931148288?ref_src=twsrc%5Etfw">August 8, 2017</a>
            </blockquote>
          ')
          )
        )
      ),
      server = function(input, output, session) {}
    ))
    

    I used raw HTML for the tweet, but you could convert it to HTML tag objects.