Receive notification in MS Teams about Confluence DC pages you are watching


Get Started

Not the template you're looking for? Browse more.

About the template


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. Get started to learn more.

About ScriptRunner Connect


What is ScriptRunner Connect?

ScriptRunner Connect is an AI assisted code-first (JavaScript/TypeScript) integration platform (iPaaS) for building complex integrations and automations.

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


README

Scripts

TypeScriptOnConfluenceOnPremisePageUpdated
Page Updated

README


๐Ÿ“‹ Overview

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.

๐Ÿ–Š๏ธ Setup

  • Configure the API Connection and Event Listener by creating connectors for Confluence On-Premise and MS Graph, or use existing ones.
  • Note that for if you are using a self-managed Connector for MS Graph, you might need to add certain API permissions to your app and get them approved by an administrator. As a minimum, make sure you have the privileges set by the User.ReadBasic.All and Chat.ReadWrite permissions. After changing permissions you will have to reauthorize your MS Graph Connector.

๐Ÿš€ Usage

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.

API Connections


TypeScriptOnConfluenceOnPremisePageUpdated

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;
}
Documentation ยท Support ยท Suggestions & feature requests