Team Ai
Apppublic

Coding-With-Raptor/Likendin-Agent

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
raw_function.py111 linesDownload Raw Back to mcp_server_tools
1from dotenv import load_dotenv, find_dotenv2import requests3import os4 5# Constants6LINKEDIN_ACCESS_TOKEN = os.getenv("LINKEDIN_ACCESS_TOKEN")7 8load_dotenv(find_dotenv())9 10 11HEADERS = {12    "Authorization": f"Bearer {LINKEDIN_ACCESS_TOKEN}",13    "Content-Type": "application/json",14}15 16 17def get_user_id():18    """19    Retrieve LinkedIn user profile information using the /userinfo endpoint.20 21    Returns:22        dict: User profile information or None if an error occurs.23    """24    url = "https://api.linkedin.com/v2/userinfo"25 26    try:27        response = requests.get(url, headers=HEADERS)28        response.raise_for_status()29        return response.json()30    except requests.exceptions.RequestException as e:31        print(f"Error fetching user info: {e}")32        return None33 34 35def get_user_info():36    """Retrieve the authenticated user's LinkedIn information."""37    url = "https://api.linkedin.com/v2/userinfo"38    response = requests.get(url, headers=HEADERS)39    if response.status_code == 200:40        return response.json()41    else:42        print(f"Error fetching user info: {response.status_code}")43        return None44 45 46def register_image_upload():47    """Register an image upload with LinkedIn."""48    user_info = get_user_info()49    if not user_info:50        print("Failed to retrieve user information.")51        return None, None52    url = "https://api.linkedin.com/v2/assets?action=registerUpload"53    payload = {54        "registerUploadRequest": {55            "recipes": ["urn:li:digitalmediaRecipe:feedshare-image"],56            "owner": f"urn:li:person:{user_info['sub']}",57            "serviceRelationships": [58                {59                    "relationshipType": "OWNER",60                    "identifier": "urn:li:userGeneratedContent",61                }62            ],63        }64    }65    response = requests.post(url, headers=HEADERS, json=payload)66    if response.status_code == 200:67        return response.json().get("value", {}).get("uploadMechanism", {}).get(68            "com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest", {}69        ).get("uploadUrl"), response.json().get("value", {}).get("asset")70    else:71        print(f"Error registering image upload: {response.status_code}")72        return None, None73 74 75def upload_image(upload_url, image_source):76    """77    Upload the image to LinkedIn.78 79    Args:80        upload_url (str): The LinkedIn upload URL81        image_source (str): Either a local file path or a URL to the image82    """83    if image_source.startswith(("http://", "https://")):84        # Handle URL85        response = requests.get(image_source)86        if response.status_code != 200:87            print(f"Error fetching image from URL: {response.status_code}")88            return False89        image_data = response.content90    else:91        # Handle local file92        try:93            with open(image_source, "rb") as image_file:94                image_data = image_file.read()95        except FileNotFoundError:96            print(f"Error: Image file not found at {image_source}")97            return False98 99    response = requests.post(100        upload_url,101        headers={"Authorization": f"Bearer {LINKEDIN_ACCESS_TOKEN}"},102        data=image_data,103    )104 105    if response.status_code == 201:106        print("Image uploaded successfully.")107        return True108    else:109        print(f"Error uploading image: {response.status_code}")110        return False111