Skip to content

Instantly share code, notes, and snippets.

@gmariette
Last active June 29, 2023 13:52
Show Gist options
  • Select an option

  • Save gmariette/e7bf063c81e57552be6ba8d67156fee0 to your computer and use it in GitHub Desktop.

Select an option

Save gmariette/e7bf063c81e57552be6ba8d67156fee0 to your computer and use it in GitHub Desktop.
def ShareContentOnLinkedin(myposttitle, myposturl, myposttags):
######## LINKEDIN PART
# First generated a client_id and a client_secret within the app page on your linkedin account
# Then follow this procedure to generate a code https://medium.com/@ellesmuse/how-to-get-a-linkedin-access-token-a53f9b62f0ce
# Following code will allow you to get an access token ! use only once (token as to be generated every 60 days)
# code = 'xxx'
# url = 'https://www.linkedin.com/oauth/v2/accessToken'
# data = {"client_id": "xxx", "client_secret": "xxx", "grant_type": "authorization_code", "redirect_uri": "https://movingmarseille.wordpress.com/", "code": code}
# headers = {"Content-Type": "application/x-www-form-urlencoded"}
# r = requests.post(url, data=data, headers=headers)
# print(r.content)
# Then you will be able to post on linkedin
access_token = "xxx"
linkedinBaseUrl = 'https://api.linkedin.com/v2/'
headers = {'Authorization': 'Bearer ' + access_token}
r = requests.get(linkedinBaseUrl+'me?projection=(id)', headers=headers)
linkedInProfile = r.json()
#create the author variable in linkedin urn format
author = "urn:li:person:"+linkedInProfile['id']
api_url = linkedinBaseUrl+'ugcPosts'
#concat all tags extracted from medium with an hashtag
myTagsstr = ' #'.join(map(str, myposttags))
post_data = {
"author": author,
"lifecycleState": "PUBLISHED",
"specificContent": {
"com.linkedin.ugc.ShareContent": {
"shareCommentary": {
"text": "Check out my new Medium post : " + myposttitle + "\n" + myposturl + "\n #" + myTagsstr + "\n \n This was automaticaly posted from AWS Lambda"
},
"shareMediaCategory": "NONE"
},
},
"visibility": {
"com.linkedin.ugc.MemberNetworkVisibility": "CONNECTIONS"
},
}
response = requests.post(api_url, headers=headers, json=post_data)
if response.status_code == 201:
print("Success")
print(response.content)
else:
print(response.content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment