如何用Node.js建立一个Twitch聊天机器人

673 阅读11分钟

在Node.js中构建一个Twitch聊天机器人

Twitch是一个在线流媒体平台,它允许流媒体人和观众之间进行生动的互动。起初只是一个为游戏玩家提供的小型游戏流媒体平台,但很快就迎来了人气的飙升,并一跃成为了曾经的平台。

它不仅支持其他服务,而且还拥有广泛的内容。例如,有烹饪节目、现场谈话节目、日常生活流、现场聊天和互动等等。

流媒体人根据不同的内容,只要内容符合公司的[服务条款]、[社区准则]和[销售条款],就可以从每月的订阅费用或粉丝的捐款中获得收入。

由于服务的增长,出现了与Twitch API互动以创建更多个性化服务或功能的更大需求。这导致了与服务互动的机器人的开发和部署。

这些天才开发者创造的机器人包括聊天机器人、观众参与机器人、监控和统计机器人、投票机器人、聊天和内容管理机器人等。

尽管已经有这么多不同的机器人被创建或修改,但仍然需要根据你想解决的问题,提供个性化的机器人。

在本教程中,我们将了解Twitch API以及如何在Node.js中创建一个简单的聊天机器人与之互动。

主要收获

在本教程结束时,你将学会。

  • 什么是Twitch API。
  • 关键组件、基础知识,以及如何在Node.js中与API互动。
  • 如何构建一个简单的Twitch聊天机器人。
  • 如何在Node.js中运行Twitch聊天机器人。

先决条件

跟随本教程所需的一些基础知识包括以下内容。

  • 网络开发基础知识。
  • 与Twitch网站的少量互动。这有助于了解Twitch是如何工作的,它的一些服务,以及你将处理的界面。
  • 在你的机器上安装一个IDE。
  • 在你的机器上安装并配置好Node.js环境。
  • 一个稳定的互联网连接。

什么是聊天机器人

让我们从这个有趣的问题开始。

Chat-Bot 是一个有能力通过文本信息、语音、甚至视频进行在线聊天的应用程序。它可以有预设的对话输入和预期的输出。他们也可以使用人工智能根据上下文创造新的对话。大多数都不是自主的,因此在它不理解的任何问题上,人类总是在附近。

尽管这些聊天机器人还没有成为完全自主的,但每天都在进行改进,使其接近完美。

聊天机器人的服务已经被整合到许多不同的地方。其中两个地方是游戏和流媒体服务。这些都使网站具有互动性,并看到了更多的观众。

聊天机器人的优势

  • 与人类可以处理的客户数量相比,一旦部署,可以轻松地处理多个客户。
  • 由于他们被教导一些主要功能、输入和输出,他们提供快速重复的答案而不会感到厌倦或疲惫。
  • 向所有客户一致地提供常见问题解答(FAQ)的答案。这可以防止任何歧视。
  • 它的运行成本很低。
  • 易于部署。
  • 它们可以始终在线,这就防止了用户的关闭时间和停机时间。

由于它们可以在服务器上连续运行,例如,像Section.io的Node.js服务器。这些服务器可以24/7运行,任何时候用户上线直播,总能在网上找到。这促进了程序的高可用性。

聊天机器人的劣势

虽然它们有一些有趣和相当合理的功能,但它们也有另一个面孔。

这些包括。

  • 聊天机器人需要大量的维护,因为要不断增加更多的功能,才能使它们具有竞争优势。他们还需要能够处理客户提出的未回答的问题。
  • 它们不能识别客户的情绪,如救济或愤怒。这使他们无法在服务之后或之前充分捕捉到用户的反馈。他们对反馈表的依赖使他们受到限制。
  • 需要人监督或作为后备,这可能是昂贵的。
  • 系统故障可能导致关键服务受到限制。

什么是Twitch的API?

这是用于访问TWITCH系统和开发新集成的API。它是免费的。你可以使用脚本标签或作为Node.js的模块访问它。

在Node.js中,我们使用tmi.js库。

为了实现我们的目标,我们将做以下工作。

  • 创建一个Twitch账户并建立一个Twitch频道。
  • 创建一个演示流。
  • 获得Bot的OAuth密钥。这将被用来允许机器人访问我们的频道。
  • 创建一个简单的Twitch聊天机器人,并将其连接到我们的流。
  • 测试我们的机器人。

创建和设置一个Twitch账户和频道

访问[www.twitch.tv\],创建一个新的用户账户。您可以在设置中完成其他细节的设置,如生物、资料图片和资料横幅。

