-
-
Save johnsibly/806a7190fbdc4b439ed040f327e6e679 to your computer and use it in GitHub Desktop.
'use strict'; | |
const axios = require('axios'); // axios must be installed via npm i axios | |
const webhookURL = "https://outlook.office.com/webhook/1234567890"; // Replace with a valid webhool URL obtained by adding an "Incomming Webhook" connector to your teams channel | |
if (process.argv.length === 4) { | |
const title = process.argv[2]; | |
const message = process.argv[3]; | |
console.log(`${title}, ${message}`); | |
postMessageToTeams(title, message); | |
} else { | |
console.log('Usage: node post-message-to-teams.js title messageBody'); | |
} | |
async function postMessageToTeams(title, message) { | |
const card = { | |
'@type': 'MessageCard', | |
'@context': 'http://schema.org/extensions', | |
'themeColor': "0072C6", // light blue | |
summary: 'Summary description', | |
sections: [ | |
{ | |
activityTitle: title, | |
text: message, | |
}, | |
], | |
}; | |
try { | |
const response = await axios.post(webhookURL, card, { | |
headers: { | |
'content-type': 'application/vnd.microsoft.teams.card.o365connector' | |
}, | |
}); | |
return `${response.status} - ${response.statusText}`; | |
} catch (err) { | |
return err; | |
} | |
} |
Thanks for your feedback @voidbar. This worked back in 2019, but I've now updated the gist to let Axios calculate the content-length as you suggest.
FYI run this script using the syntax node post-message-to-teams.js "test" "test"
will this work as a javascript function triggered by a button click? on first attempt I got
teamsmessagesender.html:40
Error sending message to Teams:
X {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
code
:
"ERR_NETWORK"
config
:
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
:
"Network Error"
name
:
"AxiosError"
request
:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
stack
:
"AxiosError: Network Error\n at w.onerror (https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js:1:23886)"
[[Prototype]]
:
Error
This doesn't work for me. Fixed it by letting Axios handle the
content-length
calculation.See more at this answer at stackoverflow