DEV Community

Cover image for Automate Slack and Microsoft Teams Notifications using Python
Shreya for Courier

Posted on • Originally published at courier.com

Automate Slack and Microsoft Teams Notifications using Python

Messaging apps are essential for internal collaboration and critical notifications such as reminders, alerts, and other time-sensitive updates. While integrating with the Slack and Microsoft APIs is fairly straightforward, implementing these tools as a part of a full-featured notification system that embeds with your app experience can be far more daunting.

In this article, we'll show you how to send notifications via Slack and Microsoft Teams, using Courier to make these tools a seamless part of how your app communicates with users.

Prerequisites

Create a Notification Template for Slack and Teams

Head over to the Notification Designer and create a new notification. Once you have created the notification, you will be able to select your channels. Here you can add Slack, Teams, and/or any other channels you would like to send with.

Click on any of the channels to customize your message. Once you have created your message, you can use the drag-and-drop "Library" on the left side to recreate the message for the remaining channels.

library

Click on the settings (gear) icon next to the template name (top right) to access the Notification ID, which you will need later to send this message.

Send with Slack

Step 1: Add the Slack integration to Courier

First, head to the Slack channel in Courier https://app.courier.com/channels/slack and click "Install Provider". If you only want to send with Teams, you can skip to the “Send with Microsoft Teams” section.

channel slacks

Step 2: Create a Slack App

Navigate to the Slack Apps page and log into Slack. Click the Create an App button and provide your App Name as depicted below.

slack-app

Step 3: Add OAuth Permission and Scopes

Define the permissions that your Slack App is authorized to do.

To do so, navigate to the OAuth & Permissions page in the sidebar menu and select the following options from the Scopes section:

  • chat:write
  • im:write
  • users:read
  • users:read.email

slack-app-scopes

Afterward, click the Install App to Workspace or Reinstall App button at the top of the page. This will generate an output -"Bot User OAuth Token" as depicted below, which will be needed later.

slack-app-oath-token

Step 4: Send a Slack DM with Python

Add the code snippet below to your codebase (e.g. index.py ) and update the following properties:

  • replace with your Courier API key
  • access_code: replace xoxb-abcd with the Bot User OAuth Token
  • replace example@gmail.com with your user's email address (this is the email associated with the recipient's Slack Account)
  • Recommended: use your own email for testing
  • replace 85S5NWXJVQ4GN8J21JSKV3JVCSV2 with your Notification ID from the first part of this tutorial
from trycourier import Courier
client = Courier(auth_token="<auth-token>")

resp = client.send_message(
  message={
    "to": {
      "slack": {
        "access_token": "xoxb-abcd",
        "email": "example@gmail.com",
      },
    },
    "template": "85S5NWXJVQ4GN8J21JSKV3JVCSV2",
    "data": {
    },
  }
)
print(resp['requestId'])

Enter fullscreen mode Exit fullscreen mode

Execute the Python script to see your notification popup in the user's Slack direct message!

Slack message

Check your Courier logs for errors if your user did not receive the message.

Slack Resources

Send with Microsoft Teams

We can now try sending the same message via Teams. If you only want to send with Slack, you can skip to the “Routing to multiple channels” section.

Step 1: Sign up for a Microsoft 365 Developer Account

If you do not have a Microsoft 365 developer account, follow the instructions from this guideline to create an account. If you already have an account, you can skip this step.

Step 2: Create a Teams App

Create a new App in Teams. You will need to install the Developer Portal from the Team Apps.

After installing the Developer Portal, navigate to the Apps tab and click the New App button. Then, you will get prompted to enter the application name.

ms teams add app

After clicking the Add button, you will be redirected to a new window where you can see the App ID. Make sure to copy the App ID for later use.

MS Teams Bot Basic Info

Then, click App features from the left menu and click on the tile named Bot. It will open a new window for selecting a bot and bot scopes.

Identify Bot

If you do not have a bot created already, follow these steps to create a new one. Also, make sure to save the password generated during the process. Keep the Messaging endpoint blank for the moment.

MS Teams App Configuration

Step 3: Deploy the bot

Now you need to deploy the App to create the messaging endpoint. For that, open the Microsoft Teams Bot Starter Repo and click the Deploy to Netlify button. There, you will have to connect to your GitHub account and enter your App ID (Bot ID), App Password, Courier Auth Token, and a name for the repo.

Deploy app on netlify

Once the site is deployed, copy your site URL since you need it to finish installing the bot.

Step 4: Install the bot

Now, go back to the Tools > Bot Management tab in Developer Portal and select the created bot to finalize the installation process. There, select the Configure option and copy the site URL to the Bot endpoint address field.

Bot Endpoint Developer Portal

Then, select the Channels option from the left menu and tick the Microsoft Teams option.

Channels Developer Portal

Step 5: Add the Teams integration to Courier

Now, you need to create a Teams integration in Courier. For that, navigate to the Channels tab and select Microsoft Teams from the options. Then, it will show a window like the one below. Enter the App ID, App Password and click the Install Provider button.

Channel TeamsGet link to team

Step 6: Sending a Simple Teams Notification with Python

