From 173adee4a68b3a01292a3878e7fc33fa9622ee32 Mon Sep 17 00:00:00 2001 From: Mike Helmick Date: Tue, 25 Jun 2013 21:58:10 -0400 Subject: [PATCH] HTML for tweet fixes #224 --- twython/api.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/twython/api.py b/twython/api.py index d265186..c67868f 100644 --- a/twython/api.py +++ b/twython/api.py @@ -407,3 +407,41 @@ class Twython(EndpointsMixin, object): if is_py2 and isinstance(text, (str)): return Twython.unicode2utf8(text) return str(text) + + @staticmethod + def html_for_tweet(tweet, use_display_url=True, use_expanded_url=False): + if 'retweeted_status' in tweet: + tweet = tweet['retweeted_status'] + + if 'entities' in tweet: + text = tweet['text'] + entities = tweet['entities'] + + # Mentions + for entity in entities['user_mentions']: + start, end = entity['indices'][0], entity['indices'][1] + + mention_html = '@%(screen_name)s' + text = text.replace(tweet['text'][start:end], mention_html % {'url': entity['screen_name']}) + + # Hashtags + for entity in entities['hashtags']: + start, end = entity['indices'][0], entity['indices'][1] + + hashtag_html = '#%(hashtag)s' + text = text.replace(tweet['text'][start:end], hashtag_html % {'hashtag': entity['text']}) + + # Urls + for entity in entities['urls']: + start, end = entity['indices'][0], entity['indices'][1] + if use_display_url and entity.get('display_url'): + shown_url = entity['display_url'] + elif use_expanded_url and entity.get('expanded_url'): + shown_url = entity['expanded_url'] + else: + shown_url = entity['url'] + + url_html = '%s' + text = text.replace(tweet['text'][start:end], url_html % (entity['url'], shown_url)) + + return text