Platform
Docs
Solutions
ContactLog In

Start Routing Notifications Today!

Courier is a notification service that centralizes all of your templates and messaging channels in one place which increases visibility and reduces engineering time.

Sign-up

Twitch Notifications Part 3 Header
ENGINEERING

Twitch Notifications (Part Three): How to Create and Notify a List of Subscribers Using Courier

Aydrian Howard

February 04, 2021

In this series, I explain how to use Twitch EventSub and Courier to automatically send notifications to multiple destinations – Slack, Discord, and more – when your Twitch stream goes live.

In part one, we built a Node.js app using Express.js to accept events from Twitch EventSub. In part two, we listened for our event and triggered a notification using Courier. Now, in part three, we're going to use Courier’s List API to send multiple notifications when our event is triggered.

Follow along with the series:

Need help getting started with sending notifications about your Twitch stream? Join our community on Discord – we’re happy to chat!

How to create and notify a list of subscribers using Courier

In this tutorial, I'll show you how to extend the Node.js and Express app that we updated in part two to send notifications to more than one destination using Courier’s Lists API. We'll update the sendOnline function to use a List send. I'll also demo sending to a Discord channel.

Prerequisites

To complete this tutorial, you'll need a few things:

If you’re using the Node.js and Express.js app we created in part one, it should either be deployed somewhere publicly accessible that supports HTTPS and port 443, or be running locally using ngrok.

We'll need an existing Discord Bot that Courier can use to send your notifications. If you don't have one, check out our Discord Integration Guide to get started.

You'll also need your Courier Auth Token for the following steps. You can find your Courier Auth Token in Settings > API Keys in your Courier account. Use the Published Production Key.

Step one: Update your code to send to a list

To send to multiple recipients, we'll need to refactor the sendOnline function to use a list send instead of the regular send. We'll also need to create a list of recipients. To continue sending the SMS notification we created in part two, we'll create a stored profile for the recipient and subscribe them to our list.

Create a List in Courier

To create our list, we'll use the Courier Lists API. Our list will need a list id and a name. For this tutorial, we'll create a list with an id of “twitch.stream.online“ and a name of “Twitch Stream Online.“ You can learn more about using list id patterns in our Help Center.

Let's create our list by executing the following cURL command in your terminal, replacing COURIER_AUTH_TOKEN with your auth token:

1
curl --request PUT \
2
--url https://api.courier.com/lists/twitch.stream.online \
3
--header 'Accept: application/json' \
4
--header 'Authorization: Bearer COURIER_AUTH_TOKEN' \
5
--header 'Content-Type: application/json' \
6
--data '{"name":"Twitch Stream Online"}'

Your new list should now be visible in the data tab in your Courier Account.

Add a new subscriber to the List

Now that we have a list, let's subscribe the recipient we used in part two to it. To do this, we'll first need to use the Profiles API to store the recipient's profile information in Courier. Then, we'll make a call to the List API to subscribe them to the list.

We'll use the recipient id and profile information from the existing send command. Execute the following cURL command in your terminal using your values:

1
curl --request POST \
2
--url https://api.courier.com/profiles/AYDRIAN10036 \
3
--header 'Accept: application/json' \
4
--header 'Authorization: Bearer COURIER_AUTH_TOKEN' \
5
--header 'Content-Type: application/json' \
6
--data '{"profile":{"phone_number":"+12025550140"}}'

Now that we have the profile stored, we can use the recipient id and subscribe it to our list. Execute the following cURl command in your terminal replacing AYDRIAN10036 with your recipient id:

1
curl --request PUT \
2
--url https://api.courier.com/lists/twitch.stream.online/subscriptions/AYDRIAN10036 \
3
--header 'Authorization: Bearer COURIER_AUTH_TOKEN'

Repeat this process to add more subscribers to the list. When you’re ready, let's update the code to send to our new list.

Swap out the Courier Send

Previously, we told Courier to send to a single recipient. In order to send to the list we just created, we’ll need to use a List send instead.

In your index.js file, replace the following in the sendOnline function:

1
const { messageId } = await courier.send({
2
eventId: "TWITCH_ONLINE",
3
recipient: "AYDRIAN10036",
4
profile: {
5
phone_number: "+12025550140"
6
},
7
data: { stream, game }
8
});

With the following:

1
const { messageId } = await courier.send({
2
event: "TWITCH_ONLINE",
3
list: "twitch.stream.online",
4
data: { stream, game }
5
});

