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