Automate Slack and Microsoft Teams Notifications using Python
Published: 2023-03-16 16:28:47

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

*   [Get access to your Courier API Key](https://app.courier.com/settings/api-keys)
*   Install [Python 3.x](https://www.python.org/downloads/) on your computer
*   Install [trycourier](https://github.com/trycourier/courier-python) by running the `pip install trycourier` command

# Create a Notification Template for Slack and Teams

Head over to the [Notification Designer](https://app.courier.com/designer/notifications) 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](//images.ctfassets.net/z7iqk1q8njt4/4t6oJw1bAPc9e52j60bSqV/25db3c6da9ca8b2374ce013186d512d0/library.png)

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](//images.ctfassets.net/z7iqk1q8njt4/SWRZHOpuy16BSC7U6bKZC/7012a8b640279a373385030f5915e783/channel_slack.png)

**Step 2: Create a Slack App**

Navigate to the [Slack Apps](https://api.slack.com/apps) page and log into Slack. Click the **Create an App** button and provide your **App Name** as depicted below.

![slack-app](//images.ctfassets.net/z7iqk1q8njt4/miwFyPxaShQwSo2TOsfAw/9a528f8789cc9e4b2254f6596026167f/image-3.png)

**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](//images.ctfassets.net/z7iqk1q8njt4/198iG9vhkW4tlkJyeBrpNn/cbf936323438e33685359b7ebc6b4a8b/image-4.png)

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](//images.ctfassets.net/z7iqk1q8njt4/2EqXlD3eNxgMPsC7HaRbVs/0f34a765a9db3d7c623d59e338a3ad2d/slack-app-oath-token.png)

**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 <auth-token> 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

```mikrotik
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'])

```

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

![Slack message](//images.ctfassets.net/z7iqk1q8njt4/7oK2GoJdrfngJoXuqd8DDo/6bb2407eafaf8b4a1ff1cbf978c9ab61/Slack_message.png)

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

## Slack Resources

*   [Slack Integration documentation](https://www.courier.com/docs/guides/providers/direct-message/slack/)
*   [Python quick start guide](https://www.courier.com/docs/guides/getting-started/python/)
*   [Video walkthrough: Automating Slack Messages with Courier API](https://youtu.be/sZpxo9kOa78)

# 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](https://developer.microsoft.com/en-us/microsoft-365/dev-program/) 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](https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/build-and-test/teams-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](//images.ctfassets.net/z7iqk1q8njt4/4aAPZzFGQGiXPs2wvYpv1u/508cbfafe3f3df87b0efed75eb02117a/ms_teams_add_app.png)

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](//images.ctfassets.net/z7iqk1q8njt4/5GqgOocVChW7ODrHXOYiSR/ae5c800f466fa408be455448e0828d24/MS_Teams_Basic_Info.png)

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](//images.ctfassets.net/z7iqk1q8njt4/4un7lX2rG9oos1pcte7mXf/c0d66c40799682ffa3e8847ed9d0b265/Identify_Bot.png)

If you do not have a bot created already, follow [these steps](https://learn.microsoft.com/en-us/microsoftteams/platform/resources/bot-v3/bots-create) 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](//images.ctfassets.net/z7iqk1q8njt4/2QJEtyIRyEW1IoOjVWc5jT/254f097453ffbda26b71a44b518925a2/MS_Teams_App_Configuration.png)

**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](https://github.com/trycourier/courier-netlify-msteams) 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](https://app.courier.com/settings/api-keys), and a name for the repo.

![Deploy app on netlify](//images.ctfassets.net/z7iqk1q8njt4/1l8TdpjQHBxZyII6wTz1T8/7d595d569310633ec8f8f188b4f08857/image-11.png)

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](//images.ctfassets.net/z7iqk1q8njt4/3MSoYstFOcCu92kmVmwTWd/7f4b8dd17db4999c6d0873112a8aca27/Bot_Endpoint_Developer_Portal.png)

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

![Channels Developer Portal](//images.ctfassets.net/z7iqk1q8njt4/5t8S8x0RqXXaLE6SGIrb31/6174c8f87136d972c2f9e87cba194cd8/Channels_Developer_Portal.png)

**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 Teams](//images.ctfassets.net/z7iqk1q8njt4/60s7rXRUyYBWby7VaCv4oZ/dd3a0a79a075c791fe3968d5c8a81d92/Channel_Teams.png)![Get link to team](//images.ctfassets.net/z7iqk1q8njt4/5QmeLiEkDVGii3zjF2v7Yr/34011d75428a42c2c3175c6a89337608/image-15.png)

**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

```mikrotik
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'])
```

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

Microsoft Teams Resources

*   [Teams Integration documentation](https://www.courier.com/docs/guides/providers/direct-message/microsoft-teams/)
*   [Python quick start guide](https://www.courier.com/docs/guides/getting-started/python/)

# 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](//images.ctfassets.net/z7iqk1q8njt4/79z4TRaE3a2PunYENuHsUZ/da046abe8e232c15a78af03ee27c5435/channels.png)

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](//images.ctfassets.net/z7iqk1q8njt4/4FHXzgaBVw4lgmvaSjJCyo/ee47ec3c01f60b41b6620d30b44b2b7f/Always_send_to.png)

```python
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'])
```

![Four channels](//images.ctfassets.net/z7iqk1q8njt4/4BUpIEvF4twcNx4POd0sO0/58b2c3859e8fb57a0b270d1bdcc238df/Four_channels.png)

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](https://app.courier.com/automations), 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](//images.ctfassets.net/z7iqk1q8njt4/5mGTvwwLzJJkdFJC9s0a2K/d4d299365be7cf11823824f5866ff6b6/automation_2.png)

## 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](https://www.courier.com/) 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.