Logging is a good thing.
[kiosk.git] / twitter_renderer.py
index 40a3385d92fd4746461e067f595c70486ad1f7b3..23c36f87131d64a12591f84f5c2e7b012a2479c8 100644 (file)
@@ -1,17 +1,21 @@
 #!/usr/bin/env python3
 
+import logging
 import random
 import re
-from typing import Dict, List
+from typing import Dict, List, Optional
 
 import tweepy  # type: ignore
+from scottutilz import profanity_filter
 
 import file_writer
 import renderer
-import profanity_filter
 import kiosk_secrets as secrets
 
 
+logger = logging.getLogger(__name__)
+
+
 class twitter_renderer(renderer.abstaining_renderer):
     def __init__(self, name_to_timeout_dict: Dict[str, int]) -> None:
         super().__init__(name_to_timeout_dict)
@@ -60,19 +64,45 @@ class twitter_renderer(renderer.abstaining_renderer):
     def fetch_tweets(self) -> bool:
         try:
             tweets = self.api.home_timeline(tweet_mode="extended", count=200)
-        except:
+        except Exception as e:
+            logger.exception(e)
             print("Exception while fetching tweets!")
             return False
         for tweet in tweets:
+            # j = tweet._json
+            # import json
+            # print(json.dumps(j, indent=4, sort_keys=True))
+            # print("------")
+
             author = tweet.author.name
             author_handle = tweet.author.screen_name
             self.handles_by_author[author] = author_handle
             if author not in self.tweets_by_author:
                 self.tweets_by_author[author] = []
-            l = self.tweets_by_author[author]
-            l.append(tweet)
+            x = self.tweets_by_author[author]
+            x.append(tweet)
         return True
 
+    def get_hashtags(self, tweet) -> str:
+        ret = " "
+        if "entities" in tweet._json:
+            entities = tweet._json["entities"]
+            if "hashtags" in entities:
+                for x in entities["hashtags"]:
+                    ret += f'<B>#{x["text"]}</B>, '
+        ret = re.sub(", $", "", ret)
+        return ret
+
+    def get_media_url(self, tweet) -> Optional[str]:
+        if "entities" in tweet._json:
+            entities = tweet._json["entities"]
+            if "media" in entities:
+                media = entities["media"]
+                for x in media:
+                    if "media_url_https" in x:
+                        return x["media_url_https"]
+        return None
+
     def shuffle_tweets(self) -> bool:
         authors = list(self.tweets_by_author.keys())
         author = random.choice(authors)
@@ -94,7 +124,13 @@ class twitter_renderer(renderer.abstaining_renderer):
                 ):
                     already_seen.add(text)
                     text = self.linkify(text)
-                    f.write("<LI><B>%s</B>\n" % text)
+                    text = f"<B>{text}</B>"
+                    text += self.get_hashtags(tweet)
+                    media_url = self.get_media_url(tweet)
+                    if media_url:
+                        text = f"<TABLE WIDTH=100%><TD WITDH=70%>{text}</TD>"
+                        text += f'<TD><IMG SRC="{media_url}" WIDTH=200></TD></TABLE>'
+                    f.write(f"<LI>{text}")
                     count += 1
                     length += len(text)
                     if count > 3 or length > 270:
@@ -105,12 +141,12 @@ class twitter_renderer(renderer.abstaining_renderer):
 
 # Test
 # t = twitter_renderer(
-#     {"Fetch Tweets" : 1,
-#      "Shuffle Tweets" : 1})
+#    {"Fetch Tweets" : 1,
+#     "Shuffle Tweets" : 1})
 # x = "bla bla bla https://t.co/EjWnT3UA9U bla bla"
 # x = t.linkify(x)
 # print(x)
 # if t.fetch_tweets() == 0:
-#     print("Error fetching tweets, none fetched.")
+#    print("Error fetching tweets, none fetched.")
 # else:
-#     t.shuffle_tweets()
+#    t.shuffle_tweets()