TUTORIAL - Beginner - Build your own Steem Upvote Bot - JavaScript - Part 3

in #utopian-io7 years ago (edited)

wallpaper_part3.png

What Will I Learn?

In this third tutorial we will finally use a JSON config file, we will only allow upvotes with an exact amount and refund the others.

  • Understand and use config files correctly
  • Refund transactions
  • Read the transferred amount out of the transaction data

Requirements

Have a basic understanding of JavaScript

  • Read my last parts (Click here)
  • Have a TextEditor (e.g Atom.io)
  • A working brain and some time

Difficulty

  • Basic

Tutorial Contents

The Config File

What is a config file and what is JSON ? Before we continue developing our upvote bot we will first create a JSON Config file.

Config File
A config file is used to store parameters and the initial parameters for out bot, also it is a useful way to define specific variables on one place. For example we could store our private posting key in a config file, after that we can use the key everywhere in our code via the config file. If the Key changes we only need to edit ONE place instead of everywhere we used the key.

JSON
JavaScript Object Notation (JSON) is a lightweight data format. It is easy to read and write for humans and easy to parse and generate for machines. JSON is complete language independent and is perfect for creating config files.

First create a config file named config.json inside of your projects directory and add following content
Screen Shot 2018-01-23 at 15.41.55.png

Inside of your index.js add and change following code:
1 - Add to the beginning

const fs = require("fs");
var config = JSON.parse(fs.readFileSync("config.json"));

2 - Change following lines:

...
steem.api.setOptions({ url: config.steem_node });
...
steem.api.getAccounts([config.account_name], function (err, result) {
...
steem.broadcast.vote(config.private_posting_key, account.name, vote.author, vote.permlink, 10000, function (err, result) {

Now it is very easy for use to change the settings of our bot (e.g change the steem-account for the bot)

Only allow correct transaction amounts

Next we will check if a transactions was sended with a valid amount of SBD or STEEM. To do so change your code from

if (op[0] == 'transfer' && op[1].to == account.name) {
       if (validUrl.isUri(op[1].memo)) {
            checkValidMemo(op);
       }
}

To:
Screen Shot 2018-01-23 at 15.50.55.png

Let's break it down:

var amount = op[1].amount;
var currency = amount.substr(amount.indexOf(' ') + 1);
amount = parseFloat(amount);

First we are reading from the transaction data A) the amount which was send and B) the currency which was send - we are using the substring and indexOf function here. Why ? - Because normally the amount is send for example like this: '1.00 SBD'. So first we get the Index of the whitespace and create a substring starting and the next index after the substring. We will get SBD from this call.

After this we parse the amount to a valid float value.

if(config.accepted_currencies && config.accepted_currencies.indexOf(currency) < 0) {
                        console.log("INVALID CURRENCY SENT - SHOULD REFUND");
                        refund(op[1].from, op[1].amount);
                        return;
} else if(amount < config.min_bid) {
                        console.log("BID TO LOW - SHOULD REFUND");
                        refund(op[1].from, op[1].amount);
                        return;
} else if (amount > config.max_bid) {
                        console.log("BID TO HIGH - SHOULD REFUND");
                        refund(op[1].from, op[1].amount);
                        return;
}

Here we have our exit-early clauses. Exit early means we first check all possible clauses which we DO NOT want. If they appear we want to EXIT our code EARLY before doing the real stuff our program should do.

What we check are A) Is the currency a valid currency we accept ? B) Is the amount send higher than our minimum amount ? C) Is the amount send lower than our maximal amount?
If all three succeed our bot will check the post if it is a valid post and so on...
If NOT our bot stops... But wait we still have the amount on our account balance - we should refund it !

refund(op[1].from, op[1].amount);

Calls our refund method , which we will create in a second, with following parameters:
Who sended the amount, the amount.

Refund funcion

Screen Shot 2018-01-23 at 15.43.42.png

steem.broadcast.transfer(config.private_active_key, config.account_name, sender, amount, '', function (err, response) {}

Takes as parameters your private active key, the sender account, the receiver account, the amount, the memo field.

Testing ?

Beware you should only test this with 2 different accounts (the best would be to now use a bot account!) - why ? Well when you try to refund to your own account it will get stuck in a refund loop!

What's up next ?

In the next part we will learn:

  • Using refund memo messages from our config file
  • Save the last checked transaction, so our bot does not always check the same transactions
  • Create default values for our config
  • Check post age

Source Code

Curriculum



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

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

Hey @moonrise I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Hi @moonrise
Really interested in getting a bot going, more for fun than anything.
I went through the 3 parts, and everything was working right to the last part and is now broken.
I am getting this error. Any idea what it might mean?
Great post by the way. Thank you.

Hmmm... not letting me post a picture.
The error is
=========
index.js:130
SyntaxError: missing ) after argument list
at createScript (vm.js:80:10)

A whole bunch more like that. Perhaps I can send a screen capture to you via steemit, rather than here.
Thanks
@garyph

Do you have discord ? - My name is moonrise.

Click here - this part of the code in incorrect, I realized it sadly after posting 2-3 more parts. !results should be !response. Maybe this fixes your error.

Furthermore does this error mean a ( or { is opened but never closed, maybe a typo in your code ?

Thanks for your response. I may have found something else but I will keep this post in mind.
thanks

Hi @garyph would you be open to share the other code you found?

Hi @moonrise , Thankyou so much for all your sharing! I've followed your previous tutorials closely and I've had everything working until now. I'm finding a problem when I add the last bit of code that is for the refund. I get the following error message when I run it.. Please can you double-check the code for the refund part is correct.

I've isolate the error to being in the following part, if I delete this section the bot functions without any errors:
function refund(sender, amount) {
steem.broadcast.transfer(config.private_active_key, config.account_name, sender, amount, '', function (err, response) {
if (err || !result) {
console.log("Refund failed ! For: " + sender);
}
}
});
}

For anyone who is late to the party, like I am, you may find some links broken. You can find some parts of this tutorial by just adjusting the number in the url.

The error in the code, that is mentioned by some is this

function refund(sender, amount) {
      steem.broadcast.transfer(config.private_active_key, config.account_name, sender, amount, '', function (err, response) {
   if (err || !result) {
       console.log("Refund failed ! For: " + sender);
    }
  }
});
}

the callback function uses function (err, response). So the values you want to check are err and response.
The checking code however cheks for err and result (which is an understandable mistake when writing code)

So change
if (err || !result) {
to
if (err || !response) {

and you should be fine.

Coin Marketplace

STEEM 0.19
TRX 0.17
JST 0.033
BTC 64136.37
ETH 2755.37
USDT 1.00
SBD 2.68