Python Libraries: Simple... Display your Splinterlands DEC

avatar

image.png

In an attempt to write something ‘useful’ without stealing it from the internet I set about trying out the Splinterlands API for the first time.

There are scripts on GitHub that do a lot more than what I show you here, but lifting them won't teach you Python.

You need to write them from nothing and without looking if you want it all to sink in.


image.png
...'the output after running this script, it displays the data I am looking for and nothing else'...

I have SEVEN Splinterlands accounts that are DEC collectors. You read that correctly, it’s unrelated to tax collecting and DEC is one of the native Splinterlands tokens.

I realise this is unusual but can imagine some players/investors have more than a single account. To check quickly on the status of my accounts, I wanted to have a desktop shortcut I could click to reveal my balances.

It couldn’t be that hard surely?

Using the Splinterlands API was merely a call using a variable to pipe the data into.

image.png

Nice and easy but the URL variable held a lot more than just my DEC totals and I needed to suffix the call with my account. That’s what the + is for.

As there are SEVEN of them, it made sense to use of a List data structure and further down the script use a For loop to cycle through them.

image.png

I noted the data being filtered into the 'url' variable appeared to be formatted but occasionally contained strange characters.

Being intent on mastering this myself, I tried several ways to separate the data into something more readable and eventually came to the conclusion it was json data.

image.png

This did the trick and now I could interrogate it correctly. To utilise the json.loads method, python requires a couple of libraries to be accessible.

image.png

Simply add these at the top of your script.

Now I had some readable data to work with, I needed another loop with an embedded If statement within it to get at the DEC data.

image.png

data[‘player’] and data [‘balance’] were what I needed to display in some readable form. The issue was that my account names within the data['player'] variable were all of different lengths.

Simply printing them to the console was displaying it but not in the neat straight lines I wanted.

Some padding was needed and this is where this kind of complex-looking code comes into play.

image.png

The spaces variable holds several spaces (CHR$ 32 for ASCII buffs), and that number is 20 minus the length of the Splinterlands account name.

It does look a little cryptic but can be figured out if you stare long enough at it while drinking lots of coffee and occasionally pounding your head against the nearest wall.

image.png

The final line is something I am still getting used to with Python. Adding 3 x {} separated by a comma, with the next 3 elements dictates what will be within them.

Note the middle one contains the variable 'spaces' which is simply padding so then when the script is run, it looks nice and ordered.

I do intend to create a GitHub repository for these scripts. As I still haven’t done this, please feel free to copy and paste the entire script if you find it useful.

Replace my accounts with yours unless you simply want to spy on my DEC totals. The script could easily be modified to display much more than DEC, and that one line pipes a lot of data into the 'url' variable.

RedLine.png

SplinterlandsDECBalances.py

import json, requests

splinterlands_accounts = ["account1", "account2", "account3"]

print("----------------------------------")
print("Account               DEC Total")
print("----------------------------------")

for account in splinterlands_accounts:

    url = "https://api2.splinterlands.com/players/balances?username=" + account
    spldata = json.loads(requests.get(url).text)

    for data in spldata:
        if data["token"] == "DEC":
            spaces = " " * (20-len(data['player']))
            print("{} {} {}".format(data['player'], spaces, data['balance']))

RedLine.png

  • Earn currency while you play brewing virtual beer with CryptoBrewMaster
  • Earn currency while you play and become a global Rock Star with Rising Star


CurieCurator.jpg



0
0
0.000
34 comments
avatar

Thanks for writing this blog, the code run smoothly. Also, it was short and educational.

0
0
0.000
avatar

Short should make it more understandable. These long winding scripts have my head exploding.

0
0
0.000
avatar
(Edited)

This is why I mentioned it. I wanted to give it a 1up but because of leofinance and ctp tag I got confused to be honest so I skipped. I take tags seriously when it comes to 1up and it's not always crystal clear so arguments mostly end up hurting feelings of author then doing any good so i just skip.

0
0
0.000
avatar
(Edited)

It has been many years since I enjoyed playing with C++, Java and Postgree SQL. Then life and work and limited time took me away from programming.
I never had time to study Phyton and who knows Hive might be the right motivation to start studying Phyton.

There are scripts on GitHub that do a lot more than what I show you here, but lifting them won't teach you Python.

Great advice and I completely agree.
Writing the code is the only way to learn it.
@tipu curate

0
0
0.000
avatar

I struggle with Python, probably because I am don't use it daily. Even my own code.. I forget how it works.., but understanding it is the only way you will ever gain any knowledge. Lifting code is fine.., but it doesn't get you very far.

0
0
0.000
avatar

I recommend looking at Python 'fstrings'. They make for simpler formatting. Here's an example I came up with that pads out names and numbers. Easier to read I think:

x=[{'name':'rod','amt':3},{'name':'jane','amt':555},{'name':'freddy','amt':111}]
for i in x:
    print(f"{i['name']:20} {i['amt']:6}")

