コード例 #1
0
def main():

    parser = argparse.ArgumentParser(
        description='show user balances',
        epilog='Report bugs to: https://github.com/bitfag/golos-scripts/issues'
    )
    parser.add_argument('account', help='account name')
    parser.add_argument('-c',
                        '--config',
                        default='./common.yml',
                        help='specify custom path for config file')
    args = parser.parse_args()

    # parse config
    with open(args.config, 'r') as ymlfile:
        conf = yaml.load(ymlfile)

    golos = Steem(nodes=conf['nodes_new'], no_broadcast=True)

    a = Account(args.account, steemd_instance=golos)
    b = a.get_balances()
    pprint(b)

    vests = b['total']['GESTS']
    cv = Converter(golos)
    pprint('GP: {}'.format(cv.vests_to_sp(vests)))
コード例 #2
0
def update_account(mongo, username, load_extras=True):
    """ Update Account. 
    
    If load_extras is True, update:
     - followers, followings
     - curation stats
     - withdrawal routers, conversion requests

    """
    a = Account(username)
    account = {
        **typify(a.export(load_extras=load_extras)),
        'account': username,
        'updatedAt': dt.datetime.utcnow(),
    }
    if type(account['json_metadata']) is dict:
        account['json_metadata'] = \
            strip_dot_from_keys(account['json_metadata'])
    if not load_extras:
        account = {'$set': account}
    try:
        mongo.Accounts.update({'name': a.name}, account, upsert=True)
    except WriteError:
        # likely an invalid profile
        account['json_metadata'] = {}
        mongo.Accounts.update({'name': a.name}, account, upsert=True)
        print("Invalidated json_metadata on %s" % a.name)
コード例 #3
0
def get_transactions():
    id = ""
    bid =""
    parameteraccount = "nextcolony"
    account = Account(parameteraccount)
    #this function is used to load transcations into a database
    account_history = list(account.get_account_history(-1, 10000, filter_by=["transfer"]))
    for transaction in account_history:
        try:
            memo = transaction["memo"]
            trx_id = transaction['trx_id']
            timestamp =transaction['timestamp']
            fromaccount = transaction["from"]
            if memo.startswith('nc'):
                #print (transaction)
                code, parameters = transaction["memo"].split("@")
                JSON = json.loads(parameters)
                #print(JSON)
                command = (JSON['command'])
                type = (JSON['type'])
                #print (type)
                #print (command)
                if type =="auctionbid":
                    bid = command['bid']
                    id = command['id']
                    #print (id)
                    #print (bid)
                    #print (transaction)

                    #write the transaction in the database
                    # Connect to the database

                    connection = pymysql.connect(host='localhost',
                                                 user='******',
                                                 password='******',
                                                 db='steembattle',
                                                 charset='utf8mb4',
                                                 cursorclass=pymysql.cursors.DictCursor)
                    with connection.cursor() as cursor:
                        sql = ("SELECT * FROM `auction` WHERE `steem_trx` = '"+str(trx_id)+"'")
                        #print(sql)
                        cursor.execute(sql)
                        results = cursor.fetchone()
                        #print(results)
                        if results == None:
                           print ("Noch nicht vorhanden")
                           with connection.cursor() as cursor:
                               sql = ("INSERT INTO `auction` (`trx_id`, `steem_trx`, `timestamp`, `bid`, `planet_id`, `user`) VALUES (NULL, '"+str(trx_id)+"', '"+str(timestamp)+"', '"+str(bid)+"', '"+str(id)+"', '"+str(fromaccount)+"')")
                               print(sql)
                               cursor.execute(sql)
                               connection.commit()
                               connection.close()

                #print(JSON)

        except:
            continue

    return
コード例 #4
0
 def process_timestamp(self, block):
     timestamp = block['timestamp']
     datetime_object = datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S')
     if datetime_object.second == 54:
         account = Account(self.account)
         print(f'\nVoting power: {account.voting_power()}%\n')
         if account.voting_power() == 100:
             self.queue.run_voting_round()
