🤖 TUTORIAL - Beginner friendly - Building bots With steem-js #2

in #utopian-io7 years ago (edited)

tut-2.jpg

This tutorial is part of a series on ‘How To Build Bot’s Using Steem-JS Open Source Library’ it aims to demonstrate practical applications for bots and demystify the code used to create them.

In part 1 we crated our first bot that auto-liked posts from a set list of users (out “friends list”). Please take that tutorial first as we will build on knowledge learned.

The completed bot code is here - I know some people find it easier to see everything in one block and follow along that way. ⬅️

Outline 📝

We will create an voting curation trail bot, our bot will automatically upvote any posts that our selected user also upvotes. This is the idea behind the popular tools like Steemauto

Requirements

  • A plain text editor (I use atom.io )
  • Your private posting key - This is found in your wallet on the permissions tab on steemit.com, click ‘show private key’ (remember to keep this safe). This is what allows the bot to vote for you

Difficulty

This tutorial is intended to be beginner friendly. (I appreciate feedback on the teaching level)

Learning Goals

  • familiarise ourself with the connection process to the steem-js API we used in the previous tutorial
  • Learn how to check when a ‘target’ user upvotes a post
  • Use knowledge on voting to also send a vote to that post

Step 1 - Setup 💻

For this tutorial our bot will run in the web browser, a more effective way to use this bot would be on the command-line but we’ll save that for another post.

Use this template to get started - This is a barebones file that has html, body, script tags and includes a CDN linked steem-js library. Download or copy the code into a .html file and open it in your browser. You’ll see the output in your browser console again like last time (refer to previous post if you can’t remember)

Next we’ll add the variables to store the information needed for this bot.

        // Tutorial 02 - curation trail bot
        const ACCOUNT_NAME = ''
        const ACCOUNT_KEY = ''
        const DELAY = 5000
        const TARGET_ACCOUNT = 'sambillingham'

We are storing 4 pieces of information as constants because they do not need to change when our app is running. ACCOUNT_NAME & ACCOUNT_KEY will be your steem username/posting-key. DELAY will be how long after our target we should vote in mili-seconds so 5000 is five seconds. TARGET_ACCOUNT is who we’re going to copy, so in this instance whenever user sambillingham votes, so will our bot.

Step 2 - Connect & watch 👀

