#!/usr/bin/env python import config from mastodon import Mastodon from treelib import Node, Tree from datetime import datetime, timedelta from urllib.parse import urlparse import argparse from bs4 import BeautifulSoup # Take a command line argument. e.g. python3 threads.py https://mastodon.example/@me@somewhere/1234 parser = argparse.ArgumentParser(description='Display a tree based on a Mastodon conversation.') parser.add_argument('url', metavar='URl', type=str, help='A URl of a post on your instance of Mastodon') args = parser.parse_args() path = urlparse(args.url).path path_list = path.split("/") path_id = path_list[-1] if path_id.isdigit() : # Status ID # This is the ID from *your* instance status_id = int(path_id) else : print("Hmmm... That doesn't look like a valid Mastodon Status URl.\n" + "It should look like https://mastodon.example/@me@somewhere/1234\n" + "The last part of the URl must be the status ID, which is a number." ) exit() # Set up access mastodon = Mastodon( api_base_url=config.instance, access_token=config.access_token ) # Get the status status = mastodon.status(status_id) # Get the conversation tree # Documentation https://docs.joinmastodon.org/entities/context/ conversation = mastodon.status_context(status_id) # If there are ancestors, that means we are only on a single branch. # The 0th ancestor is the "root" of the conversation tree if len(conversation["ancestors"]) > 0 : status = conversation["ancestors"][0] status_id = status["id"] conversation = mastodon.status_context(status_id) # Create a new tree tree = Tree() # Add the "root" try : tree.create_node( str(status["created_at"])[:16] + " " + status["account"]["username"] + ": " + BeautifulSoup(status["content"], features="html.parser").get_text() + " " + status["uri"], status["id"]) except : print("Problem adding node to the tree") # Add any subsequent replies for status in conversation["descendants"] : try : tree.create_node(str(status["created_at"])[:16] + " " + status["account"]["username"] + ": " + BeautifulSoup(status["content"], features="html.parser").get_text() + " " + status["uri"], status["id"], parent=status["in_reply_to_id"]) except : # If a parent node is missing print("Problem adding node to the tree") # Display tree.show()