File size: 4,503 Bytes
fb07b17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
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}")