DEV Community

Preeti Agarwal
Preeti Agarwal

Posted on

Create JavaScript Discord bot to alert Twitch live streams

Creating a Discord bot for Twitch live alerts using Node.js involves several steps. You'll need to set up a Discord bot, a Twitch app to get notified when a stream goes live, and then connect them together.

Here is a step-by-step guide to create a basic Discord bot that sends an alert to a Discord channel when a specified Twitch user goes live.

Prerequisites

  • Node.js and npm (Node Package Manager) installed.
  • Discord account and a Discord server where you have permissions to add a bot.
  • Twitch account and a Twitch developer application.

Step 1: Set Up Your Discord Bot

Create a Discord Bot:

  • Go to the Discord Developer Portal.
  • Click "New Application", name it, and save.
  • Go to the "Bot" section and click "Add Bot".
  • Save the token for later (this is the bot's authentication token).
  1. Invite the Bot to Your Server:
    • Go to the "OAuth2" section.
    • In "OAuth2 URL Generator", under "Scopes", select bot.
    • Under "Bot Permissions", select Send Messages.
    • Copy the generated URL, paste it in your browser, and invite the bot to your server.

Step 2: Set Up Your Twitch Developer Application

  1. Create a Twitch App:
    • Go to the Twitch Developer Console.
    • Click "Register Your Application", fill in the details, and save.
      • For OAuth Redirect URLs, enter "https://localhost". OAuth Redirect is not used for this bot.
      • Choose the "Confidential" client type.
    • Note down the Client ID and Client Secret.

Step 3: Create the Bot Using Node.js

Create the bot script:

Create a file named bot.js and add the following code:


    const { Client, GatewayIntentBits } = require('discord.js');
    const axios = require('axios');

    // Discord bot token and channel ID
    const DISCORD_TOKEN = 'YOUR_DISCORD_BOT_TOKEN';
    const CHANNEL_ID = 'YOUR_DISCORD_CHANNEL_ID';

    // Twitch credentials
    const TWITCH_CLIENT_ID = 'YOUR_TWITCH_CLIENT_ID';
    const TWITCH_CLIENT_SECRET = 'YOUR_TWITCH_CLIENT_SECRET';
    const TWITCH_USER_NAME = 'TWITCH_USER_NAME';

    const client = new Client({
      intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent
      ]
    });

    let twitchAccessToken = '';

    // Function to get Twitch access token
    async function getTwitchAccessToken() {
      const response = await axios.post('https://id.twitch.tv/oauth2/token', null, {
        params: {
          client_id: TWITCH_CLIENT_ID,
          client_secret: TWITCH_CLIENT_SECRET,
          grant_type: 'client_credentials'
        }
      });
      twitchAccessToken = response.data.access_token;
    }

    // Function to check if the Twitch user is live
    async function isTwitchUserLive() {
      const response = await axios.get(`https://api.twitch.tv/helix/streams`, {
        headers: {
          'Client-ID': TWITCH_CLIENT_ID,
          'Authorization': `Bearer ${twitchAccessToken}`
        },
        params: {
          user_login: TWITCH_USER_NAME
        }
      });

      return response.data.data.length > 0;
    }

    client.once('ready', () => {
      console.log(`Logged in as ${client.user.tag}!`);

      // Check Twitch status every 60 seconds
      setInterval(async () => {
        try {
          const live = await isTwitchUserLive();
          if (live) {
            const channel = await client.channels.fetch(CHANNEL_ID);
            channel.send(`${TWITCH_USER_NAME} is now live on Twitch! Check it out at https://www.twitch.tv/${TWITCH_USER_NAME}`);
          }
        } catch (error) {
          console.error('Error checking Twitch status:', error);
        }
      }, 60000); // Check every 60 seconds
    });

    client.login(DISCORD_TOKEN);

    // Get Twitch access token at the start
    getTwitchAccessToken().catch(console.error);
Enter fullscreen mode Exit fullscreen mode

Step 4: Run the Bot

Run the bot with the following command:

node bot.js
Enter fullscreen mode Exit fullscreen mode

Conclusion

This bot periodically checks if a specified Twitch user is live and sends a message to a Discord channel if they are. Remember to replace placeholders (YOUR_DISCORD_BOT_TOKEN, YOUR_DISCORD_CHANNEL_ID, YOUR_TWITCH_CLIENT_ID, YOUR_TWITCH_CLIENT_SECRET, TWITCH_USER_NAME) with actual values.

There are also many free services that provide Twitch Discord alerts. These services include Readybot.io Twitch Bot, MEE6 and others.

Top comments (1)

Collapse
 
thomasbnt profile image
Thomas Bnt

Cool script, but if the stream is online for more 60 seconds, your script run again and again and a multiple of same messages will sended to the Discord channel. Don't hesitate to register into a key to avoid this issue ๐Ÿ™Œ
Messages in a Discord server