4 import profanity_filter
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)
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_\\.]+)")
19 # == OAuth Authentication ==
21 # This mode of authentication is the new preferred way
22 # of authenticating with Twitter.
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
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
35 auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
36 auth.set_access_token(access_token, access_token_secret)
37 self.api = tweepy.API(auth)
39 def debug_prefix(self):
42 def linkify(self, value):
43 return self.urlfinder.sub(r'<a href="\1">\1</a>', value)
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()
51 raise error('Unexpected operation')
53 def fetch_tweets(self):
55 tweets = self.api.home_timeline(tweet_mode='extended', count=200)
57 print("Exception while fetching 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]
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]
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')
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)
92 if count > 3 or length > 270:
101 "Shuffle Tweets" : 1})
102 #x = "bla bla bla https://t.co/EjWnT3UA9U bla bla"
105 if t.fetch_tweets() == 0:
106 print("Error fetching tweets, none fetched.")