Add the code snippet below to your codebase (e.g. index.py ) and update the following properties:

  • replace <auth-token> with your Courier API key
  • conversation_id: get the conversation id from threadId query parameter from the URL after opening Microsoft Teams in the browser
  • service_url: the service URL associated with that Microsoft Teams tenant (if you are located in the Americas Region, the service url is https://smba.trafficmanager.net/amer)
  • tenant_id: go to https://teams.microsoft.com/?tenantId and copying the value from the redirected URL tenantId query parameter, or click the three dots next to your Team and click Get link to team to find a link with the tenantId parameter
from trycourier import Courier
client = Courier(auth_token="<auth-token>"

resp = client.send_message(
  message={
      "to": {
      "ms_teams": {
          "conversation_id": "Yl2wJmlmFQkc65UAg0I2kJyCnPJlXvIM4Q3XSrDBZnQ1",
          "tenant_id": "aac0c564-6c5e-4b05-8dc3-408087f77f76",
          "service_url": "https://smba.trafficmanager.net/amer",
      },
      },
      "template": "M79W7S9TRYM04CM634A805T8SYKM",
      "data": {
      },
  } 
)
print(resp['requestId'])
Enter fullscreen mode Exit fullscreen mode

Finally, you can run the python script, and you will see a notification in your Team channel.

Microsoft Teams Resources

Routing to multiple channels

Courier's multi-channel functionality allows you to send notifications across multiple channels, including email, SMS, push notifications, voice, chatbots, and social media platforms, using a single API.

For example, if you want to send an urgent alert to your team, you would use Courier to send this alert as an email, as well as a Slack or Teams notification. As you can see below, Courier supports a large selection of Email, SMS, chat, and push notification providers.

Channels

Let’s update the notification template to send across four channels: email, SMS, Slack, and Teams. First, add email and SMS channels to the template and make sure they both also have the same content as the previous two (remember, you can use the Library to drop in pre-built content blocks).

Next, update the Settings of each channel so that “Always send to” is toggled on (away from “Best Of”) for each of the four channels listed.

Always send to Slack

from trycourier import Courier
client = Courier(auth_token="<auth-token>")

resp = client.send_message(
  message={
    "to": {
      "slack": {
        "access_token": "xoxb-abcd",
        "email": "example@gmail.com",
      },
      "ms_teams": {
          "conversation_id": "85S5NWXJVQ4GN8J21JSKV3JVCSV2",
          "tenant_id": "aac0c564-6c5e-4b05-8dc3-408087f77f76",
          "service_url": "https://smba.trafficmanager.net/amer",
      },
    },
    "template": "Z5N9D2J8DSMBKEHWF27AEEF6J822"
  }
)
print(resp['requestId'])
Enter fullscreen mode Exit fullscreen mode

Four channels

You can also decide whether you actually want to send to all four channels or only specific ones. “Best of” means that Courier will send to one channel out of all that are listed. E.g. if you list Slack as “Always send to”, but have email and SMS as “Best of”, Courier will send a Slack message and attempt to send an email. If the email fails to deliver for any reason, Courier will then reroute to SMS. This means it will only send an SMS if and when email fails.

Automating Slack and Teams Notifications## Automating Slack notifications

If you prefer a visual workflow, you can create an automation template within Courier.

Create a new Automation, select a schedule Trigger, and add a Send step for your notification. We will update the Type to "Date" and Date to the specific date/time this message should be sent.

In the Send step, select JSON and use the Editor to add the recipient information. In the editor, click "+ Add field" and add slack as an Object. Then click "+Add nested field" and add access_token and email with the appropriate values from the code above.

Update automation JSON

Automating Teams notifications

The notification template will automatically send to all selected channels.

Head over to the Automation and, in the JSON editor of the Send step, click "+ Add field" and add ms_teams as an Object. Then click "+Add nested field" and add conversation_id, tenant_id, and service_id, with the appropriate values from the code above.

This automation will now have the required user profile data to send to both Slack and MS Teams. If you also want to send to an email or SMS, edit the JSON object to add field for "email" and "phone_number" with the appropriate values.

Conclusion

Automating notifications in team communication platforms such as Slack and Teams can significantly improve team productivity and communication. However, building automated notifications from scratch can be complex and time-consuming. That's where Courier comes in with its easy-to-use Python SDK that allows developers to send notifications to multiple channels with just a few lines of code.

By following the steps outlined in this article, you can set up notification automation with Courier and Python for both Slack and Teams. Additionally, you can leverage Courier's multi-channel functionality to integrate other applications and channels into your notification system.

FAQs

1. What is Courier?

Courier connects communication APIs, data, and development tools that your team already uses to deliver a best-in-class notification system that will trigger messages from your app at just the right time, using just the right channel. It provides powerful API primitives and reusable UI components for building, plus no-code tools for designing templates and communication sequences.

2. What is Slack?

Slack is a cloud-based messaging platform that enables teams to communicate and collaborate in real-time. It is known for its user-friendly interface and extensive third-party integrations, making it a highly customizable platform for teams of all sizes. Slack allows users to easily organize their conversations into channels, share files, and collaborate with other team members. It also offers multiple app integrations, including project management and automation tools.

3. What is Microsoft Teams?

Microsoft Teams is another popular communication and collaboration platform that is part of the Microsoft Office 365 suite. It enables teams to chat, share files, and collaborate in real time, both synchronously and asynchronously. With features such as video conferencing, screen sharing, and group chats, Microsoft Teams is ideal for businesses and organizations that require a comprehensive and centralized collaboration platform.

4. Missing Provider Support error message

If your message did not go through, check your Courier logs. For a "MISSING_PROVIDER_SUPPORT" error message, you will need to double-check if the Slack and/or Teams channels were installed properly in Courier. Try removing the channel(s) (go to the channel and click "Remove Channel" at the bottom of the page) that is causing the error and then adding it again.

Top comments (0)