コード例 #5
0
def run():
    account     = "sttest1"
    account      = Account(account)
    wif          = os.environ.get("UNLOCK")
    steem        = Steem(wif=wif)
    blockchain   = Blockchain()
    stream       = map(Post, blockchain.stream(filter_by=["comment"]))
    upvote_list  = json.load(open('upvote_list.json'))
    upvoted      = {}
    upvote_queue = {}
    date         = int(time.strftime("%d"))
    hour         = int(time.strftime("%-H"))

    print("Entering blockchain stream!")
    while True:
        try:
            for post in stream:

                time_string = str(post.time_elapsed())
                post_age = time_string.split(":")

                try:
                    # Omit posts older than 10 min
                    if int(post_age[0]) > 0 or int(post_age[1]) > 10:
                        break
                except Exception as e:
                    #print (repr(e))
                    break

                # start upvoting cycle at 100% voting power
                if account.voting_power() == 100:
                    start_upvote_cycle(upvote_queue, account, steem)

                # check for new date
                if int(time.strftime("%d")) is not date:
                    upvoted = {}
                    date = int(time.strftime("%d"))
                #check for new hour
                if int(time.strftime("%-H")) is not hour:
                    upvote_list  = json.load(open('upvote_list.json'))
                    hour = int(time.strftime("%-H"))

                # verify post and add to queue
                if valid_post(post, upvote_list, upvoted):
                    try:
                        author = post["author"]
                        print ("\nAdding to queue{}\nPermlink: {}".format(author, post['identifier']))
                        if post['identifier'] not in upvote_queue:
                            upvote_queue[post['identifier']] = upvote_list[author]["upvote_weight"]
                            print ("Upvoted {} for {}%".format(author, upvote_list[author]["upvote_weight"]))
                            upvoted[author] += 1
                    except Exception as error:
                        print(repr(error))
                        continue

        except Exception as error:
            #print(repr(error))
            continue
コード例 #6
0
    def get_history(self, username):
        a = Account(username)
        history = a.history_reverse()
        count = 1

        for item in history:
            if count > 3:
                break
            print(item)
            count = count + 1
コード例 #7
0
def get_inbound_steem_transfers(account_name):
    nodes = ['https://api.steemit.com', 'https://gtg.steem.house:8090']
    set_shared_steemd_instance(Steemd(nodes=nodes))
    acc = Account('greenman')

    def filter(t):
        return t['to'] == account_name and float(
            t['amount'].split(' ')[0]) > .1

    return [t for t in acc.history(filter_by=['transfer']) if filter(t)]