Now if you were to run this code, it would still deliver the notification via SMS.

Step two: Add Discord to your notification in Courier

Now that we can send notifications to multiple recipients with Lists, let's expand the available destinations. Recently, Discord committed to fully supporting online communities, making it a top choice for notifying people about our Twitch stream. Let's add the ability to have Courier post to a channel using a Discord Bot.

Configure the Discord integration in Courier

Let's start by configuring the Discord integration. This will require you to enter the bot token for the bot that Courier will send as.

Courier Discord Integration

Design the Discord notification

Now we can update our existing Twitch Online Alert notification. We'll add Discord by clicking “Add Channel” and selecting Discord from the list of configured integrations.

Add Discord notification channel

We can now select Discord under Channels to the left and start designing our notification. Because we have already created our SMS notification, we can reuse those content blocks for Discord. Simply drag the blocks in the Library section to our Discord notification.

Discord notification

We now have a message that matches our SMS. Feel free to add more content blocks to your  Discord notifications. When you’re finished, click “Publish Changes” in the upper righthand corner.

If you'd like, you can preview the generated Discord markdown using the Preview tab. You can use the test event we created in part two.

Discord notification preview

Step three: Subscribe a Discord channel to the List

Your notification is now ready to start sending to Discord. The last step is to identify the Discord channel that you want to post your notification in and add it as a recipient to our list. Similar to how we added a recipient for our SMS notification, we'll first create a profile in Courier and then subscribe it to the list.

We'll need the channel id of the channel we want to send to. An easy way to retrieve that is to turn on Developer Mode in Discord. You can go to User Settings > Appearance and scroll to Advanced at the bottom and toggle Developer Mode to on. This will allow you to right click on a channel and copy the id.

Discord User Settings

I'm going to use the #show-and-tell channel in  Courier’s Discord server, which you’re welcome to join. For the recipient id, I'm going to use DISCORD_COURIER_SHOW_AND_TELL. It's a little long but descriptive.

Execute the following cURL command to create a profile for the channel in Courier:

1
curl --request POST \
2
--url https://api.courier.com/profiles/DISCORD_COURIER_SHOW_AND_TELL \
3
--header 'Accept: application/json' \
4
--header 'Authorization: Bearer COURIER_AUTH_TOKEN' \
5
--header 'Content-Type: application/json' \
6
--data '{"profile":{"discord":{"channel_id":"801886566419136592"}}}'

Now we can execute the following cURL command to subscribe it to our list:

1
curl --request PUT \
2
--url https://api.courier.com/lists/twitch.stream.online/subscriptions/DISCORD_COURIER_SHOW_AND_TELL \
3
--header 'Authorization: Bearer COURIER_AUTH_TOKEN'

We can test our application using the Twitch CLI. Run the following command with the needed substitutions:

1
twitch event trigger streamup --to-user YOUR_BROADCASTER_ID -F https://EXTERNAL_URL/webhook/callback -s YOUR_SECRET

This command will trigger an example stream.online event using your broadcaster id. You should see the event in the Courier Logs. You should receive an SMS message and that your Discord Bot has posted the following:

Discord example notification

Putting it all together: Full application code

With the update to the sendOnline function, your finished application should look like the following.

