DEV Community

Cover image for Twitch notifications (part one): How to handle real-time events from Twitch
Aydrian for Courier

Posted on • Updated on • Originally published at courier.com

Twitch notifications (part one): How to handle real-time events from Twitch

Over the last few years, Twitch has become the streaming platform for gaming, esports, live coding, DJ-ing, and more. If you’re a streamer, whether for work or for fun, you know that one of the biggest challenges is building your audience and attracting viewers to your Twitch channel when you go live.

Unfortunately, the options for sending notifications in Twitch are pretty limited. When you go live, Twitch will automatically send your followers an email, push, or in-app notification. But this isn’t very helpful for acquiring new viewers or engaging your community outside of Twitch.

In this series, I'll show you how to use Twitch EventSub and Courier to automatically send notifications to many destinations – Discord, Slack, Facebook Messenger, and more – when your stream begins.

  • Part one (this post): We’ll create a small Node.js and Express app to accept webhooks from Twitch EventSub.

  • Part two (coming soon): We’ll subscribe to the stream.online event and process the request using Courier. Then, we’ll use Courier to create and design our notifications.

  • Part three (coming soon): Finally, we'll create a list of subscribers and use Courier to notify the entire list across multiple destinations with one API call.

Have questions about sending notifications using Twitch EventSub and Courier? Join our new community on Discord – we're happy to help!

How to handle real-time events from Twitch

During last year's Twitch Developer Day, Twitch introduced EventSub as a single product to handle real-time events. EventSub is a transport-neutral solution that will eventually replace their existing PubSub and Webhook APIs. Today, EventSub only supports webhooks.

Let's start by creating a Node.js application and use Express to expose a POST route that Twitch EventSub can communicate with.

Prerequisites

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

  1. A Node.js v14.x dev environment
  2. The Twitch CLI (for testing)

We'll be creating a Node.js application that needs to be accessible externally. If you are working locally, you can use ngrok to expose your local endpoint. Alternatively, you can use a tool like Glitch to build and host your application.

Creating a basic Express Application

We'll start by creating an Express application with minimal features. First, create a new folder and initialize it with a package.json file.

mkdir eventsub-handler && eventsub-handler
npm init --yes
Enter fullscreen mode Exit fullscreen mode

Now we are able to install the Express package.

npm install express
Enter fullscreen mode Exit fullscreen mode

Let's use express to create a simple HTTP server. Create an index.js file and add the following:

const express = require("express");
const app = express();
const port = process.env.PORT || 3000;

app.get("/", (req, res) => {
  res.send("Hello World!");
});

const listener = app.listen(port, () => {
  console.log("Your app is listening on port " + listener.address().port);
});
Enter fullscreen mode Exit fullscreen mode

Let's run our application by executing node index.js in the terminal. If you open http://localhost:3000 in your browser, you should see "Hello World!"

Congrats! You now have a working (albeit minimal) Express server. Next, we'll add the ability to receive a POST request from Twitch.

Handling the Twitch POST request

In order to accept real-time events from Twitch, we'll need to create a callback URL. We can do this by creating a new POST route. In the index.js file above where the listener is created, add the following lines of code:

app.use(express.json());

app.post("/webhooks/callback", async (req, res) => {
  const { type } = req.body.subscription;
  const { event } = req.body;

  console.log(
    `Receiving ${type} request for ${event.broadcaster_user_name}: `,
    event
  );

  res.status(200).end();
});
Enter fullscreen mode Exit fullscreen mode

First, we are telling our Express application to use the express.json() middleware to parse any incoming JSON payloads. Then, we added a callback route that will log the request and return a 200 status. Twitch expects this 2XX response to confirm you've received the request. If it doesn't receive a response in a couple seconds, it will retry the request.

Let's test this route using the Twitch CLI. Restart your application and use the following command to trigger a test subscribe event.

twitch event trigger subscribe -F http://localhost:3000/webhooks/callback
Enter fullscreen mode Exit fullscreen mode

In the terminal running your application, you should see the event JSON for a channel.subscribe event. Next, we'll want to handle callback verification.

Handling callback verification

When you subscribe to an event, EventSub will send an initial request to the callback URL you specified. It expects a challenge response to verify you own the callback URL. We can handle this by checking the value of the Twitch-Eventsub-Message-Type header and respond with the challenge value provided in the request payload.

