const author='NQxxxxxxx'; // Tu userId
const accessToken='AQUg-xxxxxxx'; // El accessToken, una cadena superlarga
const url = 'https://api.linkedin.com'
const label = 'Publicar en Linkedin';
const lifecycleState='PUBLISHED';
const visibility = 'PUBLIC';
function checkEmail() {
try{
unreadEmail()
}catch(error){
Logger.log(error)
}
}
function unreadEmail() {
const ts = GmailApp.search(`subject:${label} is:unread to:me from:me`);
ts.forEach(t => {
t.getMessages().forEach(m => {
processEmail(m);
m.markRead();
});
});
}
function processEmail(m) {
const images = m.getAttachments();
let medias = [];
if( images ){
images.forEach( (a)=>{ medias.push(uploadImage(a))} )
}
const body=html2text(m.getBody())
var payload = {
"author": "urn:li:person:"+author,
"lifecycleState":lifecycleState,
"visibility": {
"com.linkedin.ugc.MemberNetworkVisibility":visibility
},
"specificContent":{
"com.linkedin.ugc.ShareContent":{
"shareCommentary":{
"text": body
},
"shareMediaCategory" : medias.length ? "IMAGE" : "NONE",
"media":medias
}
}
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload': JSON.stringify(payload),
'headers': {
'Authorization': `Bearer ${accessToken}`,
'X-Restli-Protocol-Version': '2.0.0'
}
};
Logger.log(options)
const resp = UrlFetchApp.fetch(`${url}/v2/ugcPosts`, options);
Logger.log(resp)
}
function html2text(body){
const ret = `${body}`.replaceAll('<br>','\n')
.replaceAll('</div>','\n')
.replaceAll(/<[^>]+>/g, '')
.replaceAll(""",'"')
.replaceAll(""a",'á')
.replaceAll(""e",'é')
.replaceAll(""i",'í')
.replaceAll(""o",'ó')
.replaceAll(""u",'ú')
return ret;
}
function uploadImage(attachment) {
var imgPayload = {
"registerUploadRequest": {
"recipes": [
"urn:li:digitalmediaRecipe:feedshare-image"
],
"owner": "urn:li:person:"+author,
"serviceRelationships": [
{
"relationshipType": "OWNER",
"identifier": "urn:li:userGeneratedContent"
}
],
"supportedUploadMechanism":[
"SYNCHRONOUS_UPLOAD"
]
}
}
var imgOptions = {
'method' : 'post',
'contentType': 'application/json',
'payload': JSON.stringify(imgPayload),
'headers': {
'Authorization': `Bearer ${accessToken}`,
'X-Restli-Protocol-Version': '2.0.0'
}
};
const resp = UrlFetchApp.fetch(`${url}/v2/assets?action=registerUpload`, imgOptions);
Logger.log(resp);
const json = JSON.parse(resp)
const uploadUrl = json.value.uploadMechanism["com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest"].uploadUrl;
const mediaId = json.value.asset;
var optionsImage = {
method : "put",
payload : attachment.copyBlob(),
headers:{
'Authorization': `Bearer ${accessToken}`,
'Accept':'*/*'
}
};
Logger.log(uploadUrl)
var respImage = UrlFetchApp.fetch(uploadUrl, optionsImage).getContentText();
Logger.log(respImage)
return {
status:'READY',
media: mediaId
}
}