Unlocking the Power of AI: Building a Sentiment Analysis Discord Bot with MindsDB and HuggingFace

Unlocking the Power of AI: Building a Sentiment Analysis Discord Bot with MindsDB and HuggingFace

Introduction

Sentiment analysis is another important application of artificial intelligence that has gained popularity in recent years. It involves the use of machine learning algorithms to analyze and interpret the emotions and opinions expressed in text. With the increasing use of chat platforms like Discord, there is a growing need for sentiment analysis tools that can help moderators and users understand the emotional tone of the conversations happening on these platforms.

In this guide, we will explore how to build a sentiment analysis bot for Discord using MindsDB and Hugging Face. MindsDB will be used to create a predictive model that can classify text into different sentiment categories, while Hugging Face will provide access to pre-trained models that can be fine-tuned for specific use cases.

By the end of this guide, you will have learned how to build a sentiment analysis bot that can analyze the emotional tone of messages in real-time. This bot can be added to any Discord server, allowing moderators and users to monitor the sentiment of conversations and take appropriate action if necessary. With this tool, you can create a more positive and inclusive community on Discord.

What is MindsDb

Building and deploying predictive models can be a daunting task, especially for those who are not experts in machine learning. However, MindsDB provides a solution that makes the process accessible to everyone. This open-source machine learning tool simplifies the process of creating machine learning models by providing a user-friendly interface that allows users to create models using SQL queries.

MindsDB offers a wide range of machine learning capabilities, including classification, regression, anomaly detection, and time-series forecasting. Its automated machine learning (AutoML) technique makes the process of model selection, feature engineering, and hyperparameter tuning automated and streamlined.

MindsDB is a powerful tool that allows individuals and businesses to leverage the power of machine learning without the need for extensive knowledge or expertise. It can be applied to various use cases such as fraud detection and natural language processing, enabling users to make informed and data-driven decisions.

Create and Train Sentimental Analysis Huggingface Model

We can create a Hugging Face model for sentimental Analysis using the below command in MindsDBCloud Editor.

CREATE MODEL sentiment_model
PREDICT sentiment
USING engine='ENGINE_NAME',
  model_name= 'MODEL_NAME',
  input_column = 'COLUMN',
  labels=['negative','neutral','positive'];

Before we proceed, let's take a look at all of the parameters we're passing in code:

• CREATE MODEL sentiment_model: This command creates a new machine learning model called 'sentiment_model'.

• PREDICT sentiment: This specifies that the model will predict a target variable called 'sentiment'.

• USING engine='ENGINE_NAME': This specifies the machine learning engine or library that will be used to build the model. The 'ENGINE_NAME' will be replaced with the actual name of the library used.

• model_name= 'MODEL_NAME': This specifies the pre-trained model that will be used as the base for the sentiment analysis model. The 'MODEL_NAME' will be replaced with the name of the specific pre-trained model used.

• input_column = 'COLUMN': This specifies the name of the column in the dataset that contains the input data, which in this case is 'COLUMN'.

• labels=['negative','neutral','positive']: This specifies the possible categories or labels that the model can predict. In this case, the labels are 'negative', 'neutral', and 'positive'. The model will classify the input data into one of these three categories.

The actual query will become like this after replacing the placeholders with appropriate values.

CREATE MODEL sentiment_model
PREDICT sentiment
USING engine='huggingface',
  model_name= 'cardiffnlp/twitter-roberta-base-sentiment',
  input_column = 'comment',
  labels=['negative','neutral','positive'];

This should return the row record of the newly created model from the models table upon successful execution.

Status of the Model

The model might take a while to be ready for use. In the meantime, we can check its status with the query below.

SELECT status FROM models
WHERE name = 'sentiment_model';

Create Discord Bot using Node.js

Setup Discord Application

  1. Open the Discord app and create a new Discord server.

  2. Create a new application on the Discord Developer Portal (discord.com/developers/applications).

  3. Give the application a name and click "Create".

  4. Click on the "Bot" section and then click "Add Bot" and give the bot a username and click "Save Changes".

  5. Click on the "OAuth2" section and select the "bot" checkbox under "Scopes" and select the permissions the bot should have under "Bot Permissions".

  6. Copy the generated URL and paste it into a new browser window.

  7. Select the server where the bot should be added and click "Authorize"