确保你的状态被设置为Online ,以避免被你的流媒体频道订阅者视为不活跃。

现在,点击Channel ,如下图所示。

Channel

Twitch频道

在频道标签上,你将能够看到你的频道是直播还是离线。你还可以根据你的喜好来定制你的频道。

创建一个演示流

在Twitch和其他许多流媒体平台上有许多流媒体托管服务。在Twitch,你需要一个流媒体。我推荐使用Streamyard

Streamyard是一个在线流媒体服务,允许你一次将你的内容流向一个或多个平台。你不需要任何安装,因为它是一个网站。它同时提供免费服务(用于小型流媒体)和付费服务(用于大型流媒体)。它使用起来很简单,不需要太多的帮助。

只要访问它,我们将做以下工作。

  • 创建一个新账户并登录。
  • 在你的流中添加一个目的地。你可以添加一个以上的目的地。这里,我们添加Twitch。
  • 验证你想要的流媒体账户。
  • 点击 "创建广播",选择广播的目的地,并输入广播名称。
  • 输入你要显示的名字。选择你将在流媒体期间使用你的麦克风或摄像机。现在,点击'进入工作室'。选择你自己作为流媒体的一部分。
  • 点击'Go live',开始在线串流。
  • 在另一个标签上,打开Twitch并访问你的账户。导航到频道标签,看看你正在向观众播放的内容。你可以看到聊天记录,还可以探索其他功能。

streamyard

流媒体的Streamyard

获得机器人OAuth密钥

我们的机器人有两种方式可以访问一个频道。

  • 匿名的:在这里,身份(用户名和密码)是不需要的,也没有指定。这在某些情况下是有利的,因为人们不会被追踪到。它限制人们只能查看,但不能回复或参与聊天。
  • OAuth令牌授权:这里,机器人的身份是必需的。它允许机器人积极监测和参与聊天。

我们将处理这两种情况。让我们获得一个OAuth令牌,我们将在以后的项目中使用。

你可以从twitchapps.com/tmi/,我认为这是一个简单的方法。你也可以从twitchtokengenerator.com/。为了安全起见,请确保这个密钥是安全的。

创建一个简单的Twitch聊天机器人

创建一个根目录并命名为 "Twitch-Chatbot"。

文件夹结构

整体文件结构如下所示。

.
├── Twitch-Chatbot
    ├── node_modules
    ├── .env
    ├── app.js
    └── package.json

在这里,我们将创建一个名为app.js 的文件,这将是我们的应用程序入口点。使用Visual Studio Code打开该文件夹,并打开集成终端。

在终端中使用初始化项目。

npm init -y

我们将安装所需的依赖项--tmi.jsdotenv ,使用。

npm i dotenv tmi.js

tmi.js 将用于访问Twitch,而 将用于从主应用程序入口点安全地存储我们的凭证。dotenv

.env文件

创建一个文件并将其命名为.env 。现在,我们将存储我们的环境变量,如用户名、OAuth和频道。

注意:如果你想把你的代码上传到GitHub,请记得把它包含在.gitignore 文件中,以防止它被上传,造成安全漏洞。我希望你在仓库中使用git secrets。请确保你也在你的仓库中启用了git guardian

该文件应该是这样的。

TWITCH_USERNAME= Name_of_the_chatbot
TWITCH_OAUTH= The_key_gotten_from-the _website
TWITCH_CHANNEL= Your_Chanell_Name

复制并粘贴到适当的部分并保存。

package.json文件

package.json ,将包含如下所示的数据。

