Python Libraries: Simple... Display your Splinterlands DEC

in STEMGeeks2 years ago

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

Sort:  

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

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!

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.

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.

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.

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?

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')

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

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.

Loading...

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.

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

It will be fine, clear text script!


~~~ embed:1582036125392044034 twitter metadata:MTI5NDM0ODMzMzg0NzQwMDQ1NXx8aHR0cHM6Ly90d2l0dGVyLmNvbS8xMjk0MzQ4MzMzODQ3NDAwNDU1L3N0YXR1cy8xNTgyMDM2MTI1MzkyMDQ0MDM0fA== ~~~

The rewards earned on this comment will go directly to the people( @joydukeson, @fabian98, @jlinaresp ) sharing the post on Twitter as long as they are registered with @poshtoken. Sign up at https://hiveposh.com.

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

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

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.

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

!BEER

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.

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.

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

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

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.

Coding!

And lots of hair pulling.

Equals bald coders lol.

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...

"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!!!!...

Your content has been voted as a part of Encouragement program. Keep up the good work!

Use Ecency daily to boost your growth on platform!

Support Ecency
Vote for new Proposal
Delegate HP and earn more

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

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.