Mastodon_Tools/threads.py

49 wiersze
1.6 KiB
Python
Czysty Zwykły widok Historia

2022-11-15 15:41:07 +00:00
from datetime import datetime, timedelta
from mastodon import Mastodon
from treelib import Node, Tree
2022-11-16 07:09:06 +00:00
from bs4 import BeautifulSoup
2022-11-15 15:41:07 +00:00
import config
# Status ID
# This is the ID from *your* instance
2022-11-16 07:09:06 +00:00
status_id = 109343943300929632
2022-11-15 15:41:07 +00:00
# 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(
2022-11-16 07:09:06 +00:00
str(status["created_at"])[:16] + " " + status["account"]["username"] + ": " + BeautifulSoup(status["content"], features="html.parser").get_text() + " " + status["uri"], status["id"])
2022-11-15 15:41:07 +00:00
except :
print("Problem adding node to the tree")
# Add any subsequent replies
for status in conversation["descendants"] :
try :
2022-11-16 07:09:06 +00:00
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"])
2022-11-15 15:41:07 +00:00
except :
# If a parent node is missing
print("Problem adding node to the tree")
# Display
tree.show()