Application Setup

  1. Run the command "npm init" to create a new Node.js project.

  2. Install all the necessary library by running the below command

    • npm install discord.js

    • npm install express

    • npm install dotenv

    • npm install mindsdb-js-sdk

              {
                "name": "discordbot",
                "version": "1.0.0",
                "description": "This is Discord bot which Interact with you.",
                "main": "index.js",
                "scripts": {
                  "start": "node index.js",
                  "test": "echo \"Error: no test specified\" && exit 1"
                },
                "author": "Arman Chand",
                "license": "ISC",
                "dependencies": {
                  "body-parser": "^1.20.2",
                  "discord.js": "^14.9.0",
                  "dotenv": "^16.0.3",
                  "express": "^4.18.2",
                  "mindsdb-js-sdk": "^2.2.0"
                }
              }
      
  3. Create a new JavaScript file in the folder and name it "index.js" and paste the following code:

     require('dotenv').config();
     const express = require('express');
     const app = express();
     const Discord = require('discord.js');
     const bodyParser = require("body-parser");
    
     const { connectToMindsDBCloud, analyzeTextSentiment} = require("./dispatcher/mindsdb.js")
     const client = new Discord.Client({ intents: [
       Discord.GatewayIntentBits.Guilds,
       Discord.GatewayIntentBits.GuildMessages,
       Discord.GatewayIntentBits.MessageContent
     ]})
    
     app.use(bodyParser.urlencoded({ extended: true }));
     app.use(bodyParser.json());
    
     app.get('/', (req, res) => {
       res.send('Discord bot is running!');
     });
    
     client.on('ready', () => {
       console.log(`Logged in as ${client.user.tag}!`);
     });
    
     client.on('messageCreate', async (message) => {
       if (message.author.bot) return;
    
       if (message.content.startsWith('!sentiment')) {
         const query = message.content.slice(10).trim();
         await connectToMindsDBCloud();
         const response = await analyzeTextSentiment(query); 
         console.log("result----->",response);
         message.reply(JSON.stringify(response.rows[0]));
       }
     });
    
     client.login(process.env.TOKEN);
     const PORT = process.env.PORT || 3000;
     app.listen(PORT, () => {
       console.log(`Express app is listening on port ${PORT}!`);
     });
    
  4. Maintain a separate .env file to store the secret key and password.

  5. Create a new file (mindsdb.js) where we maintain code for Maintaining connection with MindsDB Cloud and Function to interact to fetch the result of the trained Model to Predict the Queries.

     async function connectToMindsDBCloud() {
       try {
         await MindsDBCloud.connect({
           user: process.env.MINDSDB_USER,
           password: process.env.MINDSDB_PASS,
         });
         console.log("Suceesfully connected to MindsDB Cloud");
       } catch (error) {
         console.log("Problem connecting to MindsDB Cloud:", error);
         throw error;
       }
     }
    
  6. Create an async function that attempts to run a SQL query using the MindsDBCloud.SQL.runQuery method. The method takes in a query string that selects data from a specified table (snetimentModel) where the text column matches the message parameter. The results of the query are stored in a variable called sentimentResponse.

     async function analyzeTextSentiment(message) {
         let retries = 3; // Maximum number of retries
    
         while (retries > 0) {
           try {
             const text = `SELECT sentiment FROM ${sentimentmodel} WHERE comment='${message}'`;
             const sentimentResponse = await MindsDBCloud.SQL.runQuery(text);
             if (!sentimentResponse.rows) {
               throw new Error("Invalid response from MindsDB");
             }
             return sentimentResponse;
           } catch (error) {
             console.log("Error analyzing sentiment:", error);
             retries--;
             if (retries === 0) {
               throw new Error("Maximum number of retries reached");
             }
             await new Promise((resolve) => setTimeout(resolve, 1000)); // Wait for 1 second before retrying
           }
         }
       }
    
  7. Save the file and run the command "npm start" in the terminal to start the discord bot.

  8. Open Discord and send a message containing "!sentiment " and then pass the word which you want to verify whether it's a spam or ham message, to the server where the bot is located.

Congratulations, you have created a basic Discord bot using Node.js! From here, you can continue to add features and functionality to your bot to make it more useful and interactive.

Deployment using Railway.app

  1. Create a new project in railway.app: First, create a new project in railway.app by logging in to your account and clicking on "New Project." Choose a name and select the "Node.js" template.

  2. Connect your Github or Gitlab repository: If your Discord bot code is already hosted on Github or Gitlab, you can connect your repository to railway.app by clicking on the "Connect Repository" button in your project dashboard. Otherwise, you can upload your code directly to railway.app.

  3. Set up environment variables: Set up environment variables for your Discord bot, such as the Discord bot token and any API keys or credentials required for your bot's functionality. You can do this by clicking on the "Environment Variables" tab in your project dashboard and adding the necessary variables.

  4. Install dependencies: Install the necessary dependencies for your Discord bot by running "npm install" in the terminal or command prompt.

  5. Start your bot: Start your Discord bot by running the command "node index.js" in the terminal or command prompt. Make sure your bot is functioning as expected by testing its functionality.

  6. Configure a Discord webhook: In order to keep your bot running on railway.app, you'll need to configure a Discord webhook to ping your bot periodically. You can do this by adding a new "Scheduled Task" in your railway.app project dashboard and specifying the URL for your webhook.

  7. Expose your application: Go to the setting tab and check the Domain section, Click on Generate url . Now your application is exposed on the internet.

    URL: sentimentanalysisdiscordbot-production.up.railway.app

That's it! Your Discord bot should now be up and running on railway.app.

Conclusion

Sentiment analysis can be a powerful tool for businesses and individuals to make data-driven decisions based on the emotions and opinions of their customers or audience. With the use of machine learning tools like MindsDB and Hugging Face's Transformers library, sentiment analysis can be performed with high accuracy and efficiency.

The process of creating a sentiment analysis model may involve collecting and labeling a dataset of text data, pre-processing the data to prepare it for machine learning, selecting and training an appropriate model, and evaluating the model's performance. Once the model is trained and deployed, it can be used to classify text data into different sentiment categories like positive, negative, or neutral.

Overall, sentiment analysis can provide valuable insights into customer or audience sentiment, allowing businesses to better understand their customers and make informed decisions about their products or services. The use of machine learning tools like MindsDB and Hugging Face's Transformers library can simplify and streamline the process of sentiment analysis, making it more accessible to individuals and businesses alike.

MindsDB has recently organized a Hackathon in collaboration with Hashnode. You can check all the details by clicking on the banner below.