Update the callback code to the following:

app.post("/webhooks/callback", async (req, res) => {
  const messageType = req.header("Twitch-Eventsub-Message-Type");
  if (messageType === "webhook_callback_verification") {
    console.log("Verifying Webhook");
    return res.status(200).send(req.body.challenge);
  }

  const { type } = req.body.subscription;
  const { event } = req.body;

  console.log(
    `Receiving ${type} request for ${event.broadcaster_user_name}: `,
    event
  );

  res.status(200).end();
});
Enter fullscreen mode Exit fullscreen mode

Let's test this using the Twitch CLI. Restart your application and run the following CLI command:

twitch event verify-subscription subscribe -F http://localhost:3000/webhooks/callback
Enter fullscreen mode Exit fullscreen mode

This command will send a fake "subscription" EventSub subscription and validate if the endpoint responded with a valid status code and response.

Verifying the request

When accepting webhooks, it's good practice to verify that it came from the expected sender. We can do this by using the signature provided in the Twitch-Eventsub-Message-Signature header. We can create our own signature using the message ID, timestamp, and secret provided when subscribing to the event and compare it to the signature provided.

Let's update our use of the express.json() middleware to include a verify function. Add the following lines to the top of your index.js file:

const crypto = require("crypto");
const twitchSigningSecret = process.env.TWITCH_SIGNING_SECRET;
Enter fullscreen mode Exit fullscreen mode

And replace the app.use(express.json()); line with the following lines of code:

const verifyTwitchSignature = (req, res, buf, encoding) => {
  const messageId = req.header("Twitch-Eventsub-Message-Id");
  const timestamp = req.header("Twitch-Eventsub-Message-Timestamp");
  const messageSignature = req.header("Twitch-Eventsub-Message-Signature");
  const time = Math.floor(new Date().getTime() / 1000);
  console.log(`Message ${messageId} Signature: `, messageSignature);

  if (Math.abs(time - timestamp) > 600) {
    // needs to be < 10 minutes
    console.log(`Verification Failed: timestamp > 10 minutes. Message Id: ${messageId}.`);
    throw new Error("Ignore this request.");
  }

  if (!twitchSigningSecret) {
    console.log(`Twitch signing secret is empty.`);
    throw new Error("Twitch signing secret is empty.");
  }

  const computedSignature =
    "sha256=" +
    crypto
      .createHmac("sha256", twitchSigningSecret)
      .update(messageId + timestamp + buf)
      .digest("hex");
  console.log(`Message ${messageId} Computed Signature: `, computedSignature);

  if (messageSignature !== computedSignature) {
    throw new Error("Invalid signature.");
  } else {
    console.log("Verification successful");
  }
};

app.use(express.json({ verify: verifyTwitchSignature }));
Enter fullscreen mode Exit fullscreen mode

We just added a function to handle verifying the signature using the information from the request headers and used the crypto library to generate our own signature to which to compare it. This process used the signing secret that I'm storing in an environment variable because, well, your signing secret should stay secret.

Let's test that the signature validation is working using the Twitch CLI. You'll want to restart your app with the following command that includes the environment variable.

TWITCH_SIGNING_SECRET=purplemonkeydishwasher node index.js
Enter fullscreen mode Exit fullscreen mode

Then in another terminal, run the following CLI command:

twitch event trigger subscribe -F http://localhost:3000/webhooks/callback -s purplemonkeydishwasher
Enter fullscreen mode Exit fullscreen mode

You should now see the provided and computed signatures and that verification was successful.

Putting it all together: Full application code

Your finished application code should look like the following.

const express = require("express");
const crypto = require("crypto");
const app = express();
const port = process.env.PORT || 3000;
const twitchSigningSecret = process.env.TWITCH_SIGNING_SECRET;

app.get("/", (req, res) => {
  res.send("Hello World!");
});