1
require("dotenv").config();
2
const express = require("express");
3
const crypto = require("crypto");
4
const { CourierClient } = require("@trycourier/courier");
5
const app = express();
6
const port = process.env.PORT || 3000;
7
const twitchSigningSecret = process.env.TWITCH_SIGNING_SECRET;
8
const courier = CourierClient();
9
const { ApiClient } = require("twitch");
10
const { ClientCredentialsAuthProvider } = require("twitch-auth");
11
const authProvider = new ClientCredentialsAuthProvider(
12
process.env.TWITCH_CLIENT_ID,
13
process.env.TWITCH_CLIENT_SECRET
14
);
15
const twitch = new ApiClient({ authProvider });
16
17
app.get("/", (req, res) => {
18
res.send("Hello World!");
19
});
20
21
const verifyTwitchSignature = (req, res, buf, encoding) => {
22
const messageId = req.header("Twitch-Eventsub-Message-Id");
23
const timestamp = req.header("Twitch-Eventsub-Message-Timestamp");
24
const messageSignature = req.header("Twitch-Eventsub-Message-Signature");
25
const time = Math.floor(new Date().getTime() / 1000);
26
console.log(`Message ${messageId} Signature: `, messageSignature);
27
28
if (Math.abs(time - timestamp) > 600) {
29
// needs to be < 10 minutes
30
console.log(
31
`Verification Failed: timestamp > 10 minutes. Message Id: ${messageId}.`
32
);
33
throw new Error("Ignore this request.");
34
}
35
36
if (!twitchSigningSecret) {
37
console.log(`Twitch signing secret is empty.`);
38
throw new Error("Twitch signing secret is empty.");
39
}
40
41
const computedSignature =
42
"sha256=" +
43
crypto
44
.createHmac("sha256", twitchSigningSecret)
45
.update(messageId + timestamp + buf)
46
.digest("hex");
47
console.log(`Message ${messageId} Computed Signature: `, computedSignature);
48
49
if (messageSignature !== computedSignature) {
50
throw new Error("Invalid signature.");
51
} else {
52
console.log("Verification successful");
53
}
54
};
55
56
const sendOnline = async (event) => {
57
const stream = await twitch.helix.streams.getStreamByUserId(
58
event.broadcaster_user_id
59
);
60
const game = await stream.getGame();
61
62
const { messageId } = await courier.send({
63
event: "TWITCH_ONLINE",
64
list: "twitch.stream.online",
65
data: { stream, game }
66
});
67
console.log(
68
`Online notification for ${event.broadcaster_user_name} sent. Message ID: ${messageId}.`
69
);
70
};
71
72
app.use(express.json({ verify: verifyTwitchSignature }));
73
74
app.post("/webhooks/callback", async (req, res) => {
75
const messageType = req.header("Twitch-Eventsub-Message-Type");
76
if (messageType === "webhook_callback_verification") {
77
console.log("Verifying Webhook");
78
return res.status(200).send(req.body.challenge);
79
}
80
81
const { type } = req.body.subscription;
82
const { event } = req.body;
83
84
console.log(
85
`Receiving ${type} request for ${event.broadcaster_user_name}: `,
86
event
87
);
88
89
if (type === "stream.online") {
90
try {
91
sendOnline(event);
92
} catch (ex) {
93
console.log(
94
`An error occurred sending the Online notification for ${event.broadcaster_user_name}: `,
95
ex
96
);
97
}
98
}
99
100
res.status(200).end();
101
});
102
103
const listener = app.listen(port, () => {
104
console.log("Your app is listening on port " + listener.address().port);
105
});

Our application will process stream.online events and pass them to Courier along with additional stream data. Courier will then create SMS or Discord notifications based on the profiles in your list of subscribers.

So, what's next?

You now have an application that will send notifications to a list of subscribers, via SMS and Discord, when you start your Twitch stream. I encourage you to explore adding more subscribers to your list and adding even more destinations like Slack and Facebook Messenger. Join our Discord community and let me know where you go from here!

-Aydrian

Start Routing Notifications Today!

Courier is a notification service that centralizes all of your templates and messaging channels in one place which increases visibility and reduces engineering time.

Sign-up

More from Engineering

courier-ios-thumbnail
PRODUCT NEWSENGINEERING

Simplifying notifications with the Courier iOS SDK

Push notifications are a valuable tool for keeping users informed and increasing their engagement with your app. You can use push notifications to alert users about promotions, new content, or any other important updates. While push notifications are a powerful tool, setting up push notifications in iOS can be a daunting task that requires a significant amount of effort and time. Fortunately, the Courier iOS Mobile Notifications Software Development Kit (SDK) simplifies this process.

Mike Miller

Mike Miller

March 23, 2023

Courier Android SDK thumbnail
PRODUCT NEWSENGINEERING

Building Android push notifications with Firebase and Courier’s SDK

Push notifications have become an essential part of modern mobile apps, allowing you to keep your users engaged and informed. However, implementing push for different platforms can be a complex and time-consuming task, requiring developers to set up and handle token management, testing, and other logistical details.

Mike Miller

Mike Miller

March 21, 2023

Build your first notification in minutes

Send up to 10,000 notifications every month, for free.

Get started for free

Email & push notification

Build your first notification in minutes

Send up to 10,000 notifications every month, for free.

Get started for free

Email & push notification

Platform

Users

Content

Channels

Sending

Workflows

Preferences

Inbox

Workspaces

Observability

API Status

Changelog

© 2024 Courier. All rights reserved.