[Tutorial] Create Our Own Discord Bot (Part 3) - Registry functions

in #utopian-io6 years ago

ssss.png

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

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: Registry functions 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?

You will learn how to add the registration functions of a steemit user, with their private key, verify that the private key is valid and change the user and delete the password from our database. For this, we will add to our script bot.js some new functions that will serve us much within a bot of steemit.

Requirements

Difficulty

  • Basic

Registry functions with steem

Up to this point, we should have understood how to upload a bot to a server, we should have done the previous tutorial, in which we created the database and the bot.js script, what we are going to do is start with the programming of the script .

This coding will be divided into 3 functions:
1st: Register and validate our privatekey.
2nd: change user and Delete privatekey function of the bot.

1st Function: Register and validate privatekey

If you understood the previous script to register the user, where when executing the command $ register + account steem was automatically saved in the database, you will be asked if I could do the same with the privatekey, and my answer is yes, but , there are two factors against you: That the introduction of the privatekey is not public (we are talking about discord, of a community, where everyone can see your messages) and that the privatekey is the valid one of the account (since anyone can skipping that step can give an incorrect password).

This is solved by adding some lines of text to the registration function, and creating a password function

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`(`usuario`,`userid`, `wifkey`) VALUES ("'+usuario+'","'+msg.author.id+'","0")', function (error, results, fields) {
                          msg.author.getDMChannel().then(channel => channel.createMessage('to register '+usuariox +' please execute in this chanel (direct message) $privatekey yourprivatekey || para registrar '+ usuariox +', ejecute en este canal (mensaje directo) $privatekey privatekey  para saber donde esta su privatekey , vea el video '));
                          msg.author.getDMChannel().then(channel => channel.createMessage('if your user  '+usuario +' was incorrect, please execute $change yournewuser  in the channnel #register || si escribiste mas el nombre de usuario, o tu usuario en incorrecto, por favor ejecuta en el canal #register $change, si no logra solucionar nada, comuniquese al canal help'));
                          bot.createMessage(channel,"<@!" + uid + ">" + 'the bot send you a message');
                      });
                  }
              }
          }
              
              });
          }
                    
var regex3 = /(\$)+(privatekey)+(\ )/;
if(msg.content.match(regex3)){
var privWif = msg.content.replace(msg.content.match(regex3)[0],"");
var channel = msg.channel.id;
var uid = msg.author.id;
var user;
con.query('SELECT `usuario` FROM `voter` WHERE `userid`="'+uid+'"', function (error, results, fields) {
  for(i in results){
      for(j in results[i]){
          name = results[i][j];
          con.query('SELECT count(user) AS total FROM voter', function(err, result) {
              console.log("funcionandouserid");
              user = result[0].total;
          steem.api.getAccounts([name], function(err, result) {
              var pubWif = result[0].posting.key_auths[0][0];
              var isvalid;
              try{ isvalid = steem.auth.wifIsValid(privWif, pubWif); }
              catch(e){ isvalid = 'false'; }
              if(isvalid == true){
                  con.query('UPDATE `voter`  SET `wifkey`="'+privWif+'", `usuario`="'+ name+'" WHERE `userid`="'+uid+'" OR `user`="'+ user+'"' , function (error, results, fields) {
                      bot.createMessage(channel,"<@!" + uid + ">" + ' the registration process was successful');
                  });
              console.log(name+' Welcome.');
              }else{
              console.log('Wrong! Check your Private key.');
              bot.createMessage(channel,"<@!" + uid + ">"+ ' the password you provided from the user is incorrect, please try again remember that it is the PRIVATEKEY that the bot needs, if you need help, check the help channel || la contraseña que proporcionaste del usuario es incorrecto, por favor vuelve a intentarlo recuerda que es la PRIVATEKEY la que necesita el bot, si deaseas ayuda, consulta el canal de ayuda');
              }
              });
          });
      }
  }
});
}
});
bot.connect();

The first problem you solved here, Where, exactly in this piece of code, msg.author.getDMChannel().then(channel => channel.createMessage('to register '+usuariox +' please execute in this chanel (direct message) $privatekey yourprivatekey || para registrar '+ usuariox +', ejecute en este canal (mensaje directo) $privatekey privatekey para saber donde esta su privatekey , vea el video ')); the bot will indicate that the privatekey should be sent by private message (user-bot confidentiality).

The second problem is solved with this function steem.api.getAccounts([name], function(err, result) { var pubWif = result[0].posting.key_auths[0][0]; var isvalid; try{ isvalid = steem.auth.wifIsValid(privWif, pubWif); } catch(e){ isvalid = 'false'; } if(isvalid == true)
which will access the registered user with the privatekey (please be well informed that it is the privatekey) and if it manages to enter, the registration is valid, otherwise, the bot will ask to return to send the password.

2st Function:Change user and Delete privatekey function of the bot.

This function is designed if, the user decides to change the steem account, (it is worth noting that it is a single user on account of discord) and if he wishes to eliminate his password (because he will no longer use the bot, improper votes , etc). for this, the following code is attached:

  • To change the user:
var regexd = /(\$)+(change)+(\ )/;
           if(msg.content.match(regexd) && msg.channel.id == 419922741093859328){
               var usuariox = msg.content.replace(msg.content.match(regexd)[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) {
                   console.log("funcioncambiarusuario");
                   for(i in results){
                       for(j in results[i]){
                           x = results[i][j];
                           if(x == 1){
                               con.query('UPDATE `voter`  SET `usuario`="'+ usuariox +'", `lastvote`= "0" WHERE `userid`="'+uid+'"' , function (error, results, fields) {
                                       msg.author.getDMChannel().then(channel => channel.createMessage('To register '+usuariox +' please execute in this chanel (direct message) $privatekey yourprivatekey || Para registrar '+ usuariox +', ejecute en este canal (mensaje directo) $privatekey privatekey.'));
                               });
                           }
                           else{
                               bot.createMessage(channel,"<@!" + uid + ">" + 'there is no user to change, first register || no hay ningun usuario que cambiar, primero registrate ');
       
                           }
                       }
                   }
               });
                   }
  • To eliminate the user's password:
var regex9 = /(\$)+(delete)/;
var time = Math.floor(new Date().getTime() / 1000 );
if(msg.content.match(regex9)){
    var uid = msg.author.id;
    var channel = msg.channel.id;
con.query('UPDATE `voter`  SET `wifkey`="0" WHERE `userid`="'+uid+'"' , function (error, results, fields) {
    bot.createMessage(channel,"<@!" + uid + ">" + ' su peticion de eliminar la privatekey de su usuario se ha logrado exitosamente, lastima que ya no quieres pertenecer en este grupo, si deseas volver a registrarte solo vuelvele a enviar tu privatekey al bot || your request to delete the privatekey of your user has been successfully achieved, it hurts that you no longer want to belong in this group, if you want to register again just send your privatekey back to the bot');
});
}   

I'm going to add a plus to this, if we want to know how many users are registered, we would use this code:

var regex4 = /(\$)+(usuarios)/;
var time = Math.floor(new Date().getTime() / 1000 );
if(msg.content.match(regex4)){
    var channel = msg.channel.id;
    con.query('SELECT count(user) AS total FROM voter', function(err, result) {
        contx = result[0].total;
    bot.createMessage(channel, 'there are: '+ contx+ ' users <3');
    });
}

And this is the result

eee.png

dddd.png

I hope you have learned with this tutorial, the following tutorial will be dedicated to the votes !!!!
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:  

Thank you for your contribution. Below is our review:

  • Discord bots are certainly exciting to work with and quite useful.
  • You mentioned there were 3 items to be taught in the tutorial, yet you used points 1 and 2. Combining last 2 items under 1 point is confusing.
  • Your code had barely any comments, which makes it difficult to comprehend or maintain in the future
  • You did not explain your code quite efficiently to your readers. Explaining code properly would help readers learn better.
  • You have some English language issues in your content, try to improve those and re-read your post before submitting it.
  • I believe you had used a wrong variable usuariox in here which is not yet defined, the correct variable would be usuario. Why use confusing almost similar variable names? msg.author.getDMChannel().then(channel => channel.createMessage('to register '+usuariox +' please execute in this chanel (direct message) $privatekey yourprivatekey || para registrar '+ usuariox +', ejecute en este canal (mensaje directo) $privatekey privatekey para saber donde esta su privatekey , vea el video '));

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, @mcfarhat!

So far this week you've reviewed 2 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