{
    "name": "Twitch-Chatbot",
    "version": "1.0.0",
    "description": "Twitch node.js chat bot",
    "main": "app.js",
    "scripts": {
        "start": "node app.js",
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "repository": {
        "type": "git",
        "url": "git+https://github.com/justusmbuvi/Twitch-Chatbot-in-Node.js.git"
    },
    "keywords": [
        "Twitch",
        "node.js",
        "chat",
        "bot"
    ],
    "author": "Justus_Mbuvi",
    "license": "MIT",
    "bugs": {
        "url": "https://github.com/justusmbuvi/Twitch-Chatbot-in-Node.js/issues"
    },
    "homepage": "https://github.com/justusmbuvi/Twitch-Chatbot-in-Node.js#readme",
    "dependencies": {
        "dotenv": "^10.0.0",
        "tmi.js": "^1.8.3"
    }
}

app.js

打开我们的应用程序入口点。而且,现在我们将做以下工作。

  • 需要必要的node模块。我们还将配置tmi.js通道连接、重新连接和安全选项,如下所示。
// Require necessary node modules
// Make the variables inside the .env element available to our Node project
require('dotenv').config();

const tmi = require('tmi.js');

// Setup connection configurations
// These include the channel, username and password
const client = new tmi.Client({
    options: { debug: true, messagesLogLevel: "info" },
    connection: {
        reconnect: true,
        secure: true
    },

// Lack of the identity tags makes the bot anonymous and able to fetch messages from the channel
// for reading, supervision, spying, or viewing purposes only
    channels: [`${process.env.TWITCH_CHANNEL}`]
});
  • 建立连接并显示任何出现的错误。
// Connect to the channel specified using the setings found in the configurations
// Any error found shall be logged out in the console
client.connect().catch(console.error);

// We shall pass the parameters which shall be required
client.on('message', (channel, tags, message, self) => {
    // Lack of this statement or it's inverse (!self) will make it in active
    if (self) return;
    
// This logs out all the messages sent on the channel on the terminal
    console.log(message);

});

运行代码来窥探聊天记录

运行这段代码,使用。

npm run start

node app.js

该机器人可以加入频道流--在线或离线。这使得人们可以在需要时部署它。你也能够在出现任何错误的情况下迅速关闭它。

输出应该是这样的,以显示与频道的成功连接。

john@john:~/Tofa/Projects/Twitch/Twitch-Chatbot-in-Node.js$ node app.js
[03:30] info: Connecting to irc-ws.chat.twitch.tv on port 443..
[03:30] info: Sending authentication to server..
[03:30] info: Connected to server.
[03:30] info: Executing command: JOIN #justusmbuvi
[03:30] info: Joined #justusmbuvi

前往浏览器,使用Streamyard开始直播,同时在另一个标签上监控你的Twitch频道。你可以邀请其他人到你的频道,使会议尽可能的互动。你也可以只是自己聊天,以防你正在测试它。

在聊天选项卡中发送一条信息,你会看到它在你的终端上被注销了。这证明是成功的。

正如你所看到的,我们不能与这个实时Twitch聊天互动,而只能获取对话内容。

让机器人有反应

现在我们将添加我们的身份和输出选项。

  • 删除console.log(message); 行。
  • 在括号内,我们将添加选择性语句,以获取我们所需的用户输入并返回相应的输出。
  • 我们使用message 获取用户输入,并使用client.say(); 将输出返回到聊天室,其中我们使用tags 获取用户名。
  • 我们还能够添加另一个选择性语句,它将检查第一个输入--upvote、cheer或任何其他。如果它找到前两个,它就会返回一个结果。否则,它将保持沉默。

该代码如下所示。

// Require necessary node modules
// Make the variables inside the .env element available to our Node project
require('dotenv').config();

const tmi = require('tmi.js');

// Setup connection configurations
// These include the channel, username and password
const client = new tmi.Client({
    options: { debug: true, messagesLogLevel: "info" },
    connection: {
        reconnect: true,
        secure: true
    },

    // Lack of the identity tags makes the bot anonymous and able to fetch messages from the channel
    // for reading, supervision, spying, or viewing purposes only
    identity: {
        username: `${process.env.TWITCH_USERNAME}`,
        password: `oauth:${process.env.TWITCH_OAUTH}`
    },
    channels: [`${process.env.TWITCH_CHANNEL}`]
});

// Connect to the channel specified using the setings found in the configurations
// Any error found shall be logged out in the console
client.connect().catch(console.error);

// When the bot is on, it shall fetch the messages send by user from the specified channel
client.on('message', (channel, tags, message, self) => {
    // Lack of this statement or it's inverse (!self) will make it in active
    if (self) return;

    // Create up a switch statement with some possible commands and their outputs
    // The input shall be converted to lowercase form first
    // The outputs shall be in the chats
    
    switch (message.toLowerCase()) {
        // Use 'tags' to obtain the username of the one who has keyed in a certain input
        // 'channel' shall be used to specify the channel name in which the message is going to be displayed
        //For one to send a message in a channel, you specify the channel name, then the message
        // We shall use backticks when using tags to support template interpolation in JavaScript
        
        // In case the message in lowercase is equal to the string 'commands', send the sender of that message some of the common commands

        case 'commands':
            client.say(channel, `@${tags.username}, available commands are:
            Commands Help Greetings Hi !Website !Name
           
            For more help just type "Help"
            `);
            break;
            
            // In case the message in lowercase is equal to the string '!website', send the sender of that message your personal website
        case '!website':
            client.say(channel, `@${tags.username}, my website is www.section.io!`);
            break;
            
            // In case the message in lowercase is equal to the string 'greetings', send the sender of that message 'Hello @Username, what's up?!'
        case 'greetings':
            client.say(channel, `Hello @${tags.username}, what's up?!`);
            break;
            
            // In case the message in lowercase is equal to the string 'hi', send the sender of that message 'Username, hola'
        case 'hi':
            client.say(channel, `${tags.username}, hola!`);
            break;
            
            // In case the message in lowercase is equal to the string '!name', send the sender of that message the name of the chatbot
        case '!name':
            client.say(channel, `Hello @${tags.username}, my name is ChatBot! Type "help" to continue...`);
            break;
            
            // In case the message in lowercase is equal to the string 'help', send the sender of that message all the available help and commands
        case 'help':
            client.say(channel, `${tags.username}, Use the following commands to get quick help:
            -> Commands: Get Commands || 
            Help: Get Help || 
            Greetings: Get Greetings || 
            Hi: Get "Hola" || 
            !Website: Get my website || 
            !Name: Get my name || 
            !Upvote first_name second_name: Upvote user first_name second_name ||  Upvote first_name second_name: Upvote user first_name second_name || 
            !Cheer first_name second_name: Cheer first_name second_name || Cheers first_name second_name: Cheer first_name second_name --

            For more help just ping me up!
            `);
            break;
            
            
            // In case the message in lowercase is none of the above, check whether it is equal to '!upvote' or '!cheers'
            // these are used to  like certain users' messages or celebrate them due to an achievement
            
        default:
            // We shall convert the message into a string in which we shall check for its first word
            // and use the others for output
            let mymessage = message.toString();
            
            // We shall split the input message and check the string before the space if it is equal to '!upvote' or 'upvote'
            if ((mymessage.split(' ')[0]).toLowerCase() === '!upvote' || 'upvote') {
            
                // You can add some emojis which will appear in the chat using their emoji names
                // For example "PopCorn" or "TwitchLit" (fire emoji)
                // We shall then take the first and second strings after the space and display them together with the username
                // This shall output 'fireEmoji first_name second_name fireEmoji you have been UPVOTED by USERNAME'
                client.say(channel, `TwitchLit @${(mymessage.split(' ')[1] + '_' + mymessage.split(' ')[2])} TwitchLit  you have been UPVOTED by ${ tags.username }`);


                // We shall check if it is !cheer or cheers
                // If so, we shall display beer emojis (HSCheers) and messages
                // The bots output shall be 'beerEmoji first_name second_name beerEmoji you have been UPVOTED by USERNAME'
            } else if ((mymessage.split(' ')[0]).toLowerCase() === '!cheer' || 'cheers') {
                console.log(`HSCheers @${(mymessage.split(' ')[1] + '_' + mymessage.split(' ')[2])} HSCheers you have been UPVOTED by ${ tags.username }`);
            }
            break;
    }
});

运行它

用以下方法运行代码。

npm run start

node app.js

现在,它将按照你的配置给出输出。

下面是一个例子。

john@john:~/Tofa/Projects/Twitch/Twitch-Chatbot-in-Node.js$ node app.js
[02:15] info: Connecting to irc-ws.chat.twitch.tv on port 443..
[02:15] info: Sending authentication to server..
[02:15] info: Connected to server.
[02:15] info: Executing command: JOIN #justusmbuvi
[02:15] info: Joined #justusmbuvi
[02:15] info: [#justusmbuvi] <justusmbuvi>: hi
[02:15] info: [#justusmbuvi] <justusmbuvi>: justusmbuvi, hola!

它将看起来像这样。

Live demo

现场演示

进一步练习

  • 试着用其他语言和框架来制作聊天机器人,这可能符合你的需要。
  • 在Section.io的远程Node.js服务器上启动你的聊天工具,如Section.io Node.js文档中所示。
  • 整合本地或在线数据库来存储你的聊天记录,以便日后查看,并将其显示在网页上。

总结

聊天机器人对我们的生活至关重要。虽然它们有许多优点,但也有一些缺点。它们继续以新的发明和功能让我们感到惊讶,模仿甚至超越了人类的智慧。我们希望它们有朝一日能提高到超越人类的智力。