8a82e5e645731ba43eacb517db5c10891c138ca3
[kiosk.git] / twitter_renderer.py
1 import file_writer
2 import random
3 import renderer
4 import profanity_filter
5 import re
6 import secrets
7 import tweepy
8
9 class twitter_renderer(renderer.debuggable_abstaining_renderer):
10     def __init__(self, name_to_timeout_dict):
11         super(twitter_renderer, self).__init__(name_to_timeout_dict, False)
12         self.debug = 1
13         self.tweets_by_author = dict()
14         self.handles_by_author = dict()
15         self.filter = profanity_filter.profanity_filter()
16         self.urlfinder = re.compile(
17             "((http|https)://[\-A-Za-z0-9\\.]+/[\?\&\-A-Za-z0-9_\\.]+)")
18
19         # == OAuth Authentication ==
20         #
21         # This mode of authentication is the new preferred way
22         # of authenticating with Twitter.
23
24         # The consumer keys can be found on your application's Details
25         # page located at https://dev.twitter.com/apps (under "OAuth settings")
26         consumer_key=secrets.twitter_consumer_key
27         consumer_secret=secrets.twitter_consumer_secret
28
29         # The access tokens can be found on your applications's Details
30         # page located at https://dev.twitter.com/apps (located
31         # under "Your access token")
32         access_token=secrets.twitter_access_token
33         access_token_secret=secrets.twitter_access_token_secret
34
35         auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
36         auth.set_access_token(access_token, access_token_secret)
37         self.api = tweepy.API(auth)
38
39     def debug_prefix(self):
40         return "twitter"
41
42     def linkify(self, value):
43         return self.urlfinder.sub(r'<a href="\1">\1</a>', value)
44
45     def periodic_render(self, key):
46         if key == "Fetch Tweets":
47             return self.fetch_tweets()
48         elif key == "Shuffle Tweets":
49             return self.shuffle_tweets()
50         else:
51             raise error('Unexpected operation')
52
53     def fetch_tweets(self):
54         try:
55             tweets = self.api.home_timeline(tweet_mode='extended', count=200)
56         except:
57             print("Exception while fetching tweets!")
58             return False
59         for tweet in tweets:
60             author = tweet.author.name
61             author_handle = tweet.author.screen_name
62             self.handles_by_author[author] = author_handle
63             if author not in self.tweets_by_author:
64                 self.tweets_by_author[author] = list()
65             l = self.tweets_by_author[author]
66             l.append(tweet)
67         return True
68
69     def shuffle_tweets(self):
70         authors = list(self.tweets_by_author.keys())
71         author = random.choice(authors)
72         handle = self.handles_by_author[author]
73         tweets = self.tweets_by_author[author]
74         already_seen = set()
75         f = file_writer.file_writer('twitter_10_none.html')
76         f.write('<TABLE WIDTH=96%><TR><TD WIDTH=86%>')
77         f.write('<H2>%s (@%s)</H2></TD>\n' % (author, handle))
78         f.write('<TD ALIGN="right" VALIGN="top">')
79         f.write('<IMG SRC="twitter.png" WIDTH=42></TD></TR></TABLE>\n')
80         f.write('<HR>\n<UL>\n')
81         count = 0
82         length = 0
83         for tweet in tweets:
84             text = tweet.full_text
85             if ((text not in already_seen) and
86                 (not self.filter.contains_bad_words(text))):
87                 already_seen.add(text)
88                 text = self.linkify(text)
89                 f.write('<LI><B>%s</B>\n' % text)
90                 count += 1
91                 length += len(text)
92                 if count > 3 or length > 270:
93                     break
94         f.write('</UL>\n')
95         f.close()
96         return True
97
98 # Test
99 t = twitter_renderer(
100     {"Fetch Tweets" : 1,
101      "Shuffle Tweets" : 1})
102 #x = "bla bla bla https://t.co/EjWnT3UA9U bla bla"
103 #x = t.linkify(x)
104 #print x
105 if t.fetch_tweets() == 0:
106     print("Error fetching tweets, none fetched.")
107 else:
108     t.shuffle_tweets()