Learning Python Network Programming

(Sean Pound) #1

APIs in Action


found = True
break
if found:
timezone = pytz.timezone(tz)
time = datetime.datetime.now(timezone).strftime('%H:%M')
reply = '@{} The time in {} is currently
{}'.format(username, place, time)
else:
reply = "@{} Sorry, I didn't recognize " \
"'{}' as a city".format(username, place)
print(reply)

if __name__ == '__main__':
auth_obj = init_auth()
since_id = 1
for tweet in get_mentions(since_id, auth_obj):
process_tweet(tweet)

The bulk of processtweet() is used for formatting the tweet's text and processing
the time zone data. First we will remove any @username mentions and #hashtags
from the tweet. Then, we prepare the remaining tweet text to be compared with the
time zone names database. The time zone names database is held in pytz.common

timezones, but the names also contain regions, which are separated from the names
with slashes (/). Also, in these names underscores are used in place of spaces.


We scan through the database checking against the formatted tweet text. If a match is
found, then we construct a reply, which contains the local time of the matched time
zone. For this, we use the datetime module along with a time zone object generated
by pytz. If we don't find a match in the time zone database, then we compose a
reply to let the user know the same. Then, we print our reply to screen to check if it's
working as expected.


Again, before running this, we may want to create a few tweets that contain just
a city name and mention our world clock app account, so that the function has
something to process. Some cities that appear in the time zone database are
Dublin, New York, and Tokyo.


Give it a try! When you run it, you will get some tweet reply texts on the screen,
which contain the cities and the current local times for those cities.


Rate limits


If we run the aforementioned several times, then we'll find that it will stop working
after a while. Either the credentials will temporarily fail to validate, or the HTTP
request in get_mentions() will fail.

Free download pdf