Created
March 11, 2023 10:36
-
-
Save pstef/b77a4b7103ac7210731db366f056a803 to your computer and use it in GitHub Desktop.
Generate plain text mastodon threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# https://codeberg.org/edent/Mastodon_Tools/src/commit/b284814810db1aaa5b0dfe98afa668f8d35eb525/threads.py | |
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() | |
url = urlparse(args.url) | |
path_id = url.path.split("/")[-1] | |
if path_id.isdigit(): | |
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() | |
mastodon = Mastodon(api_base_url=url.scheme+'://'+url.netloc) | |
root = mastodon.status(status_id) | |
# 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: | |
root = conversation["ancestors"][0] | |
conversation = mastodon.status_context(root["id"]) | |
tree = Tree() | |
# Add any subsequent replies | |
for status in [root] + conversation["descendants"]: | |
try: | |
tree.create_node(status["account"]["username"] + ": " + BeautifulSoup(status["content"], features="html.parser").get_text(), status["id"], parent=status["in_reply_to_id"]) | |
except: | |
print("Problem adding node to the tree") | |
tree.show() |
Author
pstef
commented
Nov 21, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment