Skip to content

Instantly share code, notes, and snippets.

@johnsibly
Last active January 8, 2024 13:27
Show Gist options
  • Save johnsibly/806a7190fbdc4b439ed040f327e6e679 to your computer and use it in GitHub Desktop.
Save johnsibly/806a7190fbdc4b439ed040f327e6e679 to your computer and use it in GitHub Desktop.
Javascript for posting a message to a Microsoft Teams channel
'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;
}
}
@voidbar
Copy link

voidbar commented Jan 16, 2022

This doesn't work for me. Fixed it by letting Axios handle the content-length calculation.
See more at this answer at stackoverflow

@johnsibly
Copy link
Author

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.

@johnsibly
Copy link
Author

FYI run this script using the syntax node post-message-to-teams.js "test" "test"

@fenster89411
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment