import requests import os from dotenv import load_dotenv from agents import function_tool # Load environment variables load_dotenv() # # Constants LINKEDIN_ACCESS_TOKEN = os.getenv("LINKEDIN_ACCESS_TOKEN") # Headers for LinkedIn API requests HEADERS = { "Authorization": f"Bearer {LINKEDIN_ACCESS_TOKEN}", "X-Restli-Protocol-Version": "2.0.0", "Content-Type": "application/json", } def get_user_info(): """Retrieve the authenticated user's LinkedIn information.""" url = "https://api.linkedin.com/v2/userinfo" response = requests.get(url, headers=HEADERS) if response.status_code == 200: return response.json() else: print(f"Error fetching user info: {response.status_code}") return None def register_image_upload(): """Register an image upload with LinkedIn.""" user_info = get_user_info() if not user_info: print("Failed to retrieve user information.") return None, None url = "https://api.linkedin.com/v2/assets?action=registerUpload" payload = { "registerUploadRequest": { "recipes": ["urn:li:digitalmediaRecipe:feedshare-image"], "owner": f"urn:li:person:{user_info['sub']}", "serviceRelationships": [ { "relationshipType": "OWNER", "identifier": "urn:li:userGeneratedContent", } ], } } response = requests.post(url, headers=HEADERS, json=payload) if response.status_code == 200: return response.json().get("value", {}).get("uploadMechanism", {}).get( "com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest", {} ).get("uploadUrl"), response.json().get("value", {}).get("asset") else: print(f"Error registering image upload: {response.status_code}") return None, None def upload_image(upload_url, image_source): """ Upload the image to LinkedIn. Args: upload_url (str): The LinkedIn upload URL image_source (str): Either a local file path or a URL to the image """ if image_source.startswith(("http://", "https://")): # Handle URL response = requests.get(image_source) if response.status_code != 200: print(f"Error fetching image from URL: {response.status_code}") return False image_data = response.content else: # Handle local file try: with open(image_source, "rb") as image_file: image_data = image_file.read() except FileNotFoundError: print(f"Error: Image file not found at {image_source}") return False response = requests.post( upload_url, headers={"Authorization": f"Bearer {LINKEDIN_ACCESS_TOKEN}"}, data=image_data, ) if response.status_code == 201: print("Image uploaded successfully.") return True else: print(f"Error uploading image: {response.status_code}") return False @function_tool def create_post_links_image(image_path: str, post_text: str): """Create a post on LinkedIn with the uploaded image.""" # Step 1: Register image upload upload_url, image_urn = register_image_upload() if not (upload_url and image_urn): print("Failed to register image upload.") return # Step 2: Upload the image if not upload_image(upload_url, image_path): print("Failed to upload image.") return # Step 3: Create the post user_info = get_user_info() if not user_info: print("Failed to retrieve user information.") return url = "https://api.linkedin.com/v2/ugcPosts" payload = { "author": f"urn:li:person:{user_info['sub']}", "lifecycleState": "PUBLISHED", "specificContent": { "com.linkedin.ugc.ShareContent": { "shareCommentary": {"text": post_text}, "shareMediaCategory": "IMAGE", "media": [ { "status": "READY", "media": image_urn, } ], } }, "visibility": {"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"}, } response = requests.post(url, headers=HEADERS, json=payload) if response.status_code == 201: print("Post created successfully.") else: print(f"Error creating post: {response.status_code}")