コード例 #8
0
class Testcases(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(Testcases, self).__init__(*args, **kwargs)
        self.account = Account(testaccount)

    def test_readAccount(self):
        self.assertEqual(self.account["id"], 1489)

    def test_getbalance(self):
        self.account.get_balances()
コード例 #9
0
    def get_latest_flags(self):
        flags = {}
        total_amount = 0
        account = Account(self.account_for_flag_report,
                          steemd_instance=self.steemd_instance)
        for vote in account.history_reverse(filter_by="vote"):
            if vote["weight"] > 0:
                continue
            if vote["voter"] != self.account_for_flag_report:
                continue
            ts = parse(vote["timestamp"])
            if ts < (datetime.utcnow() - timedelta(days=1)):
                break

            try:
                p = Post("%s/%s" % (vote["author"], vote["permlink"]),
                         steemd_instance=self.steemd_instance)
            except steembase.exceptions.PostDoesNotExist:
                logger.info("Couldnt load the post. %s" % vote["permlink"])
                continue

            if vote["author"] not in flags:
                flags[vote.get("author")] = {
                    "posts": 0,
                    "comments": 0,
                    "total_removed": 0
                }

            if p.is_main_post():
                flags[vote.get("author")].update(
                    {"posts": flags[vote.get("author")]["posts"] + 1})
            else:
                flags[vote.get("author")].update(
                    {"comments": flags[vote.get("author")]["comments"] + 1})

            logger.info("Analyzing %s" % self.url(p))

            for active_vote in p.get("active_votes"):
                if float(active_vote.get("rshares")) > 0:
                    continue

                if active_vote.get("voter") != self.account_for_flag_report:
                    continue

                amount_removed = self.get_payout_from_rshares(
                    active_vote.get("rshares"))
                total_amount += amount_removed

                flags[vote.get("author")].update({
                    "total_removed":
                    flags[vote.get("author")]["total_removed"] +
                    amount_removed,
                })

        return flags, round(total_amount, 2)
コード例 #10
0
    def handle_curation(self, op_type, op_value):

        curators = [c["account"] for c in get_curators()]

        # we're only interested in votes
        if op_type != "vote":
            return

        # if the voter is not a trusted curator, skip it.
        if op_value.get("voter") not in curators:
            return

        # check the post if we have already voted?
        p = Post("%s/%s" % (op_value.get("author"), op_value.get("permlink")),
                 steemd_instance=self.s)

        # we're only interested in main posts
        if not p.is_main_post():
            return

        # the post is tagged with the tags we defined?
        if len(set(self.expected_tags).intersection(p.get("tags"))) == 0:
            return

        # is the author in the blacklist?
        if is_blacklisted(op_value.get("author")):
            return

        score = 0
        already_voted = False
        curators_on_the_post = []
        for active_vote in p.get("active_votes", []):
            if active_vote.get("voter") == self.bot_account:
                already_voted = True
            if active_vote.get("voter") in curators:
                score += active_vote.get("percent")
                curators_on_the_post.append({
                    "curator":
                    active_vote.get("voter"),
                    "weight":
                    active_vote.get("percent"),
                })

        # if we already voted on that, skip.
        if already_voted:
            return

        # if the score is lower then the threshold, skip.
        if score < int(get_option(THRESHOLD_OPTION_ID)["value"]):
            return

        bot_account = Account(self.bot_account, steemd_instance=self.s)
        weight = bot_account.voting_power()
        self.upvote(p, weight, self.bot_account)
        self.post_to_webhooks(p, curators_on_the_post, score, weight)
コード例 #11
0
ファイル: follow.py プロジェクト: repodiscover/boiler
def run(tags):
    log.info("Follow mode activated", tags=tags)

    if tags is None or len(tags) < 1:
        raise ValueError("You must specify at least one tag")

    log.debug("initializing...")
    steem = Steem(keys=[cred.key])
    account = Account(cred.id, steem)
    chain = Blockchain(steem)
    log.debug("ready", steem=steem, account=account, blockchain=chain)

    log.info("Gathering our following list...")
    following = account.get_following()
    pending = []
    log.info("Following list retrieved", count=len(following))

    log.info("Watching for new posts...")
    while True:
        stream = map(Post, chain.stream(filter_by=['comment']))

        try:
            for post in stream:
                count = len(pending)
                if count > 0:
                    copy = list(pending)
                    for i in range(count):
                        if have_bandwidth(steem, account):
                            user = copy[i]
                            log.info("following user", user=user)
                            steem.follow(user, account=cred.id)
                            del pending[0]

                        else:
                            log.warn("Waiting for more bandwidth before following another user")
                            break


                if post.is_main_post():
                    log.debug("found a top-level post", author=post.author, tags=post.tags)

                    if post.author != cred.id:
                        for tag in tags:
                            if tag in post.tags:
                                if post.author not in following:
                                    pending.append(post.author)
                                    following.append(post.author)
                                    break

        except PostDoesNotExist as e:
            log.debug("Post has vanished", exception=e)

        except RPCError as e:
            log.error("RPC problem while streaming posts", exception=e)
コード例 #12
0
def update_account(mongo, steem, username, load_extras=True):
    """ Update Account. If load_extras """
    a = Account(username, steem_instance=steem)
    account = {
        **typify(a.export(load_extras=load_extras)),
        'account': username,
        'updatedAt': dt.datetime.utcnow(),
    }
    if not load_extras:
        account = {'$set': account}
    mongo.Accounts.update({'name': a.name}, account, upsert=True)
コード例 #13
0
def test_history():
    a = Account('barbara2')
    h1 = [x['index'] for x in list(a.history())]
    h2 = [x['index'] for x in list(a.history_reverse())]

    # pprint(list(zip(h1, h2[::-1])))

    # various tests of equality should pass
    assert len(h1) == len(h2)
    assert set(h1) == set(h2) == set(range(a.virtual_op_count() + 1))
    assert h1 == h2[::-1] == list(range(a.virtual_op_count() + 1))
コード例 #14
0
ファイル: blog.py プロジェクト: bue-twitter/steemdata
    def __init__(self, account_name, steem_instance=None):
        if not steem_instance:
            steem_instance = stm.Steem()
        self.steem = steem_instance

        self.account = Account(account_name)
        self.current_index = self.account.virtual_op_count()
        self.history = None

        # prevent duplicates
        self.seen_items = set()
コード例 #15
0
 def voting_stats(account_name):
 # Get voting statistics given an account name.
 # Returns Steem Power, Voting Power, Time to recharge(min), Current Voting Power and Value of vote in Steem 
     account = Account(account_name)
     SP = steemfunc.calculateSP(account)
     print('Steem Power:', int(SP), 'SP')
     VP,recharge_time = steemfunc.getactiveVP(account)
     current_VP = account.voting_power()
     print('Voting Power:', int(VP))
     vote_value = steemfunc.getvotevalue(SP, VP, 100)
     return SP,VP,recharge_time,current_VP,vote_value
コード例 #16
0
def calculate_producer_rewards(steemd_instance, witness_account):
    account = Account(witness_account, steemd_instance=steemd_instance)

    total_vests = 0

    for producer_reward in account.history_reverse(
            filter_by=["producer_reward"]):
        total_vests += Amount(producer_reward["vesting_shares"]).amount

    converter = Converter(steemd_instance=s)
    total_sp = converter.vests_to_sp(total_vests)

    return total_vests, total_sp
コード例 #17
0
ファイル: bot.py プロジェクト: eosvenezuela/tagbot
    def last_voted_accounts_and_posts(self):
        voted_accounts = set()
        voted_posts = set()
        account = Account(self.config.get("BOT_ACCOUNT"))
        vote_interval = self.config.get("VOTE_INTERVAL_IN_DAYS", 1)
        for vote in account.history_reverse(filter_by=["vote"]):
            created_at = parse(vote["timestamp"])
            if created_at < (datetime.utcnow() -
                             timedelta(days=vote_interval)):
                break
            voted_accounts.add(vote["author"])
            voted_posts.add("@%s/%s" % (vote["author"], vote["permlink"]))

        return voted_accounts, voted_posts
コード例 #18
0
def processComment(op):
    comment_body = op['body']
    if not comment_body or comment_body.startswith('@@ '):
        return
    post = Post(op, steem_instance=steem)
    pkey = getPostKey(post)
    print('post: ', pkey)
    if not pkey or pkey in processed_posts:
        return
    processed_posts[pkey] = True
    author_account = Account(op['author'], steem_instance=steem)
    if author_account.rep < MIN_NOTIFY_REPUTATION:
        # no notifications for low-rep accounts
        return
    processMentions(author_account, comment_body, op)
    if op['parent_author']:
        if op['parent_author'] != op['author']:
            # no need to notify self of own comments
            title = 'Steemit'
            body = '@%s replied to your post or comment' % (op['author'])
            url = '%s/@%s/recent-replies' % (
                os.environ['STEEMIT_WEBCLIENT_ADDRESS'], op['parent_author'])
            profile = author_account.profile
            pic = img_proxy_prefix + profile['profile_image'] \
                if profile and 'profile_image' in profile else ''
            tnt_server.call('notification_add', op['parent_author'],
                            NTYPES['comment_reply'], title, body, url, pic)
    else:
        followers = getFollowers(author_account)
        for follower in followers:
            tnt_server.call('notification_add', follower, NTYPES['feed'])
コード例 #19
0
ファイル: paydelegates.py プロジェクト: symbiotes/TrufflePig
def claim_all_reward_balance(steem, account):
    """Helper funtion to claim rewards because of bug in Steem"""
    acc = Account(account, steem)
    reward_steem = acc['reward_steem_balance']
    reward_sbd = acc['reward_sbd_balance']
    reward_vests = acc['reward_vesting_balance']
    logger.info('Claiming {}, {}, and {} for {}'.format(reward_sbd,
                                                        reward_vests,
                                                        reward_steem,
                                                        account))
    op = operations.ClaimRewardBalance(account=account,
                                       reward_steem=reward_steem,
                                       reward_sbd=reward_sbd,
                                       reward_vests=reward_vests)

    can_claim = any(Amount(x).amount > 0 for x in (reward_sbd, reward_vests, reward_steem))
    if can_claim:
        try:
            return error_retry(steem.commit.finalizeOp)(op, account, "posting")
        except Exception:
            logger.exception('Could not claim rewards {}. '
                             'Reconnecting...'.format((reward_sbd,
                                                      reward_vests,
                                                      reward_steem)))
            steem.reconnect()
    else:
        logger.info('Nothing to claim!')
コード例 #20
0
    def __init__(self, username):
        self.username = username
        self.session = Account(self.username, steemd_instance=s)

        self.wallet = {
            "steem_balance":
            float(self.session['balance'].replace('STEEM', '')),
            "sbd_balance":
            float(self.session['sbd_balance'].replace('SBD', '')),
            "vests":
            float(self.session['vesting_shares'].replace('VESTS', '')),
            "delegated_vests":
            float(self.session['received_vesting_shares'].replace('VESTS', ''))
            - float(self.session['delegated_vesting_shares'].replace(
                'VESTS', '')),
            "delegated_vesting_shares":
            float(self.session['delegated_vesting_shares'].replace(
                'VESTS', '')),
            "received_vesting_shares":
            float(self.session['received_vesting_shares'].replace('VESTS',
                                                                  '')),
            "voting_power":
            float(self.session['voting_power'] / 100)
        }

        self.wallet['acc_value'] = self.calculate_estimated_acc_value()
        self.wallet['upvote'] = self.calculate_estimated_upvote()
        self.wallet['delegations'] = self.calculate_steem_power(
        )['delegations']
        self.wallet['sp_balance'] = self.calculate_steem_power()['sp_balance']
コード例 #21
0
    def create(self,
               community_type: str = 'public',
               admins: Union[str, list] = None):
        """ Create a new community.

        This method will upgrade an existing STEEM account into a new community.

        Args:
            community_type: Can be **public** (default) or **restricted**.
            admins: A single username, or a list of users who will be community Admins.
             If left empty, the community owner will be assigned as a single admin. Can be modified later.
        """
        # validate account and community name
        Account(self.account)
        assert self.community == self.account, 'Account name and community name need to be the same'

        if is_community(self.community):
            raise NameError(
                'Can not create community %s, because it already exists.' %
                self.community)

        if type(admins) == str:
            admins = [admins]
        if not admins:
            admins = [self.community]

        op = self._op(action='create', type=community_type, admins=admins)
        return self._commit(op)
コード例 #22
0
def commitParticipants():
    current = Account(donation_account)
    current_participants = current['json_metadata']['extensions']['ico']
    if state != current_participants:
        l("Committing participants to `json_metadata` on @{}".format(
            donation_account))
        saveState()
コード例 #23
0
def getsbdprice():
    #get the last transactions of steemmonsters from the blockchain
    acc = Account('steemmonsters')
    account_history = acc.get_account_history(-1,
                                              1000,
                                              filter_by=["custom_json"])
    for custom_json in account_history:
        try:
            data = custom_json["json"]
            parsed_json = json.loads(data)
            code = custom_json["id"]
            if code == "sm_price_feed":
                sbd = parsed_json["sbd"]
                return (sbd)
        except:
            print("Error getting the SBD price")
コード例 #24
0
def update_account_ops(mongo, username):
    """ This method will fetch entire account history, and back-fill any missing ops. """
    for event in Account(username).history():
        with suppress(DuplicateKeyError):
            transform = compose(strip_dot_from_keys, remove_body, json_expand,
                                typify)
            mongo.AccountOperations.insert_one(transform(event))
コード例 #25
0
ファイル: methods.py プロジェクト: d-trip/dtrip-mongo
def update_account(name):
    account = Account(name).export(load_extras=False)
    prepare_account(account)

    # TODO Parse coordinates
    # parse_location(account)

    AccountModel.objects(name=name).update(**account, upsert=True)
コード例 #26
0
def saveState():
    current = Account(donation_account)
    profile = current['json_metadata']
    if 'extensions' not in profile:
        profile.update({'extensions': {'ico': {}}})
    if 'ico' not in profile['extensions']:
        profile['extensions'].update({'ico': {}})
    profile['extensions']['ico'] = state
    s.update_account_profile(profile, account=donation_account)
コード例 #27
0
def create_json():
    user_json = {}
    for user in Account(username).export()["following"]:
        user_json[user] = {
            "upvote_weight": 100.0,
            "upvote_limit": 2,
            "upvote_count": 0
        }
    return user_json
コード例 #28
0
def addFollower(account_name, follower):
    print('addFollower', account_name, follower)
    res = tnt_server.call('add_follower', account_name, follower)
    if not res[0][0]:
        with suppress(Exception):
            followers = getFollowersWithDirection(Account(account_name))
            followers.append(follower)
            followers_space.insert((account_name, followers))
            tnt_server.call('add_follower', account_name, follower)
コード例 #29
0
ファイル: stream.py プロジェクト: mtastafford/runburgundy
def create_json():
    user_json = {}
    for user in Account("runburgundy").export()["following"]:
        user_json[user] = {
            "upvote_weight": 100.0,
            "upvote_limit": 2,
            "upvote_count": 0
        }
    print(user_json)
    return user_json
コード例 #30
0
def get_current_vp(username, steemd):
    account = Account(username, steemd_instance=steemd)
    last_vote_time = parse(account["last_vote_time"])
    diff_in_seconds = (datetime.utcnow() - last_vote_time).total_seconds()
    regenerated_vp = diff_in_seconds * 10000 / 86400 / 5
    total_vp = (account["voting_power"] + regenerated_vp) / 100
    if total_vp > 100:
        total_vp = 100

    return total_vp
コード例 #31
0
ファイル: main.py プロジェクト: DocBox12/Steem-transactions
def get_fill_vesting_withdraw():
    all_transactions = Account(steem_username, steem).get_account_history(
        -1,
        INT_steem_limit,
        filter_by='fill_vesting_withdraw',
        raw_output=True)

    for data in all_transactions:
        DICT_details = data[1]

        trx_id = DICT_details.get("trx_id")
        block = DICT_details.get("block")
        trx_in_block = DICT_details.get("trx_in_block")
        op_in_trx = DICT_details.get("op_in_trx")
        virtual_op = DICT_details.get("virtual_op")
        timestamp = DICT_details.get("timestamp")

        human_time = datetime.datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S')

        LIST_op = DICT_details.get("op")

        DICT_op = LIST_op[1]

        from_account = DICT_op.get("from_account")
        to_account = DICT_op.get("to_account")
        withdrawn = DICT_op.get("withdrawn")
        deposited = DICT_op.get("deposited")

        # Generate link to block

        link = "https://steemworld.org/block/" + str(block)

        filled = ""

        value = check_exists_transaction("fill_vesting_withdraw", human_time,
                                         "timestamp")

        if value is True:
            continue

        sql_insert = ("""
        
        INSERT INTO fill_vesting_withdraw (trx_id,	block, trx_in_block, op_in_trx, virtual_op,	timestamp, from_account, to_account, withdrawn, deposited, link, filled)
        VALUES("%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s", "%s");

        """) % (str(trx_id), str(block), str(trx_in_block), str(op_in_trx),
                str(virtual_op), str(human_time), str(from_account),
                str(to_account), str(withdrawn), str(deposited), str(link),
                str(filled))

        cursor.execute(sql_insert)
        mariadb_connection.commit()

    return