Advertisement
Guest User

dump_bsky_followers.py

a guest
Jul 13th, 2023
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.21 KB | Source Code | 0 0
  1. #!/usr/bin/python3
  2.  
  3. # In this house, we don't import all of Pandas just write a bloody .csv
  4. from csv import DictWriter
  5. from datetime import datetime
  6. import sys
  7. import time
  8.  
  9. # In this house, we import the standard library *first*:
  10. # https://peps.python.org/pep-0008/#imports
  11. from atproto import Client
  12.  
  13. # In this house, functions are first-class objects.
  14. def how_long(f, *args, **kwargs):
  15.     then = datetime.now()
  16.     res = f(*args, **kwargs)
  17.     now = datetime.now()
  18.     return res, (now - then).total_seconds()
  19.  
  20. # In this house, we avoid extraneous whitespace:
  21. # https://peps.python.org/pep-0008/#pet-peeves
  22. def all_followers(client, handle, batch=100):
  23.     api_args = {'actor': handle, 'limit': batch}
  24.     chunk, latency = how_long(client.bsky.graph.get_followers, api_args)
  25.     while chunk.cursor:
  26.         yield from chunk.followers
  27.         # Very slighty throttle the API calls...
  28.         time.sleep(latency)
  29.         chunk, latency = how_long(client.bsky.graph.get_followers,
  30.             {**api_args, **{'cursor': chunk.cursor}})
  31.        
  32. def prof2dict(prof):
  33.     return {k: prof.__dict__.get(k) for k in __PROFILE_KEYS__}
  34.  
  35. __PROFILE_KEYS__ = ('handle', 'avatar', 'description', 'displayName')
  36.    
  37. def dump_followers(client, handle, fname=None):
  38.     if fname is None:
  39.         fname = '_'.join(handle.split('.')) + '.csv'
  40.     with open(fname, 'w') as csvfile:
  41.         writer = DictWriter(csvfile, __PROFILE_KEYS__)
  42.         writer.writeheader()
  43.         writer.writerows(map(prof2dict, all_followers(client, handle)))
  44.  
  45. # In this house, typing 'bsky.social' gets tedious.
  46. def bskyify(name):
  47.     if len(name.split('.')) < 2:
  48.         return '.'.join((name, 'bsky', 'social'))
  49.     else:
  50.         return name
  51.    
  52. if __name__ == '__main__':
  53.     if len(sys.argv) != 4:
  54.         print('USAGE: username, password, target username')
  55.     else:
  56.         _, uname, pw, target = sys.argv
  57.         uname = bskyify(uname)
  58.         target = bskyify(target)
  59.        
  60.         at_client = Client()
  61.         try:
  62.             at_client.login(uname, pw)
  63.         except:
  64.             at_client = None
  65.             print("Couldn't log-in!")
  66.            
  67.         if at_client:
  68.             dump_followers(at_client, target)
  69.  
Tags: python Bluesky
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement