Exemple #1
0
def send_a_tip(author):
    steem = Steem(wif=active_key)
    steem.transfer(author,
                   2.0,
                   "SBD",
                   memo="I love your blog. Here is a small gift for you.",
                   account=account)
Exemple #2
0
def curation_delay_vote(wif_key, account_to_vote_with, identifier,
                        time_to_wait):
    print(time_to_wait)
    time.sleep(time_to_wait)
    steem = Steem(wif=wif_key)
    steem.vote(identifier, 100, account_to_vote_with)
    print("====> Upvoted")
def multifeed(puppet, puppet_active_key, puppet_posting_key):
    #lock.acquire()
    #upvote_history = []
    print("{} : Waiting for new posts by {}".format(puppet, my_subscriptions))
    steem = Steem(wif=puppet_posting_key)
    for comment in steem.stream_comments():

        if comment.author in my_subscriptions:
            #if len(comment.title) > 0:

                if comment.identifier in upvote_history:
                    #upvote_history = []
                    continue

                print("New post by @{} {}".format(comment.author, url_builder(comment)))

                try:
                    print("Voting from {} account".format(puppet))
                    comment.vote(100, puppet)
                    print("====> Upvoted")
                    upvote_history.append(comment.identifier)
                except BroadcastingError as e:
                    print("Upvoting failed...")
                    print("We have probably reached the upvote rate limit. {}".format(e))
                    print(str(e))
                except Exception as er:
                    print("Error:{}".format(e))
                #lock.release()
                return print("Voted!")
Exemple #4
0
    def create(self, serializer):
        # TODO Зарефатороить или вынести в отдельный модуль
        # методы создания постов и комментариев
        tx = self.request.data.get('tx')
        updater = BaseUpdater(self.request.data.get('blockchain'))

        rpc = Steem(updater.blockchain.wss)

        try:
            r = rpc.broadcast(tx)
        except RPCError as e:
            operation = tx['operations'][0][1]
            operation['body'] = operation['body'][:100]

            logger.warning('%s: %s' % (e, pprint.pformat(operation)))

            return Response(str(e), status.HTTP_400_BAD_REQUEST)

        operation = r['operations'][0][1]

        p = rpc.get_content({
            'permlink': operation['permlink'],
            'author': operation['author']
        })

        post = updater.upgrade_post(p)

        return Response(self.serializer_action_classes['list'](post).data)
Exemple #5
0
def vote(puppet, wif_key):
    steem = Steem(wif=wif_key)
    print("{} : Waiting for new posts by {}".format(puppet, my_subscriptions))
    for c in steem.stream_comments():
        if c.author in my_subscriptions:
            print(c.author)
            if c.identifier in upvote_history:
                continue
            print("New post by @{} {}".format(c.author, url_builder(c)))
            try:
                #print("Voting from {} account".format(puppet))
                #c.vote(100, puppet)
                #print("====> Upvoted")
                #upvote_history.append(c.identifier)
                print("Voting from {} account".format(puppet))
                curation_time = random.randint(840, 1020)
                print(c.identifier)
                t = threading.Thread(target=curation_delay_vote,
                                     args=(wif_key, puppet, c.identifier,
                                           curation_time))
                t.start()
                upvote_history.append(c.identifier)
            except Exception as e:
                print("Upvoting failed...")
                print("We have probably reached the upvote rate limit.")
                print(str(e))
Exemple #6
0
def multifeed(puppet, puppet_active_key, puppet_posting_key):
    #lock.acquire()
    #upvote_history = []
    print("{} : Waiting for new posts by {}".format(puppet, my_subscriptions))
    steem = Steem(wif=puppet_posting_key)
    for comment in steem.stream_comments():

        if comment.author in my_subscriptions:
            #if len(comment.title) > 0:

            if comment.identifier in upvote_history:
                #upvote_history = []
                continue

            print("New post by @{} {}".format(comment.author,
                                              url_builder(comment)))

            try:
                print("Voting from {} account".format(puppet))
                comment.vote(100, puppet)
                print("====> Upvoted")
                upvote_history.append(comment.identifier)
            except BroadcastingError as e:
                print("Upvoting failed...")
                print("We have probably reached the upvote rate limit. {}".
                      format(e))
                print(str(e))
            except Exception as er:
                print("Error:{}".format(e))
            #lock.release()
            return print("Voted!")
Exemple #7
0
 def default(self, **kwargs):
     """
     This will try local node first, and automatically fallback to public nodes.
     """
     if self._default:
         return self._default
     nodes = self.find_local_nodes() + self._nodes['public']
     return Steem(node=nodes, apis=self._apis, **kwargs)
Exemple #8
0
    def create(self, serializer):
        tx = self.request.data.get('tx')
        updater = BaseUpdater(self.request.data.get('blockchain'))

        rpc = Steem(updater.blockchain.wss)

        try:
            r = rpc.broadcast(tx)
        except RPCError as e:
            logger.warning('%s: %s' %
                           (e, pprint.pformat(tx['operations'][0][1])))
            return Response(str(e), status.HTTP_400_BAD_REQUEST)

        operation = r['operations'][0][1]

        comm = rpc.get_content({
            'permlink': operation['permlink'],
            'author': operation['author']
        })

        page = None

        author = updater.get_author(comm.parent_author)

        if Page.objects.filter(permlink=comm.parent_permlink).exists():
            # Если это коммект к посту
            page = Page.objects.get(author=author,
                                    permlink=comm.parent_permlink)
        else:
            parent_comm = Comment.objects.get(author=author,
                                              permlink=comm.parent_permlink)

        if page is not None:
            comment = updater.get_comment_ins(comm, page, parent=None)
        else:
            comment = updater.get_comment_ins(comm,
                                              parent_comm.page,
                                              parent=parent_comm)

        comment.save()

        return Response(self.serializer_class(comment).data)
Exemple #9
0
def run():
    parser = SafeConfigParser()
    parser.read('config.ini')

    nodes = parser.get('steem', 'nodes')
    wif = parser.get('steem', 'wif')

    steem = Steem(node=nodes, wif=wif)

    host_name = parser.get('mongodb', 'host_name')
    db_name = parser.get('mongodb', 'db_name')

    mongo_steem = MongoSteem(steem, host_name=host_name, db_name=db_name)
    mongo_steem.stream_to_mongo()
Exemple #10
0
def feed():
    print("Waiting for new posts by %s\n" % my_subscriptions)
    steem = Steem(wif=posting_key)
    for comment in steem.stream_comments():

        if comment.author in my_subscriptions:
            # Comments don't have titles. This is how we can know if we have a post or a comment.
            if len(comment.title) > 0:

                # check if we already upvoted this. Sometimes the feed will give duplicates.
                if comment.identifier in upvote_history:
                    continue

                print("New post by @%s %s" % (comment.author, url_builder(comment)))

                try:
                    comment.vote(100, account)
                    print("====> Upvoted")
                    upvote_history.append(comment.identifier)
                except BroadcastingError as e:
                    print("Upvoting failed...")
                    print("We have probably reached the upvote rate limit.")
                    print(str(e))
Exemple #11
0
def feed():
    print("Waiting for new posts by %s\n" % my_subscriptions)
    steem = Steem(wif=posting_key)
    for comment in steem.stream_comments():

        if comment.author in my_subscriptions:
            # Comments don't have titles. This is how we can know if we have a post or a comment.
            if len(comment.title) > 0:

                # check if we already upvoted this. Sometimes the feed will give duplicates.
                if comment.identifier in upvote_history:
                    continue

                print("New post by @%s %s" %
                      (comment.author, url_builder(comment)))

                try:
                    comment.vote(100, account)
                    print("====> Upvoted")
                    upvote_history.append(comment.identifier)
                except BroadcastingError as e:
                    print("Upvoting failed...")
                    print("We have probably reached the upvote rate limit.")
                    print(str(e))
def selectnode(NodeNumber):
        #Try the websocket, if it fails then print fail and try another websocket
        try:
                webs.connect(Node[NodeNumber]) 
                print('connected to node:' + Node[NodeNumber])
        except Exception:
                print(Exception)
                NodeNumber=NodeNumber+1
                selectnode(NodeNumber)

#Make sure Nodenumber doesn't exceed number of nodes
        if NodeNumber > (len(Node)-1):
                NodeNumber=0 

        steem = Steem(wif=steemPostingKey,node=Node[NodeNumber])
        
        return NodeNumber
Exemple #13
0
 def __init__(self,
              steem=None,
              post_miner=None,
              steem_voter=None,
              vote_limit=11,
              run_hours=24):
     if steem is None:
         steem = Steem(node=STEEMIT_WSS_NODES, wif=WIF)
     if mongo_steem is None:
         mongo_steem = MongoSteem(steem=steem)
     if not post_miner:
         post_miner = PostMiner(mongo_steem=mongo_steem)
     if not steem_voter:
         steem_voter = SteemVoter(steem=steem)
     self.post_miner = post_miner
     self.steem_voter = steem_voter
     self.vote_limit = vote_limit
     self.end_time = datetime.datetime.now() + datetime.timedelta(
         hours=run_hours)
Exemple #14
0
    def handle(self, *args, **options):
        settings.LOCALE = {'golos': 'ru', 'steemit': 'en'}[options['bc']]

        updater = BaseUpdater()
        steem = Steem(updater.blockchain.wss)

        last_block = options['block_num'] or get_block(steem, options['bc'])

        logger.info('Parse from %s block' % last_block)

        types = {
            'vote': updater.vote,
            'comment': updater.comment,
        }

        for op in Blockchain(steem,
                             mode="irreversible").stream(['vote', 'comment'],
                                                         start=last_block):
            to_do = types.get(op['type'])

            try:
                # TODO запилить асинихронность
                # pool.apply_async(to_do, [op])

                to_do(op)
            except InterfaceError:
                # При 2х одновременно запущенных блокчейнах
                # TODO Сделать одним прощессом все блокчейны
                db.connection.close()
                to_do(op)
            except KeyboardInterrupt:
                break
            except:
                logger.exception('Handle op err: %s' % pprint.pformat(op))

            block_num = int(op['block_num'])

            if last_block < block_num:
                last_block = block_num
                redis.set('%s_last_block' % options['bc'], last_block)
Exemple #15
0
def run():
    parser = SafeConfigParser()
    parser.read('config.ini')

    nodes = parser.get('steem', 'nodes')
    wif = parser.get('steem', 'wif')

    steem = Steem(node=nodes, wif=wif)

    host_name = parser.get('mongodb', 'host_name')
    db_name = parser.get('mongodb', 'db_name')

    mongo_steem = MongoSteem(steem, host_name=host_name, db_name=db_name)

    category = parser.get('miner', 'category')
    expiration_minutes = parser.get('miner', 'expiration_minutes')
    sleep_time = parser.get('miner', 'sleep_time')

    post_miner = PostMiner(
        mongo_steem,
        category=category,
        expiration_minutes=expiration_minutes,
        sleep_time=sleep_time)

    voter = parser.get('voter', 'voter')
    steem_voter = SteemVoter(steem=steem, voter=voter)

    vote_limit = parser.get('curator', 'vote_limit')
    run_hours = parser.get('curator', 'run_hours')

    curator = SteemCurator(
        steem=steem,
        post_minter=post_miner,
        steem_voter=steem_voter,
        vote_limit=vote_limit,
        run_hours=run_hours,
    )

    curator.run()
Exemple #16
0
# grab config vars
percentChanceToPost = int(os.environ.get('percentChanceToPost'))
numPostsToConsider = int(os.environ.get('numPostsToConsider'))
voteWeight = int(os.environ.get('voteWeight'))
steemPostingKey = os.environ.get('steemPostingKey')
steemAccountName = os.environ.get('steemAccountName')

# [percentChanceToPost] chance to proceed past this block
i = randint(1, 100)
if i > percentChanceToPost:
    print('[{:%Y-%m-%d, %H:%M:%S}] No action (failed random roll {}>{})\n'.
          format(datetime.datetime.now(), i, percentChanceToPost))
    sys.exit(1)

# initialize steem object
steem = Steem(wif=steemPostingKey)

# use piston to set default voter and author
subprocess.call(['piston', 'set', 'default_voter', steemAccountName])
subprocess.call(['piston', 'set', 'default_author', steemAccountName])

# upvote random post from the most recent [numPostsToConsider]
posts = steem.get_posts(limit=numPostsToConsider, sort='created')
postId = randint(0, numPostsToConsider - 1)

try:
    steem.vote(posts[postId]["identifier"], voteWeight)
except:
    print('[{:%Y-%m-%d, %H:%M:%S}] Vote failed: {}\n'.format(
        datetime.datetime.now(),
        sys.exc_info()[0]))
Exemple #17
0
# storage.put_container('posts', headers={'X-Container-Read': '.r:*'})
# Page.objects.filter(position__isnull=False, position_text__isnull=False).update(has_point=True)
#from itertools import chain
#from apps.pages.models import Page

# Получить все теги
#for tag in set(t for t in chain.from_iterable([i.meta['tags'] for i in Page.objects.filter(meta__tags__isnull=False)])):
#    print(tag)

from piston.steem import Steem

s = Steem('wss://steemd.steemit.com')

p = s.get_content({'author': 'acro999', 'permlink': '1'})
print(p.export())

exit()
Exemple #18
0
import json
from time import time
import traceback, logging
from piston.steem import (Steem, BroadcastingError)

config = json.load(open('config.json'))
creator = config["registory"]
wif = config["wif"]
steem = Steem(node='ws://127.0.0.1:8090', nobroadcast=False, wif=wif)

transfer_list = json.load(open('./ico_final.json'))
logs = []

print("[+] Started golos power transfer operations")
try:
    for index, tx in enumerate(transfer_list):
        try:
            transfer_log = steem.transfer_to_vesting(account=creator,
                                                     amount=tx['amount'],
                                                     to=tx['account'])
            logs.append(transfer_log)
            print("[+] <{0}> Transfered {1} to {2}".format(
                index + 1, tx['amount'], tx['account']))
        except BroadcastingError:
            print("[-] <{0}> Didn't transferred {1} to {2}".format(
                index + 1, tx['amount'], tx['account']))
            pass
except KeyboardInterrupt as e:
    print("[!] Raised keyboard interrupt...")
    raise
except Exception as e:
from piston.steem import Post
import os
import json
import re
import html2text
import requests
from itertools import islice
import difflib
import collections
from collections import OrderedDict
import random

account = 'ChangThisToYourSteemitUsername'
author = 'ChangThisToYourSteemitUsername'
wif = '5YourPostingKeyGoesHere12345678901234567890'
steem = Steem(nobroadcast=False, wif=wif)

#initialise lists to store snippets of the content
captureContentInAList = []
captureContentInTheFinalList = []

percentageDifferenceFormatted = ''
percentageRequired = 0.5
captureContentSnippet = ''
stillTheSamePoster = ''
yacySearchResultDescription = ''
link = ''
limit = 4
theContent= ''
mainLoop = 0
stopLookingForContent = 0
Exemple #20
0
import time
from piston.steem import Steem
import os
import json

steem = Steem(wif=os.environ["WIF"])
print ("login OK")
authors = json.loads(os.environ["AUTHORS"])
print ("checking authors OK")
for c in steem.stream_comments(mode="head"):
     if c["author"] in authors and c.identifier == c.openingPostIdentifier:
        try:
            time.sleep(1000)
            print(c.upvote())
        except:
            print ("something went wrong, your vote was NOT casted")

Exemple #21
0
from piston.steem import Steem
import os
import json
import sendgrid
steem = Steem()
sg = sendgrid.SendGridClient(
    os.environ['SENDGRID_USERNAME'],
    os.environ['SENDGRID_PASSWORD']
)
message = sendgrid.Mail()
addresses = {"xeroc": "*****@*****.**"}
# addresses = os.environ["ADDRESSES"]
for c in steem.stream_comments():
    for user in addresses.keys():
        if "@%s" % user in c["body"]:
            message.add_to(addresses[user])
            message.set_subject('Notification on Steem')
            message.set_text(
                "You have been messaged by %s " % (c["author"]) +
                "in the post @%s/%s" % (c["author"], c["permlink"]) +
                "\n\n" +
                "You can read the post on Steemit.com:\n" +
                "http://steemit.com/%s/%s#@%s/%s"
                % (c["category"],
                    c["openingPostIdentifier"],
                    c["author"], c["permlink"])
            )
            message.set_from('notify@steem')
            status, msg = sg.send(message)
            print("\nMessage sent!\n")
Exemple #22
0
 def public(self, **kwargs):
     return Steem(node=self._nodes['public'], apis=self._apis, **kwargs)
Exemple #23
0
import time
import sys

from piston.steem import Steem
from piston.utils import sanitizePermlink
from transliterate import translit

args = sys.argv

steem = Steem(wif=args[2]) #постинг в ноду прописанную в библиотеке по умолчанию
# steem = Steem(node="wss://ws.golos.io", wif=args[2]) #можно в явном виде прописать ноду для постинга в Голос

title = args[3]
permlink = sanitizePermlink(translit(title, 'ru', reversed=True) + '-' + str(int(time.time())))

# TODO добавлять в пост url, дату публикации и тэги исходного поста в ЖЖ

steem.post(title=title, permlink=permlink, body=args[4], author=args[1], tags=["from-lj"])
Exemple #24
0
from piston.steem import Steem
import time
from piston.post import Post
import os
import json

steem = Steem(wif="private key here")
tags = ["introduction", "introduceyourself", "introducemyself"]
past_authors = []

for p in steem.stream_comments():
    for x in tags:
        try:
            if x in p["tags"] and p.is_opening_post(
            ) and p["author"] not in past_authors:
                print(p.get_comments())
                print(p["author"])
                post = p.reply(body="message here", author="username here")
                p.upvote(weight=+0.01, voter="username here")
                print(post)
                past_authors.append(post['operations'][0][1]['parent_author'])
                time.sleep(20)
                print(past_authors)

        except:
            print("Failed to comment on post.")
from piston.steem import Steem
import os
import json
import sendgrid
steem = Steem()
sg = sendgrid.SendGridClient(os.environ['SENDGRID_USERNAME'],
                             os.environ['SENDGRID_PASSWORD'])
message = sendgrid.Mail()
addresses = {"xeroc": "*****@*****.**"}
# addresses = os.environ["ADDRESSES"]
for c in steem.stream_comments():
    for user in addresses.keys():
        if "@%s" % user in c["body"]:
            message.add_to(addresses[user])
            message.set_subject('Notification on Steem')
            message.set_text("You have been messaged by %s " % (c["author"]) +
                             "in the post @%s/%s" %
                             (c["author"], c["permlink"]) + "\n\n" +
                             "You can read the post on Steemit.com:\n" +
                             "http://steemit.com/%s/%s#@%s/%s" %
                             (c["category"], c["openingPostIdentifier"],
                              c["author"], c["permlink"]))
            message.set_from('notify@steem')
            status, msg = sg.send(message)
            print("\nMessage sent!\n")
Exemple #26
0
import os
import sys
import time
from piston.steem import Steem
from pprint import pprint
from steemtools.experimental import Transactions
from twilio.rest import TwilioRestClient

# Steem connection and witness information
node = os.environ['steem_node']
witness = os.environ['steem_account']
wif = os.environ['steem_wif']

# Establish the connection to steem
steem = Steem(node=node, keys=[wif])

# How many misses before we trigger the update, 0 for debugging (always trigger)
threshold = int(os.environ['threshold'])

# How often should we check for misses? (in seconds)
check_rate = int(os.environ['check_rate'])

# The signing key to swap to when the threshold is met
backup_key = os.environ['steem_backup']

# Properties to set on the witness update
props = {
    "account_creation_fee": os.environ['steem_account_creation_fee'],
    "maximum_block_size": int(os.environ['steem_maximum_block_size']),
    "sbd_interest_rate": int(os.environ['steem_sbd_interest_rate']),
}
Exemple #27
0
This bot randomly upvotes posts
It upvotes a random post from the most recent [numPostsToConsider]
"""
import sys
import datetime
import os
import subprocess
from piston.steem import Steem
from random import randint

from piston.steem import Steem

steemPostingKey = os.environ.get('steemPostingKey')
steemAccountName = os.environ.get('steemAccountName')

steem = Steem(wif=steemPostingKey)
tagsOrAuthors = [
    "smartcash", "crypt0", "heiditravels", "jerrybanfield", "whiteblood",
    "scooter77", "ellemarieisme", "shayne", "maneco64"
]
voteWeight = 50

for p in steem.stream_comments():
    for tag in tagsOrAuthors:
        try:
            # make p["tags"] into p["author"] if you are voting by author and not by tag
            if tag in p["author"] and p.is_main_post():
                vote = p.upvote(weight=+voteWeight, voter="your username here")
                print("Upvoted post by @" +
                      vote["operations"][0][1]["author"] + " using account @" +
                      vote["operations"][0][1]["voter"] + "!")
Exemple #28
0
from time import sleep
from piston.steem import Steem
import os


steem = Steem(wif=os.environ['STEEM_POSTING_KEY'])
USER = '******'
permlink = 'some-permlink-to-post'
title = 'SWP test test test test test test adsasd'

body = '''
Few sentences about translation process, description, etc.

# Content to translate

{content}

# Links

- link1
- link2

'''

file_summary = '''
## {filename}

```
{filecontent}
```
Exemple #29
0
    api_key = account_conf["Bittrex_API_Key"]
    api_secret = decrypt(pw, account_conf["Bittrex_API_Secret"]).decode()
    bittrexmemo = account_conf["Bittrex_STEEM_Memo"]
    account = account_conf["Steemit_Account"]
    wif = decrypt(pw, account_conf["Steemit_Active_Key"]).decode()
    market = config["Market"]
    dust = float(market["Dust_Level"])
    target = float(market["Target_SBD_Price"])
    margin = float(market["Spread"])
    offset = float(market["Offset"])
    batch = float(market["Batch_Amount"])
    intvlong = int(market["Interval_Long"])
    intvshort = int(market["Interval_Short"])

    bt = Bittrex(api_key, api_secret)
    steem = Steem(wif=wif, node="ws://127.0.0.1:8090")  #steem = Steem(wif=wif)
    cancel_all("both")
    cancel_steem()
    convert()
    time.sleep(2)
    btcbal = balance("BTC")
    sbdbal = balance("SBD")
    steembal = balance("STEEM")
    buyprice, sellprice = prices(btcbal, sbdbal)
    steemprice = steemp(steembal)
    buyprice = rounding(buyprice + offset)
    sellprice = rounding(sellprice - offset)
    steemprice = rounding(steemprice - offset)
    buyquantity = round(btcbal / buyprice - 0.0005, 3) * 0.9975
    sellquantity = sbdbal
    steemquantity = steembal
from piston.steem import Steem
import pprint
pp = pprint.PrettyPrinter(indent=2)
steem = Steem(wif="5KgDg7C8HJqeRaTBQa6kzXRAEtRjn6sUYs1fT15n1wtmyerTiHf")
ignored = ["comment", "vote", "custom_json", "pow2", "account_create"]
for c in steem.rpc.block_stream():
    try:
        tx = tx = c['transactions'][0]['operations'][0]
        if (tx[0] not in ignored):
            pp.pprint(tx)
    except:
        pass
from piston.steem import Steem

# vote by tag:

steem = Steem(wif = "wif posting key here")
tagsOrAuthors = ["introduction", "introduceyourself", "introducemyself"]
voteWeight = 0.05

for p in steem.stream_comments():
        for tag in tags:
            try:
                if tag in p["tags"] and p.is_main_post():
                    vote = p.upvote(weight = +voteWeight, voter = "username here")
                    print("Upvoted post by @"+vote["operations"][0][1]["author"]+" using account @"+vote["operations"][0][1]["voter"]+"!")
            except:
                print("Failed to vote on post.")


                
# vote by author:

steem = Steem(wif = "wif posting key here")
tagsOrAuthors = ["zcgolf16", "jesta", "lukestokes"]
voteWeight = 0.05

for p in steem.stream_comments():
        for tag in tags:
            try:
                if tag in p["author"] and p.is_main_post():
                    vote = p.upvote(weight = +voteWeight, voter = "username here")
                    print("Upvoted post by @"+vote["operations"][0][1]["author"]+" using account @"+vote["operations"][0][1]["voter"]+"!")
Exemple #32
0
import unittest

from piston.post import Post
from piston.steem import Steem
from piston.exceptions import (MissingKeyError, InsufficientAuthorityError,
                               VotingInvalidOnArchivedPost)

identifier = "@xeroc/piston"
testaccount = "xeroc"
wif = {
    "active": "5KkUHuJEFhN1RCS3GLV7UMeQ5P1k5Vu31jRgivJei8dBtAcXYMV",
    "posting": "5KkUHuJEFhN1RCS3GLV7UMeQ5P1k5Vu31jRgivJei8dBtAcXYMV",
    "owner": "5KkUHuJEFhN1RCS3GLV7UMeQ5P1k5Vu31jRgivJei8dBtAcXYMV"
}
steem = Steem(nobroadcast=True, keys=wif)


class Testcases(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(Testcases, self).__init__(*args, **kwargs)
        self.post = Post(identifier, steem_instance=steem)

    def test_getOpeningPost(self):
        self.post._getOpeningPost()

    def test_reply(self):
        try:
            self.post.reply(body="foobar",
                            title="",
                            author=testaccount,
                            meta=None)
Exemple #33
0
    # connect to the database
    connection = pymysql.connect(host='******************',
                                 user='******',
                                 password='******',
                                 db='******************',
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)

    with connection.cursor() as cursor:
        cursor.execute(
            """SELECT SteemAccountRules.id AS ruleID, accountName, author, votePower, delay FROM `SteemAccountRules`
                        INNER JOIN `SteemAccounts` USING (userID) WHERE SteemAccounts.isActive=1 ORDER BY SteemAccounts.dateAdded"""
        )
        userRules = cursor.fetchall()

    steem = Steem("wss://node.steem.ws")  # Create steem object.
    max_time_reached = False  # when max time reached
    last_identifier = None  # store last identifier for next loop
    post_min_time = timedelta(minutes=0)
    post_max_time = timedelta(minutes=35)
    this_list = load_past_votes()
    while not max_time_reached:
        if last_identifier is not None:
            # Get new posts starting at the last one
            results = steem.get_posts(limit=STEEM_MAX_POSTS_REQUEST,
                                      sort='created',
                                      start=last_identifier)
        else:
            # Get the new posts, starting at the beginning
            results = steem.get_posts(limit=STEEM_MAX_POSTS_REQUEST,
                                      sort='created')  # Get new posts
Exemple #34
0
from time import sleep
from piston.steem import Steem
import os

steem = Steem(wif=os.environ['STEEM_POSTING_KEY'])
USER = '******'
permlink = 'some-permlink-to-post'
title = 'SWP test test test test test test adsasd'

body = '''
Few sentences about translation process, description, etc.

# Content to translate

{content}

# Links

- link1
- link2

'''

file_summary = '''
## {filename}

```
{filecontent}
```

'''
Exemple #35
0
def send_a_tip(author):
    steem = Steem(wif=active_key)
    steem.transfer(author, 2.0, "SBD", memo="I love your blog. Here is a small gift for you.", account=account)
Exemple #36
0
def main() :
    global args
    config = Configuration()

    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description="Command line tool to interact with the Steem network"
    )

    """
        Default settings for all tools
    """
    parser.add_argument(
        '--node',
        type=str,
        default=config["node"],
        help='Websocket URL for public Steem API (default: "wss://this.piston.rocks/")'
    )
    parser.add_argument(
        '--rpcuser',
        type=str,
        default=config["rpcuser"],
        help='Websocket user if authentication is required'
    )
    parser.add_argument(
        '--rpcpassword',
        type=str,
        default=config["rpcpassword"],
        help='Websocket password if authentication is required'
    )
    parser.add_argument(
        '--nobroadcast',
        action='store_true',
        help='Do not broadcast anything'
    )
    parser.add_argument(
        '--verbose', '-v',
        type=int,
        default=3,
        help='Verbosity'
    )
    subparsers = parser.add_subparsers(help='sub-command help')

    """
        Command "set"
    """
    setconfig = subparsers.add_parser('set', help='Set configuration')
    setconfig.add_argument(
        'key',
        type=str,
        choices=["default_author",
                 "default_voter",
                 "node",
                 "rpcuser",
                 "rpcpassword",
                 "default_vote_weight",
                 "list_sorting",
                 "categories_sorting",
                 "limit",
                 "post_category"],
        help='Configuration key'
    )
    setconfig.add_argument(
        'value',
        type=str,
        help='Configuration value'
    )
    setconfig.set_defaults(command="set")

    """
        Command "config"
    """
    configconfig = subparsers.add_parser('config', help='show local configuration')
    configconfig.set_defaults(command="config")

    """
        Command "addkey"
    """
    addkey = subparsers.add_parser('addkey', help='Add a new key to the wallet')
    addkey.add_argument(
        'wifkeys',
        nargs='*',
        type=str,
        help='the private key in wallet import format (wif)'
    )
    addkey.set_defaults(command="addkey")

    """
        Command "listkeys"
    """
    listkeys = subparsers.add_parser('listkeys', help='List available keys in your wallet')
    listkeys.set_defaults(command="listkeys")

    """
        Command "listaccounts"
    """
    listaccounts = subparsers.add_parser('listaccounts', help='List available accounts in your wallet')
    listaccounts.set_defaults(command="listaccounts")

    """
        Command "list"
    """
    parser_list = subparsers.add_parser('list', help='List posts on Steem')
    parser_list.set_defaults(command="list")
    parser_list.add_argument(
        '--start',
        type=str,
        help='Start list from this identifier (pagination)'
    )
    parser_list.add_argument(
        '--category',
        type=str,
        help='Only posts with in this category'
    )
    parser_list.add_argument(
        '--sort',
        type=str,
        default=config["list_sorting"],
        choices=["trending", "created", "active", "cashout", "payout", "votes", "children", "hot"],
        help='Sort posts'
    )
    parser_list.add_argument(
        '--limit',
        type=int,
        default=config["limit"],
        help='Limit posts by number'
    )

    """
        Command "categories"
    """
    parser_categories = subparsers.add_parser('categories', help='Show categories')
    parser_categories.set_defaults(command="categories")
    parser_categories.add_argument(
        '--sort',
        type=str,
        default=config["categories_sorting"],
        choices=["trending", "best", "active", "recent"],
        help='Sort categories'
    )
    parser_categories.add_argument(
        'category',
        nargs="?",
        type=str,
        help='Only categories used by this author'
    )
    parser_categories.add_argument(
        '--limit',
        type=int,
        default=config["limit"],
        help='Limit categories by number'
    )

    """
        Command "read"
    """
    parser_read = subparsers.add_parser('read', help='Read a post on Steem')
    parser_read.set_defaults(command="read")
    parser_read.add_argument(
        'post',
        type=str,
        help='@author/permlink-identifier of the post to read (e.g. @xeroc/python-steem-0-1)'
    )
    parser_read.add_argument(
        '--full',
        action='store_true',
        help='Show full header information (YAML formated)'
    )
    parser_read.add_argument(
        '--comments',
        action='store_true',
        help='Also show all comments'
    )
    parser_read.add_argument(
        '--parents',
        type=int,
        default=0,
        help='Show x parents for the reply'
    )
    parser_read.add_argument(
        '--format',
        type=str,
        default=config["format"],
        help='Format post',
        choices=["markdown", "raw"],
    )

    """
        Command "post"
    """
    parser_post = subparsers.add_parser('post', help='Post something new')
    parser_post.set_defaults(command="post")
    parser_post.add_argument(
        '--author',
        type=str,
        required=False,
        default=config["default_author"],
        help='Publish post as this user (requires to have the key installed in the wallet)'
    )
    parser_post.add_argument(
        '--permlink',
        type=str,
        required=False,
        help='The permlink (together with the author identifies the post uniquely)'
    )
    parser_post.add_argument(
        '--category',
        default=config["post_category"],
        type=str,
        help='Specify category'
    )
    parser_post.add_argument(
        '--title',
        type=str,
        required=False,
        help='Title of the post'
    )
    parser_post.add_argument(
        '--file',
        type=str,
        default=None,
        help='Filename to open. If not present, or "-", stdin will be used'
    )

    """
        Command "reply"
    """
    reply = subparsers.add_parser('reply', help='Reply to an existing post')
    reply.set_defaults(command="reply")
    reply.add_argument(
        'replyto',
        type=str,
        help='@author/permlink-identifier of the post to reply to (e.g. @xeroc/python-steem-0-1)'
    )
    reply.add_argument(
        '--author',
        type=str,
        required=False,
        default=config["default_author"],
        help='Publish post as this user (requires to have the key installed in the wallet)'
    )
    reply.add_argument(
        '--permlink',
        type=str,
        required=False,
        help='The permlink (together with the author identifies the post uniquely)'
    )
    reply.add_argument(
        '--title',
        type=str,
        required=False,
        help='Title of the post'
    )
    reply.add_argument(
        '--file',
        type=str,
        required=False,
        help='Send file as responds. If "-", read from stdin'
    )

    """
        Command "edit"
    """
    parser_edit = subparsers.add_parser('edit', help='Edit to an existing post')
    parser_edit.set_defaults(command="edit")
    parser_edit.add_argument(
        'post',
        type=str,
        help='@author/permlink-identifier of the post to edit to (e.g. @xeroc/python-steem-0-1)'
    )
    parser_edit.add_argument(
        '--author',
        type=str,
        required=False,
        default=config["default_author"],
        help='Post an edit as another author'
    )
    parser_edit.add_argument(
        '--file',
        type=str,
        required=False,
        help='Patch with content of this file'
    )
    parser_edit.add_argument(
        '--replace',
        action='store_true',
        help="Don't patch but replace original post (will make you lose votes)"
    )

    """
        Command "upvote"
    """
    parser_upvote = subparsers.add_parser('upvote', help='Upvote a post')
    parser_upvote.set_defaults(command="upvote")
    parser_upvote.add_argument(
        'post',
        type=str,
        help='@author/permlink-identifier of the post to upvote to (e.g. @xeroc/python-steem-0-1)'
    )
    parser_upvote.add_argument(
        '--voter',
        type=str,
        required=False,
        default=config["default_voter"],
        help='The voter account name'
    )
    parser_upvote.add_argument(
        '--weight',
        type=float,
        default=config["default_vote_weight"],
        required=False,
        help='Actual weight (from 0.1 to 100.0)'
    )

    """
        Command "downvote"
    """
    parser_downvote = subparsers.add_parser('downvote', help='Downvote a post')
    parser_downvote.set_defaults(command="downvote")
    parser_downvote.add_argument(
        '--voter',
        type=str,
        required=False,
        help='The voter account name'
    )
    parser_downvote.add_argument(
        'post',
        type=str,
        help='@author/permlink-identifier of the post to downvote to (e.g. @xeroc/python-steem-0-1)'
    )
    parser_downvote.add_argument(
        '--weight',
        type=float,
        default=config["default_vote_weight"],
        required=False,
        help='Actual weight (from 0.1 to 100.0)'
    )

    """
        Command "replies"
    """
    replies = subparsers.add_parser('replies', help='Show recent replies to your posts')
    replies.set_defaults(command="replies")
    replies.add_argument(
        '--author',
        type=str,
        required=False,
        default=config["default_author"],
        help='Show replies to this author'
    )
    replies.add_argument(
        '--limit',
        type=int,
        default=config["limit"],
        help='Limit posts by number'
    )

    """
        Command "transfer"
    """
    parser_transfer = subparsers.add_parser('transfer', help='Transfer STEEM')
    parser_transfer.set_defaults(command="transfer")
    parser_transfer.add_argument(
        'to',
        type=str,
        help='Recepient'
    )
    parser_transfer.add_argument(
        'amount',
        type=str,
        help='Amount to transfer including asset (e.g.: 100.000 STEEM)'
    )
    parser_transfer.add_argument(
        'memo',
        type=str,
        nargs="?",
        default="",
        help='Optional memo'
    )
    parser_transfer.add_argument(
        '--account',
        type=str,
        required=False,
        default=config["default_author"],
        help='Transfer from this account'
    )

    """
        Command "powerup"
    """
    parser_powerup = subparsers.add_parser('powerup', help='Power up (vest STEEM as STEEM POWER)')
    parser_powerup.set_defaults(command="powerup")
    parser_powerup.add_argument(
        'amount',
        type=str,
        help='Amount to powerup including asset (e.g.: 100.000 STEEM)'
    )
    parser_powerup.add_argument(
        '--account',
        type=str,
        required=False,
        default=config["default_author"],
        help='Powerup from this account'
    )
    parser_powerup.add_argument(
        '--to',
        type=str,
        required=False,
        default=config["default_author"],
        help='Powerup this account'
    )

    """
        Command "powerdown"
    """
    parser_powerdown = subparsers.add_parser('powerdown', help='Power down (start withdrawing STEEM from STEEM POWER)')
    parser_powerdown.set_defaults(command="powerdown")
    parser_powerdown.add_argument(
        'amount',
        type=str,
        help='Amount to powerdown including asset (e.g.: 100.000 VESTS)'
    )
    parser_powerdown.add_argument(
        '--account',
        type=str,
        required=False,
        default=config["default_author"],
        help='powerdown from this account'
    )

    """
        Command "balance"
    """
    parser_balance = subparsers.add_parser('balance', help='Power down (start withdrawing STEEM from STEEM POWER)')
    parser_balance.set_defaults(command="balance")
    parser_balance.add_argument(
        'account',
        type=str,
        nargs="*",
        default=config["default_author"],
        help='balance from this account'
    )

    """
        Parse Arguments
    """
    args = parser.parse_args()

    # Logging
    log = logging.getLogger("piston")
    verbosity = ["critical",
                 "error",
                 "warn",
                 "info",
                 "debug"][int(min(args.verbose, 4))]
    log.setLevel(getattr(logging, verbosity.upper()))
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    ch = logging.StreamHandler()
    ch.setLevel(getattr(logging, verbosity.upper()))
    ch.setFormatter(formatter)
    log.addHandler(ch)

    # GrapheneAPI logging
    if args.verbose > 4:
        verbosity = ["critical",
                     "error",
                     "warn",
                     "info",
                     "debug"][int(min((args.verbose - 4), 4))]
        gphlog = logging.getLogger("graphenebase")
        gphlog.setLevel(getattr(logging, verbosity.upper()))
        gphlog.addHandler(ch)
    if args.verbose > 8:
        verbosity = ["critical",
                     "error",
                     "warn",
                     "info",
                     "debug"][int(min((args.verbose - 8), 4))]
        gphlog = logging.getLogger("grapheneapi")
        gphlog.setLevel(getattr(logging, verbosity.upper()))
        gphlog.addHandler(ch)

    rpc_not_required = ["set", "config", ""]
    if args.command not in rpc_not_required and args.command:
        steem = Steem(
            args.node,
            args.rpcuser,
            args.rpcpassword,
            nobroadcast=args.nobroadcast
        )

    if args.command == "set":
        config[args.key] = args.value

    if args.command == "config":
        t = PrettyTable(["Key", "Value"])
        t.align = "l"
        for key in config.store:
            t.add_row([key, config[key]])
        print(t)

    elif args.command == "addkey":
        wallet = Wallet(steem.rpc)
        if len(args.wifkeys):
            for wifkey in args.wifkeys:
                pub = (wallet.addPrivateKey(wifkey))
                if pub:
                    print(pub)
        else:
            import getpass
            wifkey = ""
            while True:
                wifkey = getpass.getpass('Private Key (wif) [Enter to quit]:')
                if not wifkey:
                    break
                pub = (wallet.addPrivateKey(wifkey))
                if pub:
                    print(pub)

        name = wallet.getAccountFromPublicKey(pub)
        print("Setting new default user: %s" % name)
        print("You can change these settings with:")
        print("    piston set default_author x")
        print("    piston set default_voter x")
        config["default_author"] = name
        config["default_voter"] = name

    elif args.command == "listkeys":
        t = PrettyTable(["Available Key"])
        t.align = "l"
        for key in Wallet(steem.rpc).getPublicKeys():
            t.add_row([key])
        print(t)

    elif args.command == "listaccounts":
        t = PrettyTable(["Name", "Available Key"])
        t.align = "l"
        for account in Wallet(steem.rpc).getAccounts():
            t.add_row(account)
        print(t)

    elif args.command == "reply":
        from textwrap import indent
        parent = steem.get_content(args.replyto)
        if parent["id"] == "0.0.0":
            print("Can't find post %s" % args.replyto)
            return

        reply_message = indent(parent["body"], "> ")

        post = frontmatter.Post(reply_message, **{
            "title": args.title if args.title else "Re: " + parent["title"],
            "author": args.author if args.author else "required",
            "replyto": args.replyto,
        })

        meta, message = yaml_parse_file(args, initial_content=post)

        for required in ["author", "title"]:
            if (required not in meta or
                    not meta[required] or
                    meta[required] == "required"):
                print("'%s' required!" % required)
                # TODO, instead of terminating here, send the user back
                # to the EDITOR
                return

        pprint(steem.reply(
            meta["replyto"],
            message,
            title=meta["title"],
            author=args.author
        ))

    elif args.command == "post" or args.command == "yaml":
        post = frontmatter.Post("", **{
            "title": args.title if args.title else "required",
            "author": args.author if args.author else "required",
            "category": args.category if args.category else "required",
        })

        meta, body = yaml_parse_file(args, initial_content=post)

        if not body:
            print("Empty body! Not posting!")
            return

        for required in ["author", "title", "category"]:
            if (required not in meta or
                    not meta[required] or
                    meta[required] == "required"):
                print("'%s' required!" % required)
                # TODO, instead of terminating here, send the user back
                # to the EDITOR
                return

        pprint(steem.post(
            meta["title"],
            body,
            author=meta["author"],
            category=meta["category"]
        ))

    elif args.command == "edit":
        original_post = steem.get_content(args.post)

        edited_message = None
        if original_post["id"] == "0.0.0":
            print("Can't find post %s" % args.post)
            return

        post = frontmatter.Post(original_post["body"], **{
            "title": original_post["title"] + " (immutable)",
            "author": original_post["author"] + " (immutable)"
        })

        meta, edited_message = yaml_parse_file(args, initial_content=post)
        pprint(steem.edit(
            args.post,
            edited_message,
            replace=args.replace
        ))

    elif args.command == "upvote" or args.command == "downvote":
        if args.command == "downvote":
            weight = -float(args.weight)
        else:
            weight = +float(args.weight)
        if not args.voter:
            print("Not voter provided!")
            return
        pprint(steem.vote(
            args.post,
            weight,
            voter=args.voter
        ))

    elif args.command == "read":
        post_author, post_permlink = resolveIdentifier(args.post)

        if args.parents:
            # FIXME inconsistency, use @author/permlink instead!
            dump_recursive_parents(
                steem.rpc,
                post_author,
                post_permlink,
                args.parents,
                format=args.format
            )

        if not args.comments and not args.parents:
            post = steem.get_content(args.post)

            if post["id"] == "0.0.0":
                print("Can't find post %s" % args.post)
                return
            if args.format == "markdown":
                body = markdownify(post["body"])
            else:
                body = post["body"]

            if args.full:
                meta = post.copy()
                meta.pop("body", None)  # remove body from meta
                yaml = frontmatter.Post(body, **meta)
                print(frontmatter.dumps(yaml))
            else:
                print(body)

        if args.comments:
            dump_recursive_comments(
                steem.rpc,
                post_author,
                post_permlink,
                format=args.format
            )

    elif args.command == "categories":
        categories = steem.get_categories(
            args.sort,
            begin=args.category,
            limit=args.limit
        )
        t = PrettyTable(["name", "discussions", "payouts"])
        t.align = "l"
        for category in categories:
            t.add_row([
                category["name"],
                category["discussions"],
                category["total_payouts"],
            ])
        print(t)

    elif args.command == "list":
        list_posts(
            steem.get_posts(
                limit=args.limit,
                sort=args.sort,
                category=args.category,
                start=args.start
            )
        )

    elif args.command == "replies":
        discussions = steem.get_replies(args.author)
        list_posts(discussions[0:args.limit])

    elif args.command == "transfer":
        pprint(steem.transfer(
            args.to,
            args.amount,
            memo=args.memo,
            account=args.account
        ))

    elif args.command == "powerup":
        pprint(steem.transfer_to_vesting(
            args.amount,
            account=args.account,
            to=args.to
        ))

    elif args.command == "powerdown":
        pprint(steem.withdraw_vesting(
            args.amount,
            account=args.account,
        ))

    elif args.command == "balance":
        t = PrettyTable(["Account", "STEEM", "SBD", "VESTS"])
        t.align = "r"
        if isinstance(args.account, str):
            args.account = [args.account]
        for a in args.account:
            b = steem.get_balances(a)
            t.add_row([
                a,
                b["balance"],
                b["sbd_balance"],
                b["vesting_shares"],
            ])
        print(t)

    else:
        print("No valid command given")
Exemple #37
0
from piston.steem import Steem
from piston.blockchain import Blockchain

chain = Blockchain()

blacklist = [""]   

trusted_voters = [""]   

pk = ["postingkeyhere"] 

account = ["deutschbot"]

threshold = 1 

steem = Steem(keys=pk[0])) 

for operation in chain.ops(
                           filter_by=["vote"]
                          ):

    op = operation["op"]

    if op[0] == "vote":

        comment_voter = op[1]["voter"]

        if comment_voter in trusted_voters:

            comment_link = op[1]["permlink"]
            comment_author = op[1]["author"]
from piston.steem import Post
import os
import json
import re
import html2text
import requests
from itertools import islice
import difflib
import collections
from collections import OrderedDict
import random

account = 'ChangThisToYourSteemitUsername'
author = 'ChangThisToYourSteemitUsername'
wif = '5YourPostingKeyGoesHere12345678901234567890'
steem = Steem(nobroadcast=False, wif=wif)

#initialise lists to store snippets of the content
captureContentInAList = []
captureContentInTheFinalList = []

percentageDifferenceFormatted = ''
percentageRequired = 0.5
captureContentSnippet = ''
stillTheSamePoster = ''
yacySearchResultDescription = ''
link = ''
limit = 4
theContent = ''
mainLoop = 0
stopLookingForContent = 0