Template Content
About the template
About ScriptRunner Connect
What is ScriptRunner Connect?
Can I try it out for free?
Yes. ScriptRunner Connect comes with a forever free tier.
Can I customize the integration logic?
Absolutely. The main value proposition of ScriptRunner Connect is that you'll get full access to the code that is powering the integration, which means you can make any changes to the the integration logic yourself.
Can I change the integration to communicate with additional apps?
Yes. Since ScriptRunner Connect specializes in enabling complex integrations, you can easily change the integration logic to connect to as many additional apps as you need, no limitations.
What if I don't feel comfortable making changes to the code?
First you can try out our AI assistant which can help you understand what the code does, and also help you make changes to the code. Alternatively you can hire our professionals to make the changes you need or build new integrations from scratch.
Do I have to host it myself?
No. ScriptRunner Connect is a fully managed SaaS (Software-as-a-Service) product.
What about security?
ScriptRunner Connect is ISO 27001 and SOC 2 certified. Learn more about our security.
Template Content
This template demonstrates how to send a private notification message in Microsoft Teams for a watcher in Confluence Data Center (or server) when a page is updated.
User.ReadBasic.All
and Chat.ReadWrite
permissions. After changing permissions you will have to reauthorize your MS Graph Connector.Update a page in your Confluence On-Premise instance, after successful event processing a private chat message should be sent in Microsoft Teams to each page watcher, providing that their Confluence On-Premise user can be matched with an account on Microsoft Teams.
import Microsoft from './api/microsoft';
import ConfluenceOnPremise from './api/confluence/on-premise';
import { PageUpdatedEvent } from '@sr-connect/confluence-on-premise/events';
import { User } from '@managed-api/confluence-on-prem-v7-core/definitions/User';
import { GetContentResponseOK } from '@managed-api/confluence-on-prem-v7-core/types/content';
/**
* This function listens to Confluence page updated event, and when triggered, finds all the watchers for given page, tries to match them with users in Teams (by email) and then send a message to them.
*
* @param event Object that holds Page Updated event data
* @param context Object that holds function invocation context data
*/
export default async function (event: PageUpdatedEvent, context: Context): Promise<void> {
if (context.triggerType === 'MANUAL') {
console.error('This script is designed to be triggered externally or manually from the Event Listener. Please consider using Event Listener Test Event Payload if you need to trigger this script manually.');
return;
}
console.log(`Page updated event received for page with ID: ${event.page.id}`);
// Get details about the updated page
const page = await ConfluenceOnPremise.Content.getContent({
id: event.page.id.toString()
});
// Get details about the user who updated the page
const user = await ConfluenceOnPremise.User.getUser({
key: event.userKey
});
// Construct an HTML notification message using data about the updated page
const notificationMessage = `<p>Confluence Page <a href='${page._links?.base}${page._links?.webui}'>${page.title}</a> updated by <b>${user.displayName}</b> at ${new Date(event.timestamp)}</p>`;
// Get all page watchers
const watchers = await getWatchers(page);
console.log(`Watchers found: ${watchers.pageWatchers.length}`);
// Get all page watcher details
const watcherDetails = await getWatcherDetails(watchers.pageWatchers);
// Extract watcher emails and cast them to lower case
const watcherEmails = watcherDetails.map(wd => wd.email?.toLowerCase());
// Get details for authenticated user in Microsoft Teams
const sender = await Microsoft.Users.getMyUser();
// Get all users in your Microsoft Teams instance
const users = (await Microsoft.Users.getUsers()).value ?? [];
// Match Confluence users with their Microsoft Teams counterparts by comparing emails (excluding the authenticated user)
const matchingUsers = users.filter(user => watcherEmails.includes(user.mail?.toLocaleLowerCase()) && user.id !== sender.id);
console.log(`Matching users in Teams found: ${matchingUsers.length}`);
// Iterate over all the matching users
for (const receiver of matchingUsers) {
try {
// Send a message to each user
await sendOneToOneTeamMessage(sender.id ?? '', receiver.id ?? '', notificationMessage);
console.log(`Notification message sent to: ${receiver.displayName} (${receiver.id})`);
} catch (e) {
// If something goes wrong, log it out
console.error('Failed to send notification message in Teams', e, {
sender,
receiver
});
}
}
}
// Function to get user details for all watchers
async function getWatcherDetails(watchers: Watcher[]) {
const watcherDetails: UserDetailsResponse[] = [];
for (const watcher of watchers) {
try {
watcherDetails.push(await getUserDetails(watcher.name));
} catch (e) {
console.error('Failed to get detailed Confluence user information', e, {
watcher
});
}
}
return watcherDetails;
}
// Function to get all watchers of the page using low level Fetch API to query data from undocumented endpoint
async function getWatchers(page: GetContentResponseOK): Promise<WatchersResponse> {
const response = await ConfluenceOnPremise.fetch(`/json/listwatchers.action?pageId=${page.id}`);
if (!response.ok) {
throw Error(`Unexpected status code while getting watchers: ${response.status}`);
}
return await response.json();
}
// Function to get user details for a Confluence user using low level Fetch API to query data from undocumented endpoint
async function getUserDetails(name: string): Promise<UserDetailsResponse> {
const response = await ConfluenceOnPremise.fetch(`/rest/mobile/1.0/profile/${name}`);
if (!response.ok) {
throw Error(`Unexpected status code while getting user details: ${response.status}`);
}
return await response.json()
}
// Function to create one-to-one chat with a reciver user in Teams and then send a notification message into it
async function sendOneToOneTeamMessage(senderUserId: string, receiverUserId: string, notificationMessage: string) {
const chat = await Microsoft.Teams.Messaging.Chat.createChat({
body: {
chatType: 'oneOnOne',
members: [
{
id: senderUserId,
roles: ['owner']
},
{
id: receiverUserId,
roles: ['owner']
}
]
}
});
await Microsoft.Teams.Messaging.Chat.sendMessage({
chat_id: chat.id ?? '',
body: {
body: {
content: notificationMessage,
contentType: 'html'
},
importance: 'normal',
subject: 'Confluence page updated'
}
});
}
interface Watcher extends User {
name: string;
}
interface WatchersResponse {
pageWatchers: Watcher[];
spaceWatchers: Watcher[];
}
interface UserDetailsResponse extends User {
email?: string;
}