Dispalying a tweet

Hi, I’m trying to display a tweet in my app in such a way that the text and image of a post appear. Something like that:

Captura de Pantalla 2021-08-12 a la(s) 9.54.12 a. m.

I am using this code to capture and display the tweet from a url:

class Tweet(object):
    def __init__(self, s, embed_str=False):
        if not embed_str:
            # Use Twitter's oEmbed API
            # https://dev.twitter.com/web/embedded-tweets
            api = 'https://publish.twitter.com/oembed?url={}'.format(s)
            response = requests.get(api)
            self.text = response.json()["html"]
        else:
            self.text = s

    def _repr_html_(self):
        return self.text


st.write(Tweet("https://twitter.com/OReillyMedia/status/901048172738482176"), unsafe_allow_html=True)

But I only get part of the tweet. This is my result:

Captura de Pantalla 2021-08-12 a la(s) 10.01.01 a. m.

Anyone know how to display the full Tweet? Thanks!

Hi @davera-017,

the html you are trying to display contains script tags to load some javascript. Not sure if this is possible within the st.write object. You could try to use a static html component instead, you’ll have to play around a bit with the component height.

import requests
import streamlit.components.v1 as components


class Tweet(object):
    def __init__(self, s, embed_str=False):
        if not embed_str:
            # Use Twitter's oEmbed API
            # https://dev.twitter.com/web/embedded-tweets
            api = "https://publish.twitter.com/oembed?url={}".format(s)
            response = requests.get(api)
            self.text = response.json()["html"]
        else:
            self.text = s

    def _repr_html_(self):
        return self.text

    def component(self):
        return components.html(self.text, height=600)


t = Tweet("https://twitter.com/OReillyMedia/status/901048172738482176").component()

2 Likes

Thank you! It works perfectly.