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

in #utopian-io6 years ago

Imagen1.png

Repository

What's up friends, with my most recent publication about Navi, 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

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

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

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

Imagen1.png

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

Curriculum

You can go through my profile to see other publications of other categories approved by @utopian.

Sort:  

I thank you for your contribution. Here are my thoughts;

  • You might consider changing topics to preserve some uniqueness. Similar tutorials can be easily found on the internet. Being unique with tutorials on Utopian is not required, but preferable as we value rare posts more than others.

  • One of the images you used in your post isn't English, which might cause confusions. Consider using English resources in your tutorial to avoid confusions.

    • Also, red color over the white image with black text is kinda hard to read. Please consider moving the location of the text and changing the color of it.
  • Your sentences are artificial. This makes them hard to read and understand. To overcome that, you should check the structure of your sentences and use a proper grammar. It is no shame to not, but it would be better as this is a tutorial.

  • Including same introduction for each part makes your tutorial messy. It would be better if you include them only in your first post.


Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you for your review, @yokunjon!

So far this week you've reviewed 1 contributions. Keep up the good work!

Hi @anonym0us!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @anonym0us!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.24
TRX 0.21
JST 0.036
BTC 98210.68
ETH 3384.50
USDT 1.00
SBD 3.43