Just like the previous tutorial we’re going to connect to steem-as and watch all transactions on the network.

    steem.api.setOptions({ url: 'wss://rpc.buildteam.io' });
    steem.api.streamTransactions('head’,(error, result) => {});

Let’s expand out the steem.api.streamTransactions function and see some results. Once again it’s easier to save the information from the result with a nice name like txType and TxData.

    steem.api.streamTransactions('head', function(err, result) {
       let txType = result.operations[0][0]
       let txData = result.operations[0][1]
            if(txType == 'vote') {
                console.log('vote')
        }
    }

Here we’re checking if the txType is equal to a vote, if it is we’ll just send it to the console.

Step 3 - Watch out Target 🎯

We’re only interested in one particular user the TARGET_USER so let’s narrow our data from anyone who votes to just votes from the target. if you change your output to see the txData you’ll see the output for a vote.

       if(txType == 'vote') {
            console.log(txData)
       }

Screen Shot 2018-01-14 at 09.36.52.png

From the Screenshot you can see we’re looking for the .voter information, so txData.voter will show us if the voter is our target or a different user. We’ll use the and syntax to allow us to check if the type is a vote and the voter is our target. && is the syntax in javascript to specify both of these must be true.

     if(txType == 'vote' && txData.voter == TARGET_ACCOUNT) {
           console.log(TARGET_ACCOUNT, ': has just voted')
     }

Step 3 - Copy Our Targets Vote 👍

We can use the same voting code we created in our previous tutorial except this time we’ll add custom voting weight.

previous code

    
      function sendVote(author, permlink){
        steem.broadcast.vote(ACCOUNT_KEY, ACCOUNT_NAME, author, permlink, 10000, function(err, result) {
                  console.log(result);
       });
     }

You can see we have the NAME/KEY for our bot along with author and permlink, but before we had the default vote of 10000 or in other words 100%. lets update that so we can copy what our target does. We’ll add an parameter (input data) to our function

            function sendVote(author, permlink, weight){
               steem.broadcast.vote(ACCOUNT_KEY, ACCOUNT_NAME, author, permlink, weight, function(err, result) {
           console.log(result);
         });
       } 

The final step is to combine out vote code into our streaming code so that it will send the same vote as our target. We pass the txData information into our send vote function and break it down into the relevant parts matching out function, author, permlink and weight.

    if(txType == 'vote' && txData.voter == TARGET_ACCOUNT) {
         console.log(TARGET_ACCOUNT, ': has just voted')    
         sendVote(txData.author, txData.permlink, txData.weight)
    }

Let’s also add and extra message to the sendVote function to show who we’ve voted for e.g

    console.log(`WE have just copied ${TARGET_ACCOUNT} and also upvoted ${author}`)

Backticks `, allow us to use template strings and input variables into a sentence. you’ll see a above you can use the syntax ${myinformation} to add variables into a string of text.

Our Bot is now finished and ready to make votes. This bot runs in the browser so for it to work we’ll have to keep our page open, we’ll look at making background tasks for bots in a future tutorial.

Here’s the full code 🤖

There’s still a lot more we can do with bots and the Steem API but I hope you find this interesting and useful. If you’re looking into building bots let me know or ask any questions below ✌️

Other Posts in This series



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Nice

Cool!

Hey Sam... I'm just going though these tutorials now... loved the first one but the links on this second one don't seem to work... the full code and the template links aren't happy.

New Links! (Accidentally moved the old ones.)
BASE TEMPLATE
FINAL CODE

Oops! Didn't think about the links when I moved the repo files around. Glad you liked the first one. let me know if I can help with anything when you're going through them.

Dude, can I just tell you how excellent these are? When this didn't work I actually skipped to Tutorial 8 because that was similar to what I wanted to do... and now I have a dice rolling bot up and running. These tutorials are so great, I actually can't thank you enough.

Haha, also, thanks for this repair... excited to go through it.

Honestly so glad to hear that! Thank you, I'm just glad people actually use them. Sometimes it feels like these posts mostly go into the void. Let me know if there anything else to add to the dice rolling bot that you're not sure on. I've got a few more tutorial ideas in the works too.

Yeah, Steem can very much feel like that... but I'm loving these.

I do have some questions, but I'll actually try and figure it out first. I ran into a heap of problems with my bot this morning, and managed to fix all the issues, even though I'm really just learning javascript from your tutorials.

If I get stuck I'll comment on your latest tutorial post... can't wait for the next one!

Thanks for sharing.

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Thanks for reviewing my tutorial! 💯

Good stuff once again man! I was thinking of writing a similar tutorial on how to do this using steem-python.

Thanks for stopping by again Amos. You should totally do it! Great to have examples using both libraries and I'm sure it would help people see the similarities and differences in both the languages and libraries.

I'm aiming to keep the concepts simple for now and will build up into more intelligent bots as people have a chance to pick up the basics. 👍

Thanks Sam for yet another great tutorial. Keep up the great work. As I am a JavaScript developer they are very helpful for me to build some stuff for Steemit in the near future.

Cheers.

Thanks Jo, glad I'm making things people find useful. I have a bunch more ideas for this bot series so will try to get another one out tomorrow. You should totally see what you can build for steemit, just let me know if
I can help 👊

Thanks for offering your help. I will come back to it ;)

👊

I always dream of having my own (bid)bot. I'm not technical enough though. Neither I have enough steem power. But I'm trying so hard to increase it. Once I am capable to do it I'll do it. But what do you think I should learn to do all technical stuffs on my own ? What skills should I have ? I just want want your thought on it.

hey it's totally possible to make your own bid bot, I have it inline as part of this series although it won't be as advanced as some of the bid bots (the tutorial would be too long). Should be tue or wed next week.

There are great tools for the steem blockchain in javascript and python. I would recommend to start learning either of those languages. Any programming will help because building something like a bit bot is more about concepts and problem-solving. Learning to figure out what needs to happen in what order then matching up the available tools to those steps.

You can learn a lot from trial and error, copy the finished code here and open it up in your browser. Try changing a name or changing 'vote' and see what breaks, then reset and try again.

Thanks, man. This is so fascinating. I was already planning to learn JavaScript and as you said it will help me in building bid bot, I got motivated. I didn't know that before. Gotta start it from the scratch. Thanks again.

@sambillingham, thanks for your awesome Guide!
This was exactly what I was looking for.
But I have a short question:

Is there a way to add multiple accounts?

I tried it a few different ways, but I keep getting errors, I tried too add the Accounts like this:

const ACCOUNT_NAME =[ 'name1', 'name2']
const ACCOUNT_KEY = ['key1', 'key2']

Hope you can help me solving this problem, gz @davsner !

Very nice tutorial series to get started building steem bots in simple and clear articles. I am liking it.

thanks for the support

Coin Marketplace

STEEM 0.20
TRX 0.25
JST 0.038
BTC 96483.87
ETH 3356.14
USDT 1.00
SBD 3.20