From af3197c0435dbb6221ffef86886c69bfad464b76 Mon Sep 17 00:00:00 2001 From: Devin Gaffney Date: Fri, 8 Nov 2024 03:46:43 -0800 Subject: [PATCH] Create get_posts_by_url.py --- examples/get_posts_by_url.py | 54 ++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 examples/get_posts_by_url.py diff --git a/examples/get_posts_by_url.py b/examples/get_posts_by_url.py new file mode 100644 index 00000000..d72f8a08 --- /dev/null +++ b/examples/get_posts_by_url.py @@ -0,0 +1,54 @@ +from atproto import Client, IdResolver, models +from typing import Optional + +def fetch_posts(client: Client, resolver: IdResolver, url: str) -> Optional[models.app.bsky.feed.get_posts.Response]: + """ + Fetches a post using its Bluesky URL. + Args: + client (Client): Authenticated Atproto client. + resolver (IdResolver): Resolver instance for DID lookup. + url (str): URL of the Bluesky post. + Returns: + Optional[models.Record]: The hydrated post record if found, otherwise None. + """ + try: + # Extract the handle and post ID from the URL + parts = url.split("/") + handle = parts[4] # Username in the URL + post_id = parts[6] # Post ID in the URL + # Resolve the DID for the username + did = resolver.handle.resolve(handle) + if not did: + print(f"Could not resolve DID for handle '{handle}'.") + return None + # Construct the `at://` URI for the post + at_uri = f"at://{did}/app.bsky.feed.post/{post_id}" + # Fetch and return the post record + post_response = client.get_posts([at_uri]) + return post_response + except Exception as e: + print(f"Error fetching post for URL {url}: {e}") + return None + +def main() -> None: + # Initialize client and authenticate + client = Client() + client.login('my-handle', 'my-password') + + # Initialize IdResolver for DID resolution + resolver = IdResolver() + + # Define the URL of the post to fetch + url = "https://bsky.app/profile/danabra.mov/post/3lagnt6bpkc2l" + + # Fetch the post + post_record = fetch_posts(client, resolver, url) + + # Display the post details + if post_record: + print(f"Post Content: {post_record.text}") + else: + print("Post could not be fetched.") + +if __name__ == '__main__': + main()