Search code examples
discorddiscord.jsgithub-pages

How do I communicate through my discord bot and website (and get/store data in my discord bot)


I'm trying to make a Discord bot where whenever you press/do something on the website, it communicates with the bot, and sends data to it. Does anyone have any suggustions? Here is some of the code I have for one of the pages on my GitHub hosted site:

<html>
<!–- Website Stuff -–>
<button onclick="share()">Share</button>
<p id="sharedtext"></p>
<script>
function share() {
var projectID = prompt('Whats the project ID of your scratch project?')

<!-- Send data to bot -->

document.getElementById("sharedtext").innerHTML = "Project Shared.";
}
</script>

I use discord.js to make my discord bots. I also have a good understanding of JavaScript too.


Solution

  • You can use a mysql database that saves the data from the website and the bot sets an Interval for like every 5 seconds to check if there is new data and if there is that it does the required action. The HTML:

    <html>
      <body>
        <button onclick="share()">Share</button>
        <p id="sharedtext"></p>
        <script>
        function share() {
            var projectID = prompt('Whats the project ID of your scratch project?');
            var path = 'Action page path here'; //Change this to the action page path
            if(projectID !== null){
               var Http = new XMLHttpRequest();
               Http.responseType = 'text';
               Http.onreadystatechange = function(){
                 if(Http.readyState == 4 && Http.status == 200){
                     document.getElementById("sharedtext").innerHTML = Http.response;
                 }
               }
               Http.open("POST", path, true);
               Http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
               Http.send(`projectID=${projectID}`);
            }
        }
        </script>
      </body>
    </html>
    

    The action page:

    <?php
       $hostname = 'localhost';
       $username = 'root';
       $password = '';
       $dbname = 'db';
       $conn = new mysqli($hostname, $username, $password, $dbname);
       if(!$conn){
           echo 'There was an error while connecting to the database!';
           exit();
       }
    
       if(isset($_POST['projectID'])){
          $stmt = $conn->prepare("SELECT * FROM yourTable WHERE projectid = ?");
          $stmt->bind_param("s", $_POST['projectID']);
          $stmt->execute();
          $result = $stmt->get_result();
          if($result->num_rows < 1){
              $stmt2 = $conn->prepare("INSERT INTO yourTable (projectid) VALUES (?)");
              $stmt2->bind_param("s", $_POST['projectID']);
              $stmt2->execute();
              echo 'Project Shared.';
              exit();
          } else {
             echo 'The project ID has already been shared!';
             exit();
          }
       } else {
           echo 'Invalid method';
           exit();
       }
    ?>
    

    The bot:

    const Discord = require('discord.js');
    const mysql = require('mysql');
    const client = new Discord.Client();
    
    var conn = = mysql.createPool({
         connectionLimit : 50,
         host            : 'localhost',
         user            : 'root',
         password        : '',
         database        : 'db'
    });
    
    var diff, length, numb;
    function checkNew(){
        conn.query('SELECT * FROM yourTable ORDER BY id ASC', function(err, results){
            if(err) return console.log(err);
            if(length === results.length) return;
            diff = results.length - length;
            numb = results.length;
            length = results.length;
            while(diff > 0){
                results[numb - 1].projectid //Do something with the project id
                --numb;
                --diff;
            }
        });
    }
    client.once("ready", () => {
        console.log(`Started`);
        setInterval(checkNew, 5000);
    });
    

    The MySQL:

    CREATE TABLE yourTable(
        id int(11) AUTO_INCREMENT PRIMARY KEY NOT NULL,
        projectid TINYTEXT NOT NULL
    );