diff options
-rw-r--r-- | print_mutual_friends.py | 20 | ||||
-rw-r--r-- | track_online.py | 75 |
2 files changed, 65 insertions, 30 deletions
diff --git a/print_mutual_friends.py b/print_mutual_friends.py index 6895a3c..b3beb39 100644 --- a/print_mutual_friends.py +++ b/print_mutual_friends.py @@ -8,26 +8,30 @@ def users_get(user_ids): response = api.users_get(user_ids=','.join(user_ids), fields='screen_name') if len(response) < len(user_ids): - print('Error: couldn\'t find at least one of the users!', - file=sys.stderr) - sys.exit(1) + raise RuntimeError('Couldn\'t find at least one of the users!') return response def friends_get(user_id): return api.friends_get(user_id=user_id) -def format_friend(user): - s = '{} {}'.format(user['last_name'], user['first_name']) +def extract_screen_name_or_uid(user): if 'screen_name' in user: - s += ' ({})'.format(user['screen_name']) - return s + return user['screen_name'] + return 'id' + str(user['uid']) + +def format_friend(user): + return '{} {} ({})'.format( + user['last_name'], user['first_name'], + extract_screen_name_or_uid(user)) if __name__ == '__main__': import argparse - parser = argparse.ArgumentParser() + parser = argparse.ArgumentParser( + description='Learn who your ex and her new boyfriend are both friends with.') parser.add_argument(metavar='UID', dest='user_ids', nargs='+', help='user IDs or "screen names"') args = parser.parse_args() + users = users_get(args.user_ids) user_ids = map(lambda user: user['uid'], users) friend_lists = map(frozenset, map(friends_get, user_ids)) diff --git a/track_online.py b/track_online.py index 7a4085d..ed43f11 100644 --- a/track_online.py +++ b/track_online.py @@ -2,7 +2,9 @@ # This file is licensed under the terms of the MIT License. # See LICENSE.txt for details. +import argparse from datetime import datetime +import logging import time import sys @@ -12,31 +14,26 @@ def users_get(user_ids): response = api.users_get(user_ids=','.join(user_ids), fields='online,last_seen') if len(response) < len(user_ids): - print('Error: couldn\'t find at least one of the users!', - file=sys.stderr) - sys.exit(1) + raise RuntimeError('Couldn\'t update status of at least one of the users!') return response -def log(s): - print('[{}] {}'.format(datetime.now().replace(microsecond=0), s)) - def format_user_name(user): return '{} {}'.format(user['last_name'], user['first_name']) def user_is_online(user): - log('{} is ONLINE'.format(format_user_name(user))) + logging.info('{} is ONLINE'.format(format_user_name(user))) def user_is_offline(user): user_name = format_user_name(user) - log('{} is OFFLINE'.format(user_name)) + logging.info('{} is OFFLINE'.format(user_name)) last_seen = datetime.fromtimestamp(user['last_seen']['time']) - log('{} was last seen at {}'.format(user_name, last_seen)) + logging.info('{} was last seen at {}'.format(user_name, last_seen)) def user_went_online(user): - log('{} went ONLINE'.format(format_user_name(user))) + logging.info('{} went ONLINE'.format(format_user_name(user))) def user_went_offline(user): - log('{} went OFFLINE'.format(format_user_name(user))) + logging.info('{} went OFFLINE'.format(format_user_name(user))) def print_user(status): if status['online']: @@ -44,25 +41,59 @@ def print_user(status): else: user_is_offline(status) -def print_user_update(status): +def print_status_update(status): if status['online']: user_went_online(status) else: user_went_offline(status) -if __name__ == '__main__': - import argparse - parser = argparse.ArgumentParser() - parser.add_argument(metavar='UID', dest='user_ids', nargs='+', - help='user IDs or "screen names"') - args = parser.parse_args() - users = users_get(args.user_ids) +def parse_timeout(source): + timeout = int(source) + if timeout < 1: + raise argparse.ArgumentTypeError( + 'please specify a positive number of seconds as refresh timeout') + return timeout + +DEFAULT_TIMEOUT=5 + +def print_initial_status(user_ids): + users = users_get(user_ids) for user in users: print_user(user) + return users + +def loop_update_status(users, user_ids, timeout=DEFAULT_TIMEOUT): while True: - time.sleep(5) - updated_users = users_get(args.user_ids) + time.sleep(timeout) + updated_users = users_get(user_ids) for i in range(len(updated_users)): if users[i]['online'] != updated_users[i]['online']: users[i] = updated_users[i] - print_user_update(updated_users[i]) + print_status_update(updated_users[i]) + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description='Track when people go online/offline.') + parser.add_argument(metavar='UID', dest='user_ids', nargs='+', + help='user IDs or "screen names"') + parser.add_argument('-t', '--timeout', default=DEFAULT_TIMEOUT, + type=parse_timeout, + help='set refresh interval (seconds)') + parser.add_argument('-l', '--log', type=argparse.FileType('w'), + default=sys.stdout, + help='set log file path (stdout by default)') + args = parser.parse_args() + + logging.basicConfig(format='[%(asctime)s] %(message)s', + stream=args.log, + level=logging.INFO, + datefmt='%Y-%m-%d %H:%M:%S') + + try: + users = print_initial_status(args.user_ids) + loop_update_status(users, args.user_ids, timeout=args.timeout) + except KeyboardInterrupt: + pass + except Exception as e: + logging.exception(e) + sys.exit(1) |