Skip to content

Instantly share code, notes, and snippets.

@lucahammer
Last active February 12, 2024 11:29
Show Gist options
  • Save lucahammer/bb2770114fe734b2c96250ada6df7ca5 to your computer and use it in GitHub Desktop.
Save lucahammer/bb2770114fe734b2c96250ada6df7ca5 to your computer and use it in GitHub Desktop.
Mastodon Network visualization (for use with Gephi)
'''
Replace base_url, access_token and user_id
'''
import requests
base_url = 'https://vis.social/api/v1/'
# https://takahashim.github.io/mastodon-access-token/
access_token = '###'
# which followers to visualize
user_id = '1'
print('Started.')
followers = []
r = requests.get(base_url+'accounts/'+user_id+'?access_token='+access_token)
followers.append (r.json())
r = requests.get(base_url+'accounts/'+user_id+'/followers?limit=80&access_token='+access_token)
followers += r.json()
while 'next' in r.links:
r = requests.get(r.links['next']['url']+'&access_token='+access_token)
followers += r.json()
print('Followers collected: ' + str(len(followers)))
print('Expect the collection of followings to take at least 1 second per follower.')
edges = []
for follower in followers:
#print(follower)
r = requests.get(base_url+'accounts/'+follower['id']+'/following?limit=40&access_token='+access_token)
followings = r.json()
for following in followings:
edges.append(follower['id'] + ',' + following['id'])
while 'next' in r.links:
r = requests.get(r.links['next']['url']+'&access_token='+access_token)
followings = r.json()
for following in followings:
edges.append(follower['id'] + ',' + following['id'])
with open('vis_social.gdf', 'w') as f:
f.write ('nodedef>name VARCHAR,label VARCHAR,followers_count VARCHAR,following_count VARCHAR,statuses_count VARCHAR\n')
for follower in followers:
f.write (follower['id']+','+follower['acct']+','+str(follower['followers_count'])+','+str(follower['following_count'])+','+str(follower['statuses_count'])+'\n')
f.write ('edgedef>node1 VARCHAR,node2 VARCHAR,directed BOOLEAN\n')
for edge in edges:
f.write (edge+',true\n')
print('Done. You can now open the generated .gdf with Gephi')
@lucahammer
Copy link
Author

Web-version written in Javascript: https://mastoviz.glitch.me/

@DennisFaucher
Copy link

Thanks for this. I'm getting this error but working out a way to fix the error.

Traceback (most recent call last):
  File "/Volumes/1TB_USB/Downloads/gephi_mastodon.py", line 43, in <module>
    edges.append(follower['id'] + ',' + following['id'])
TypeError: string indices must be integers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment