Code Monkey home page Code Monkey logo

steem-python's Introduction

A modern Piston fork

steem-python is a fork of the legendary Piston library by @xeroc.

It features a refactored codebase, JSON-RPC support, new types and transactions, full API coverage, and a handful of new features.

Installation

You can install steem-python with pip:

pip install -U git+git://github.com/Netherdrake/steem-python

Warning: This is NOT the official steem-python library. Use at own risk.

Documentation

Full documentation is available at http://steem.readthedocs.io

Example Uses

Here are a few example scripts that utilize steem-python.

Syncing Blockchain to a Flat File

Here is a relatively simple script built on top of steem-python that will let you sync STEEM blockchain into a simple file. You can run this script as many times as you like, and it will continue from the last block it synced.

import json
import os
from contextlib import suppress
from steem.blockchain import Blockchain


def get_last_line(filename):
    if os.path.isfile(filename):
        with open(filename, 'rb') as f:
            f.seek(-2, 2)
            while f.read(1) != b"\n":
                f.seek(-2, 1)
            return f.readline()


def get_previous_block_num(block):
    if not block:
        return -1

    if type(block) == bytes:
        block = block.decode('utf-8')

    if type(block) == str:
        block = json.loads(block)

    return int(block['previous'][:8], base=16)


def run(filename):
    b = Blockchain()
    # automatically resume from where we left off
    # previous + last + 1
    start_block = get_previous_block_num(get_last_line(filename)) + 2
    with open(filename, 'a+') as file:
        for block in b.stream_from(start_block=start_block, full_blocks=True):
            file.write(json.dumps(block, sort_keys=True) + '\n')


if __name__ == '__main__':
    output_file = '/home/user/Downloads/steem.blockchain.json'
    with suppress(KeyboardInterrupt):
        run(output_file)

To see how many blocks we currently have, we can simply perform a line count.

wc -l steem.blockchain.json

We can also inspect an arbitrary block, and pretty-print it. Replace 10000 with desired block_number + 1.

sed '10000q;d' steem.blockchain.json | python -m json.tool

Witness Killswitch

Occasionally things go wrong: software crashes, servers go down... One of the main roles for STEEM witnesses is to reliably mint blocks. This script acts as a kill-switch to protect the network from missed blocks and prevents embarrassment when things go totally wrong.

import time
from steem import Steem

steem = Steem()

# variables
disable_after = 10  # disable witness after 10 blocks are missed
witness_name = 'furion'
witness_url = "https://steemit.com/steemit/@furion/power-down-no-more"
witness_props = {
    "account_creation_fee": "0.500 STEEM",
    "maximum_block_size": 65536,
    "sbd_interest_rate": 15,
}


def total_missed():
    return steem.get_witness_by_account(witness_name)['total_missed']


if __name__ == '__main__':
    treshold = total_missed() + disable_after
    while True:
        if total_missed() > treshold:
            tx = steem.commit.witness_update(
                signing_key=None,
                url=witness_url,
                props=witness_props,
                account=witness_name)

            print("Witness %s Disabled!" % witness_name)
            quit(0)

        time.sleep(60)

Batching Operations

Most of the time each transaction contains only one operation (for example, an upvote, a transfer or a new post). We can however cram multiple operations in a single transaction, to achieve better efficiency and size reduction.

This script will also teach us how to create and sign transactions ourselves.

from steem.transactionbuilder import TransactionBuilder
from steembase import operations

# lets create 3 transfers, to 3 different people
transfers = [
    {
        'from': 'richguy',
        'to': 'recipient1',
        'amount': '0.001 STEEM',
        'memo': 'Test Transfer 1'
    },
    {
        'from': 'richguy',
        'to': 'recipient2',
        'amount': '0.002 STEEM',
        'memo': 'Test Transfer 2'
    },
    {
        'from': 'richguy',
        'to': 'recipient3',
        'amount': '0.003 STEEM',
        'memo': 'Test Transfer 3'
    }

]

# now we can construct the transaction
# we will set no_broadcast to True because
# we don't want to really send funds, just testing.
tb = TransactionBuilder(no_broadcast=True)

# lets serialize our transfers into a format Steem can understand
operations = [operations.Transfer(**x) for x in transfers]

# tell TransactionBuilder to use our serialized transfers
tb.appendOps(operations)

# we need to tell TransactionBuilder about
# everyone who needs to sign the transaction.
# since all payments are made from `richguy`,
# we just need to do this once
tb.appendSigner('richguy', 'active')

# sign the transaction
tb.sign()

# broadcast the transaction (publish to steem)
# since we specified no_broadcast=True earlier
# this method won't actually do anything
tx = tb.broadcast()

Simple Voting Bot

Here is a simple bot that will reciprocate by upvoting all new posts that mention us. Make sure to set whoami to your Steem username before running.

from contextlib import suppress

from steem.blockchain import Blockchain
from steem.post import Post


def run():
    # upvote posts with 30% weight
    upvote_pct = 30
    whoami = 'my-steem-username'

    # stream comments as they are published on the blockchain
    # turn them into convenient Post objects while we're at it
    b = Blockchain()
    stream = map(Post, b.stream(filter_by=['comment']))

    for post in stream:
        if post.json_metadata:
            mentions = post.json_metadata.get('users', [])

            # if post mentions more than 10 people its likely spam
            if mentions and len(mentions) < 10:
                post.upvote(weight=upvote_pct, voter=whoami)

if __name__ == '__main__':
    with suppress(KeyboardInterrupt):
        run()

steem-python's People

Contributors

biophil avatar fxnormaluser avatar holgern avatar john-g-g avatar maxpatternman avatar metaperl avatar netherdrake avatar sneak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

steem-python's Issues

Q: API to submit blog post?

Hi, is there an example on how to use the API to submit a blog post? I've been searching the docs but can't seem to find one.

$ pip install -U steem produces following error, Any solutions?

$python3.6 -m pip install steem
Collecting steem
Using cached steem-0.18.103.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "/tmp/pip-build-9i5v1kel/steem/setup.py", line 8, in
import package_meta # this is a simple tool for loading metadata from Pipfile and other places
File "/tmp/pip-build-9i5v1kel/steem/package_meta.py", line 10, in
from setuptools.config import read_configuration
ModuleNotFoundError: No module named 'setuptools.config'
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
from apport.fileutils import likely_packaged, get_recent_crashes
File "/usr/lib/python3/dist-packages/apport/init.py", line 5, in
from apport.report import Report
File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in
import apport.fileutils
File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in
from apport.packaging_impl import impl as packaging
File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in
import apt
File "/usr/lib/python3/dist-packages/apt/init.py", line 23, in
import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/tmp/pip-build-9i5v1kel/steem/setup.py", line 8, in <module>
    import package_meta # this is a simple tool for loading metadata from Pipfile and other places
  File "/tmp/pip-build-9i5v1kel/steem/package_meta.py", line 10, in <module>
    from setuptools.config import read_configuration
ModuleNotFoundError: No module named 'setuptools.config'

----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-9i5v1kel/steem/

ContextualVersionConflict

jared@debian:~$ steempy addaccount
Traceback (most recent call last):
File "/home/jared/anaconda3/bin/steempy", line 7, in
steem.cli.legacy()
File "/home/jared/anaconda3/lib/python3.6/site-packages/steem/cli.py", line 83, in legacy
version=pkg_resources.require("steem")[0].version
File "/home/jared/anaconda3/lib/python3.6/site-packages/pkg_resources/init.py", line 984, in require
needed = self.resolve(parse_requirements(requirements))
File "/home/jared/anaconda3/lib/python3.6/site-packages/pkg_resources/init.py", line 875, in resolve
raise VersionConflict(dist, req).with_context(dependent_req)
pkg_resources.ContextualVersionConflict: (toml 0.9.3 (/home/jared/anaconda3/lib/python3.6/site-packages), Requirement.parse('toml==0.9.3.1'), {'steem'})

What error message is this? How can I solve this problem?

root@ubuntu:~# steempy
Traceback (most recent call last):
File "/usr/local/bin/steempy", line 7, in
from steem.cli import legacy
File "/usr/local/lib/python3.5/dist-packages/steem/init.py", line 2, in
from .steem import Steem
File "/usr/local/lib/python3.5/dist-packages/steem/steem.py", line 1, in
from .commit import Commit
File "/usr/local/lib/python3.5/dist-packages/steem/commit.py", line 20, in
from .account import Account
File "/usr/local/lib/python3.5/dist-packages/steem/account.py", line 8, in
from funcy.simple_funcs import rpartial
ImportError: No module named 'funcy.simple_funcs'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.