const verifyTwitchSignature = (req, res, buf, encoding) => {
  const messageId = req.header("Twitch-Eventsub-Message-Id");
  const timestamp = req.header("Twitch-Eventsub-Message-Timestamp");
  const messageSignature = req.header("Twitch-Eventsub-Message-Signature");
  const time = Math.floor(new Date().getTime() / 1000);
  console.log(`Message ${messageId} Signature: `, messageSignature);

  if (Math.abs(time - timestamp) > 600) {
    // needs to be < 10 minutes
    console.log(
      `Verification Failed: timestamp > 10 minutes. Message Id: ${messageId}.`
    );
    throw new Error("Ignore this request.");
  }

  if (!twitchSigningSecret) {
    console.log(`Twitch signing secret is empty.`);
    throw new Error("Twitch signing secret is empty.");
  }

  const computedSignature =
    "sha256=" +
    crypto
      .createHmac("sha256", twitchSigningSecret)
      .update(messageId + timestamp + buf)
      .digest("hex");
  console.log(`Message ${messageId} Computed Signature: `, computedSignature);

  if (messageSignature !== computedSignature) {
    throw new Error("Invalid signature.");
  } else {
    console.log("Verification successful");
  }
};

app.use(express.json({ verify: verifyTwitchSignature }));

app.post("/webhooks/callback", async (req, res) => {
  const messageType = req.header("Twitch-Eventsub-Message-Type");
  if (messageType === "webhook_callback_verification") {
    console.log("Verifying Webhook");
    return res.status(200).send(req.body.challenge);
  }

  const { type } = req.body.subscription;
  const { event } = req.body;

  console.log(
    `Receiving ${type} request for ${event.broadcaster_user_name}: `,
    event
  );

  res.status(200).end();
});

const listener = app.listen(port, () => {
  console.log("Your app is listening on port " + listener.address().port);
});
Enter fullscreen mode Exit fullscreen mode

We now have a Node.js and Express application that can receive real-time events from Twitch using EventSub. We've tested it locally using the Twitch CLI but, remember, before you can start using it with Twitch, you'll need to make sure the route uses HTTPS and port 443 and is publicly available. If you want to continue running it locally, look into using ngrok.

So, what’s next?

In the next post, we'll walk through creating a subscription for the stream.online event and use Courier to design and send our notifications. In the meantime, feel free to create subscriptions to any of the many supported events and try out your application.

-Aydrian

Latest comments (3)

Collapse
 
ericeberhart profile image
Eric_Eberhart

Handling real-time events from Twitch requires integrating with Twitch's API and implementing event listeners in your streaming setup. Here's a step-by-step guide on how to handle real-time events from Twitch:

Register Your Application: ** Start by registering your **application on the Twitch Developer Portal to obtain API credentials, including a client ID and client secret.

**Authenticate Your Application: **Use OAuth 2.0 authentication to obtain an access token that allows your application to interact with the Twitch API on behalf of a user. This token will be used to authenticate your requests when accessing Twitch's API endpoints.

Subscribe to Webhooks: Twitch offers webhooks for real-time event notifications. Subscribe to the relevant Twitch webhooks based on the events you want to receive updates for, such as follows, subscriptions, donations, or channel updates.

Set Up Webhook Endpoints: Create HTTP endpoints on your server to receive notifications from Twitch's webhooks. These endpoints will handle incoming event payloads and process them accordingly.

Handle Incoming Events: Implement logic in your webhook endpoints to parse incoming event payloads and take appropriate actions based on the event type. For example, if a user follows your channel, you may want to send them a personalized message or trigger an alert on your stream overlay.

Ensure Reliability and Scalability: Implement error handling and retry mechanisms to ensure reliability in handling incoming events. Additionally, design your system to scale gracefully as the number of events and concurrent users increases over time.

Test Your Integration: Test your webhook endpoints thoroughly to ensure they correctly receive and process events from Twitch's API. Use tools like Postman or curl to simulate event payloads and verify your application's behavior.

Monitor and Debug: Monitor your webhook endpoints for any errors or failures and implement logging and monitoring solutions to track the performance of your integration. Debug any issues promptly to maintain a smooth real-time event handling experience.

Stay Up-to-Date with API Changes: Keep an eye on Twitch's API documentation and announcements for any updates or changes to the API endpoints or event payloads. Update your integration accordingly to ensure compatibility with the latest changes.

Implement Additional Features: Once you have the basics in place, consider implementing additional features such as analytics, user engagement tools, or integrations with third-party services to enhance the functionality and value of your Twitch channel.

By following these steps, you can effectively handle real-time events from Twitch and create interactive and engaging experiences for your viewers.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.