Output:

rod                       3
jane                    555
freddy                  111
0
0
0.000
avatar

More efficient for sure (1 line less of coding), but getting my head around it was tough. It does it for you! Here's the adjusted section of code:

image.png

image.png

Thanks for the lesson, I was never a master.., but can get by!

0
0
0.000
avatar

It's pretty powerful and generally quite readable. You can also align the numbers to the right. It's something I use all the time, but I don't know all the tricks.

0
0
0.000
avatar

Thanks for the insight, I'm not sure about the 'more readable' part but it's the way to go for sure. I always have to dig in and understand how things work.., having it simply work isn't enough.

0
0
0.000
avatar

It's something where you can quickly learn the basics and pick up further insight as you need it. You can get into really trying to optimise the amount of code, but that can compromise readability.

0
0
0.000
avatar

This is something I am struggling with.., given a variable name.. it works.. but suffixing the :20 to a literal string.. does not. I have tried several combinations.. which either gives me errors.. or prints the 20!

print(f'Account{:20} DEC Total')

Any ideas?

0
0
0.000
avatar

Try this. The part you are formatting has to be in {}. It can even be an expression. Anything outside the {} is output as-is.

print(f'{"Account":20} DEC Total')
0
0
0.000
avatar

Perfect and now working.. thanks!. So quotes can go inside the squiggles and are not interpreted as variable data if enclosed with quotes.. interesting. I couldn't find a single example of this on the net.

0
0
0.000
avatar

It can be expressions like this. Probably other ways to do it. Just need to use different quotes in the {} to those around the whole string.

for n in range(20,0,-1):
    print(f'{"*"*n:20} bottles of beer')
0
0
0.000
avatar

Dipping you toes in to learn something different, frustrating and rewarding, thanks for insight on what you been doing.

!BEER

0
0
0.000
avatar

I used to code as part of my work, but being out of work has not helped much. Python was new to me, but I have adjusted to it well.

0
0
0.000
avatar

Fiddled a couple of years with code, not Python though. Would need time and quiet to sit fathoming out which I have not had recently... 😇 Enjoy something different, learning new is never lost always put to good use.

0
0
0.000
avatar

Getting Python installed is the hardest bit, took me a while to get everything working!

0
0
0.000
avatar

You need to write them from nothing and without looking if you want it all to sink in.

That sounds like a good plan - but then, when would one find time to write???

This post has been manually curated by the VYB curation project

0
0
0.000
avatar

That sounds like a good plan - but then, when would one find time to write???

There's little point in doing anything unless you have a goal. Time.., that depends on your lifestyle and what's more important.

0
0
0.000
avatar

Thank you, This was pretty interesting to me. I need to break out my Rasp-Pi and give it a try one day. I am still wary about trying things on my everyday computer.

0
0
0.000
avatar

I am still wary about trying things on my everyday computer.

It will be fine, clear text script!

0
0
0.000
avatar

i started learning python, i want to do more with python.

0
0
0.000
avatar

Great content again my best author you are the best author i ever came across but that is by the way, you really explained this well the python should be a broad topic, I mean maybe you should do a podcast about it just a suggestion thanks for sharing.

0
0
0.000
avatar

At the end of the day, you keep producing the best content you can, engage and respond. The rest is outside of your control. Probably not an idea that is appealing to most... people want guarantees, along with instant gratification. Not gonna happen...

0
0
0.000
avatar

"In an attempt to write something ‘useful’ without stealing it from the internet I set about trying out the Splinterlands API for the first time."

Haaaaa haaaa haaaaa :))

It's a pleasure to read you, my friend!.... Thank you!!!!...

0
0
0.000
avatar

Coding!

And lots of hair pulling.

Equals bald coders lol.

0
0
0.000
avatar

Well, you piqued my interest!

This got me to install Python 3 and, using PIP to add the requests repository.

After all that I thought I would contribute by adding a total...

Altered the code as follows:

import json, requests

splinterlands_accounts = ["account1", "account2", "account3"]

print("----------------------------------")
print("Account DEC Total")
print("----------------------------------")

totalDEC = float("0")

for account in splinterlands_accounts:

url = "https://api2.splinterlands.com/players/balances?username=" + account
spldata = json.loads(requests.get(url).text)

for data in spldata:
    if data["token"] == "DEC":
        spaces = " " * (20-len(data['player']))
        print("{} {} {}".format(data['player'], spaces, data['balance']))
        totalDEC = totalDEC + float(data['balance'])

print("----------------------------------")
spaces = " " * (18-len(str(totalDEC)))
print("{} {} {}".format("Total DEC", spaces, str(totalDEC)))
print("----------------------------------")

0
0
0.000
avatar

Great, have a go at doing something else, and install the BEEM library.., then you can truly manipulate HIVE stuff.

0
0
0.000