[Tutorial] Create Our Own Discord Bot (Part 2) - Basic Functions + Beginning with Steem

View this thread on: d.buzz | hive.blog | peakd.com | ecency.com
·@anonym0us·
0.000 HBD
[Tutorial] Create Our Own Discord Bot (Part 2) - Basic Functions + Beginning with Steem
![Imagen1.png](https://ipfs.busy.org/ipfs/QmSNpW4AHBx2yfRLRpWfK8FAU68iyyFHd1oKB2hSdgLRHf)

[Repository](https://github.com/Carlososuna11/Discord-Tutorial-2)

What's up friends, with my most recent publication about [Navi](https://steemit.com/utopian-io/@anonym0us/navi-a-discord-trail-bot-that-will-help-small-communities-1537050648986), many people have asked me, "Anonym0us, How can I make my own bot for my discord community?", So I decided to upload this simple, but essential tutorial about our own Discord bot, which will be adding more functions to these weeks, but for now we will do something simple: Adding Basic Functions and beginning with steem.

#### What Is a Discord Bot?
If you do not know what a Discord bot is, friend let me tell you that you do not live in the 21st century or have never used Discord. The definition of a bot is simple
> A Discord bot is like a phones Siri.
It’s not necessary to do what you need to do, but it provides functionality and various tools that enable your server to be more lightweight, and streamlined. For example, in order to ban someone from your server, you’d need to go to their profile, scroll down and find the ban @name option. Whereas a discord bot could allow you to do that by inputting a short command in to the chat line, e.g. *.Ban name — this reduces the hassle required to find and scroll. It's quicker, not necessarily better.

#### What Will I Learn?
We will start with the basic functions that our bot can have to use Steem, where we will create three scripts:
1st Which will be the script of the database, where we will create some tables of data (Js working with MySQL) which will be as much to save the user, the pass, or some other data that we are going to require later.
2nd, which will be our main script that will include all the basic functions that we will learn in this tutorial.
3rd The `.JSON` file which will have the dependencies of Steem, discord and MySQL.

#### Requirements
- A [Discord](https://discordapp.com/) Account.
- A [GitHub](https://github.com/) Account.
- A [Heroku](https://www.heroku.com/) Account.
- A [Steemit](https://steemit.com/) Account.
- A [Online Remote MySQL Database](https://www.db4free.net/about.php).
- Basic knowledge of JavaScript.
- Some patience.

#### Difficulty
- Intermediate

#### Configuring the Database
First of all, before creating the scripts, we have to configure the database, which is a very simple step, we will go to the link placed in MySQL database requirements (If you do not have a database of your own) and we will create a base gives free data of 200Mb, more than perfect for this tutorial, only registering your email, password and the name of the database, we would have it ready.

![ttps0wpem8jcjs9yr7rb.png](https://ipfs.busy.org/ipfs/QmYK2DCM7rYQY6wEY6UHKNS8nm4SmxBghPKTRdcAGcwk36)

After we set up our database we will receive an email saying that to continue with the registration click on the link and the registration and creation of our database will be complete

![gbsa7c3anxauvx3f3psr.png](https://ipfs.busy.org/ipfs/QmUv2qeUMBC9sncnMyJS7XquYLvBbra6aAzPuR1vMxcc37)

Well, now we have the database, but we must configure the data tables, probably ask what that is, it is simple, the data tables is where the information is stored, it is distributed by rows and columns, therefore each cell will have a specific information.

#### Configuring the Script

First let's start with the database, for this we will use this script:

`server.js`
```
var mysql = require('mysql');

var con = mysql.createConnection({
  host: "HOST",
  user: "DATABASE-USER",
  password: "DATABASE-PASSWORD",
  database: " YOUR-DATABASE"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  var sql = "CREATE TABLE voter (id INT NOT NULL AUTO_INCREMENT , PRIMARY KEY (id), user text NOT NULL, lastvote text NOT NULL, userid text NOT NULL, usuario text NOT NULL, language text NOT NULL,   text NOT NULL)";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("Table created"); //
  });
});
```

This script is responsible for creating the tables and columns within our database, where we are adding the different names of the columns:
`id` is to place a successive whole number, to locate the row more easily.
`user` will be the user of steemit.
`lastvote` will be the last vote (used for later).
`userid` will be the id of the discord user.
`language` will be the language (used for later).
`wifkey` will be our steemit privatekey (used for later).

Once created and configure the script for the database, we will go to the interesting, as we are starting with steem, we will implement 3 simple functions in the `bot.js` script:
`bot.js`

1st function: Register a user to the bot.

```
const Eris = require("eris");
const steem = require("steem");
var mysql = require('mysql');

var con = mysql.createConnection({
    host: "db4free.net",// the db used
    user: "YOUR USER",
    password: "YOUR PASS",
    database: "YOUR DB NAME"
});

con.connect();
var bot = new Eris("THE BOT TOKEN", { // We create a new instance of our bot (usually named client)
    disableEveryone: true, // Makes it programmatically impossible for the bot to mention @everyone
    getAllUsers: true // It fetches all users, Good for small bots. (recommend)
  });
bot.on("messageCreate", (msg) => { 
  var regex2 = /(\$)+(register)+(\ )/;
  if(msg.content.match(regex2)){
      var usuario = msg.content.replace(msg.content.match(regex2)[0],"");
      var channel = msg.channel.id;
      var uid = msg.author.id;
      con.query('SELECT EXISTS(SELECT * FROM `voter`WHERE `userid`="'+uid+'")', function (error, results, fields) {
          for(i in results){
              for(j in results[i]){
                  x = results[i][j];
                  if(x == 1){
                    bot.createMessage(channel,"<@!" + uid + ">"+ ' Already Registered! || ya estas registrado');
                  }
                  else{
                      con.query('INSERT INTO `voter`(`user`,`userid`, `wifkey`) VALUES ("'+user+'","'+msg.author.id+'","0")', function (error, results, fields) {                       
                          bot.createMessage(channel,"<@!" + uid + ">" + 'your registration was successful');
                      });
                  }
              }
          }
              
              });
          }
	});
}
});
bot.connect();
```

2nd function: Know the reputation of steemit of said user.

```
var regex35 = /(\$)+(Reputation)/;
if(msg.content.match(regex35)){
    var channel = msg.channel.id;
    var uid = msg.author.id;
    con.query('SELECT `user` FROM `voter` WHERE `userid`="'+uid+'"', function (error, results, fields) {
        for(i in results){
            for(j in results[i]){
                namen = results[i][j];
    steem.api.getAccounts([namen], function(err, result) {
        if (!err) {         
            bot.createMessage(channel, "<@!" + uid + ">" + ' Your Reputation of your account @' + namen +'  is ' + steem.formatter.reputation(result[0].reputation) + '' )       
        }
    });
            }
}
    });
}
```

3rd function: Know the percentage of voting power of said user.
```
var regex37 = /(\$)+(Percentage)/;
if(msg.content.match(regex37)){
    var channel = msg.channel.id;
    var uid = msg.author.id;
    con.query('SELECT `user` FROM `voter` WHERE `userid`="'+uid+'"', function (error, results, fields) {
        for(i in results){
            for(j in results[i]){
                namen = results[i][j];
    steem.api.getAccounts([namen], function(err, result) {
        if (!err) {          
            const secondsago = (new Date().getTime() - new Date(result[0].last_vote_time + "Z").getTime()) / 1000;
            const votingPower = (result[0].voting_power + (10000 * secondsago / 432000)) / 100 ;
            var n = votingPower.toFixed(2);         
            bot.createMessage(channel, "<@!" + uid + ">" + ' The percentage of your voting power for your account @' + namen +'  is ' +n+ '%' );
        } 
    });
            }
}
    });
}
```

We would miss the last script, the `package.json` with the dependencies of all the used files.

```
{
  "name": "Navi",
  "main": "bot.js",
  "dependencies": {
    "express": "4.13.3",
    "discord.js": "11.1.0",
    "discord.js-commando": "^0.9.0",
    "eris": "^0.8.4",
    "mysql": "^2.15.0",
    "steem": "^0.7.1",
    "pg": "^6.1.4"
  },
  "version": "1.0.0",
  "scripts": {
    "start": "bot.js"
  },
  "devDependencies": {
    "ws": "3.3.2"
  }
}
```

Once created all these scripts, we will implement the knowledge we acquired with the first tutorial to upload it to heroku and can be seen in discord, now our result would be similar to Navi. let's try it

![nrkb8lowpulvewf8tadh.png](https://ipfs.busy.org/ipfs/QmZbcUZW9oG1bt93Stw4HCKZTEQNEs9mKd7ySdQuK65SSb)

![Imagen1.png](https://ipfs.busy.org/ipfs/QmNd2xPqriZK9Ypo9PJf3JYjyZDZ5eEbQFVLZhbKNwdh65)

For our third tutorial, I plan to implement a script capable of knowing when a user's privatekey is correct, and when it is not, in order to continue implementing more functions from there.

The work test done is called [Navi](https://discord.gg/M8V8yx)

#### Curriculum
- [Part 1](https://steemit.com/utopian-io/@anonym0us/tutorial-create-our-own-discord-button-part-1-upload-it-to-a-web-server-1537571612222)

 You can go through my [profile](https://steemit.com/@anonym0us) to see other publications of other categories approved by @utopian.
👍 , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,