def get_steem_account(username):
    username = normalize(username)

    steem_client = Steem()

    account = steem_client.get_account(username)

    return account
Exemple #2
0
class SteemHandler(object):
    def __init__(self):
        if settings.STEEM_NODES:
            self.steem = Steem(nodes=settings.STEEM_NODES)
        else:
            self.steem = Steem()

    def get_account(self, name):
        return self.steem.get_account(name)
def index(request):
    try:
        s = Steem(nodes=["https://api.steemit.com"])
        return HttpResponse(s.get_account(request.GET['a'])['post_count'],
                            content_type='text/plain')
    except:
        return HttpResponse(
            "To use this API call, please supply param a=accountname, substituting accountname with the account to see the account's total post and comments count\n\n"
            'Example: https://api.steem.place/getPostCount/?a=moisesmcardona\n\n'
            'Returns: account post count (posts and comments combined)',
            content_type='text/plain')
Exemple #4
0
def index(request):
    try:
        s = Steem(nodes=["https://api.steemit.com"])
        try:
            VP = s.get_account(request.GET['a'])['voting_power'] / 100
        except:
            VP = 0
        return HttpResponse(VP, content_type='text/plain')
    except:
        return HttpResponse(
            "To use this API call, please supply param a=accountname, substituting accountname with the account to see the account Voting Power.\n\n"
            'Example: https://api.steem.place/getVP/?a=moisesmcardona\n\n'
            'Returns: account Voting Power',
            content_type='text/plain')
Exemple #5
0
def index(request):
    try:
        s = Steem(nodes=["https://api.steemit.com"])
        try:
            created = s.get_account(request.GET['a'])['created']
        except:
            created = None
        return HttpResponse(created, content_type='text/plain')
    except:
        return HttpResponse(
            'To use this API call, please supply param a=accountname, substituting accountname with the account to see its creation date.\n\n'
            'Example: https://api.steem.place/getCreatedDate/?a=moisesmcardona\n\n'
            'Returns: Created date',
            content_type='text/plain')
def index(request):
    try:
        s = Steem(nodes=["https://api.steemit.com"])
        posting = s.get_account(request.GET['user'])
        for account in posting['posting']['account_auths']:
            if account[0] == request.GET['account']:
                return HttpResponse(True, content_type='text/plain')
        return HttpResponse(False, content_type='text/plain')
    except:
        return HttpResponse(
            'To use this API call, please supply param user=account username and account=account to check if authorized.\n\n'
            'Example: http://api.steem.place/checkApprovedAccounts/?user=moisesmcardona&account=steem.place\n\n'
            'Returns: True if user @moisesmcardona has authorized @steem.place',
            content_type='text/plain')
def index(request):
    try:
        s = Steem(nodes=["https://api.steemit.com"])
        try:
            balance = s.get_account(request.GET['a'])['balance']
        except:
            balance = '0.000 STEEM'
        return HttpResponse(balance, content_type='text/plain')
    except:
        return HttpResponse(
            "To use this API call, please supply param a=accountname, substituting accountname with the account to see the account STEEM Balance.\n\n"
            'Example: https://api.steem.place/getSTEEMBalance/?a=moisesmcardona\n\n'
            'Returns: account STEEM balance',
            content_type='text/plain')
Exemple #8
0
    def verify_key(self, name, key):
        s = Steem(keys=key)

        try:
            pubkey = PrivateKey(key).pubkey
            account = s.get_account(name)

            pubkey2 = account['posting']['key_auths'][0][0]

            if str(pubkey) != str(pubkey2):
                return False
            return True
        except Exception as e:
            print(9)
            print(e)
            return False
Exemple #9
0
def index(request):
    try:
        s = Steem(nodes=["https://api.steemit.com"])
        try:
            location = json.loads(
                s.get_account(
                    request.GET['a'])['json_metadata'])["profile"]["location"]
        except:
            location = 'N/A'
        return HttpResponse(location, content_type='text/plain')
    except:
        return HttpResponse(
            "To use this API call, please supply param a=accountname, substituting accountname with the account to see the account location based on what's typed in the profile.\n\n"
            'Example: https://api.steem.place/getLocation/?a=moisesmcardona\n\n'
            'Returns: account location information',
            content_type='text/plain')
Exemple #10
0
def x_verify_key(acctname, private_posting_key, mode):

    # Verify a Steemit Private Posting Key

    pubkey = 0
    acct = ""

    # Get a new instance of the Steemd node with the key to be tested

    try:
        steem = Steem(nodes, keys=[private_posting_key])
    except InvalidWifError as e:
        if mode != "quiet":
            print("Invalid key: " + str(e))
        return False

    # Convert the Private Posting Key into the Public Posting Key

    try:
        pubkey = PrivateKey(private_posting_key).pubkey
    except:
        if mode != "quiet":
            print("Bad private key")
        return False

    # Get the account for which the key is to be tested against

    try:
        acct = steem.get_account(acctname)
    except:
        if mode != "quiet":
            print("Could not connect to steemd")
        return False

    # Compare the Public Posting Keys with each other

    if acct:
        pubkey2 = acct['posting']['key_auths'][0][0]
    if str(pubkey) != str(pubkey2):
        if mode != "quiet":
            print("The private key and account name provided do not match.")
        return False
    else:
        if mode != "quiet":
            print("Private key is valid.")
        return True
Exemple #11
0
def index(request):
    try:
        s = Steem(nodes=["https://api.steemit.com"])
        try:
            account = s.get_account(request.GET['a'])
            votes = account["witness_votes"]
            votelist = ""
            for vote in votes:
                votelist += vote + ","
        except:
            votelist = ''
        return HttpResponse(votelist, content_type='text/plain')
    except:
        return HttpResponse(
            "To use this API call, please supply param a=accountname, substituting accountname with the account to see its Witness Votes.\n\n"
            'Example: https://api.steem.place/getWitnessVotes/?a=moisesmcardona\n\n'
            'Returns: Witnesses voted by account, separated by comma (,)',
            content_type='text/plain')
Exemple #12
0
    def get_object(self):
        username = self.kwargs.get('username')

        if username[0] == '@':
            username = username[1:]

        s = Steem(nodes=settings.STEEM_NODES)
        account_info = s.get_account(username)
        profile_image = None
        name = None
        cover_image = None

        if account_info:
            metadata = account_info.get('json_metadata')
            if metadata:
                metadata = json.loads(metadata)
                profile = metadata.get('profile')
                profile_image = profile.get('profile_image')
                name = profile.get('name')
                cover_image = profile.get('cover_image')

            account_dict = {
                'id': account_info.get('id'),
                'username': account_info.get('name'),
                'profile_image': profile_image,
                'name': name,
                'cover_image': cover_image,
                'created': parser.parse(account_info.get('created')),
                'post_count': account_info.get('post_count'),
                'voting_power': account_info.get('voting_power'),
                'curation_rewards': account_info.get('curation_rewards'),
                'posting_rewards': account_info.get('posting_rewards'),
                'reputation': account_info.get('reputation'),
            }
            return account_dict

        raise Http404
Exemple #13
0
    def verify(self, name, key):

        # Checks if the account exists, if the account does not exist in our system it checks if it really does exist
        # if the account does not exist on steem, ends, if it does exist it creates an account in our platform


        try:
            s = Steem(self.nodes[0])
            pubkey = PrivateKey(key).pubkey
            account = s.get_account(name)

            pubkey2 = account['posting']['key_auths'][0][0]

            if str(pubkey) != str(pubkey2):
                return False

        except Exception as e:
            print("here1")
            print("99")
            print(e)

            return False
        if not interpret.get_account_info(name, self.active_key, self.sending_account, self.memo_account,
                                          self.steem_node) is None:
            # account does exist on our platform. Next checks if the key for the account is correct
            if not self.verify_key(name, key):
                return False
            return True


        else:
            # checks if account exists on steem

            if not self.verify_key(name, key):
                return False
            interpret.start_account(name, self.active_key, self.memo_account, self.sending_account, self.steem_node)
        return True
def payout_rewards(sending_account,memo_account,active_key,node, account_reward= 0.45, del_reward = 0.44, owners = 0.03):
    # only pays out accounts active in the last 30 days.

    total_steem_owed = 0.01
    group_level_total = 0
    steem_levels = [0,0,0] # accounts with more than 1 steem owed, 0.1 steem and 0.01 steem
    # This is used to determine how much is paid out, if there isnt enough to pay everyone 0.01 they may not be paid in that session
    account_list = interpret.get_all_accounts(sending_account,memo_account,node)
    total_del = 0
    account_del_dict = {}
    # pulls all accounts and calculates the total amount of steem owed to them
    for account in account_list:
        try:

            account[2] = json.loads(account[2])
            steem_owed = account[2]["steem-owed"]

            total_steem_owed += steem_owed
            account_del_dict[account[2]["account"]] = 0

            # Levels to measure payout. Takes every account with a min owed balance
            # is used to check if paying everyone the min is possible
            if steem_owed > 1:
                steem_levels = [steem_levels[0] + 1, steem_levels[1] + 1, steem_levels[2] + 1]
            elif steem_owed > 0.1:
                steem_levels = [steem_levels[0], steem_levels[1] + 1, steem_levels[2] + 1]
            elif steem_owed > 0.01:
                steem_levels = [steem_levels[0], steem_levels[1], steem_levels[2] + 1]

            s = Steem(node=node)

            #account_del = float(s.get_vesting_delegations(account[2]["account"],sending_account,10000)["vesting_shares"].split(" VESTS")[0])
            thing = s.get_vesting_delegations(account[2]["account"],sending_account,1000)
            account_del = 0
            for i in thing:
                #print("account del", i["delegatee"], sending_account, float(i["vesting_shares"].split(" VESTS")[0]))
                if i["delegatee"] == sending_account:
                 #   print("here")
                    account_del += float(i["vesting_shares"].split(" VESTS")[0])
                    account_del_dict[account[2]["account"]] = account_del

                    #print(i)

            owner_total = 0
            for i in account[2]["groups"]:
                #print(i)
                if i[0] == "CI" and i[1] == 5:
                    owner_total += 1


            #print(account_del)
            account.append(account_del)
            account.append(owner_total)
            #print(account_del)
            group_level_total += owner_total
            total_del += account_del
        except Exception as e:
            print(e)
            pass



    # Gets total steem that can be paid currently from our account
    #print("here")
    s = Steem(node=node)
    total_steem = float(s.get_account(sending_account)["balance"].split(" STEEM")[0])
    #print(total_steem)


    # Measures if we are able to get every user at least 0.01 of their reward
    # if not no rewards are paid out, to save enough levels to pay everyone
    if total_steem * account_reward /0.05 < steem_levels[2]:
     #   print("RETURN", total_steem, account_reward, steem_levels[2])
        return
    #print("here1")
    reward_per_steem_owed = (total_steem * account_reward) / total_steem_owed

    # calculates total payout for each account out of the total and then sends it to that account
    for account in account_list:
      #  print("This")

        amount = reward_per_steem_owed * account[2]["steem-owed"]
        if amount > account[2]["steem-owed"]:
            amount = account[2]["steem-owed"]
       # print("here2")
        #print(total_del, group_level_total)
#        print(reward_per_steem_owed,account[2]["steem-owed"], del_reward * total_steem * account[4] / total_del)
 #       print(account)

        amount = round(amount,2)
        #print("here",amount)
        if amount > 0.01:
            print("first",amount, account)
            interpret.pay_account(amount,sending_account,memo_account,node,active_key,account[2])
        account_del = account_del_dict[account[2]["account"]]
        amount = del_reward * total_steem * account_del / total_del + account[5] * total_steem * owners/ group_level_total
        amount = round(amount, 2)
        #print(del_reward, total_steem, account_del, total_del, account[2]["account"])
        #print(amount, account)
        if amount > 0.01:
            interpret.pay_account(amount, sending_account, memo_account, node, active_key, account[2], True)
from pick import pick
from steem import Steem

import pprint

client = Steem()

#capture username
username = input('Username: '******'Invalid username')
    exit()

#capture list limit
limit = input('Max number of vesting delegations to display: ')

#list type
title = 'Please choose the type of list: '
options = ['Active Vesting Delegations', 'Expiring Vesting Delegations']

#get index and selected list name
option, index = pick(options, title)
print('\n' + 'List of ' + option + ': ' + '\n')

#parameters: account, from_account, limit
if option == 'Active Vesting Delegations':
    delegations = client.get_vesting_delegations(username, '', limit)
    if len(delegations) == 0:
Exemple #16
0
class Performer:
    log = logging.getLogger(__name__)

    def __init__(self, config, poster, priv_keys, on_complete):
        self.config = config
        self.poster = poster
        self.on_complete = on_complete
        self.steem = Steem(keys=priv_keys)
        self.last_posting = datetime.now() - POSTING_GUARD_TIME
        self.read_message_files()

    def read_message_files(self):
        with open(self.poster['message_file']) as f:
            message = f.readlines()
            self.message = [x.strip() for x in message]

    def is_busy(self):
        if (datetime.now() - self.last_posting) < POSTING_GUARD_TIME:
            return False
        return True

    def generate_warning_message(self, post):
        greet = ('Nice to meet you!' if post['reported_count'] <= 1 else
                 'We have met %s times already!' % post['reported_count'])
        lines = [
            random.choice(self.poster['photo']), '## Woff, woff!',
            '#### Hello @%s, %s' % (post['parent_author'], greet)
        ]
        lines.extend(self.message)
        return '\n'.join(lines)

    def process_warning(self, post):
        self.log.info("ID: %s, %s (%s)" %
                      (post['identifier'], post, post['bot_signal']))
        self.log.info("%s: %s/%s > %s" %
                      (post['root_title'], post['parent_author'],
                       post['author'], post['body']))
        result = True
        try:
            my_comment = self.steem.commit.post(
                title='guide puppy',
                body=self.generate_warning_message(post),
                author=self.poster['account'],
                permlink=None,
                reply_identifier=post['parent_post_id'],
                json_metadata=None,
                comment_options=None,
                community=None,
                tags=None,
                beneficiaries=None,
                self_vote=False)
            time.sleep(2)
            try:
                power = 100
                if self.steem.get_account('krguidedog')['voting_power'] < 5000:
                    power = 50
                my_comment = my_comment['operations'][0][1]
                post_id = '@%s/%s' % (my_comment['author'],
                                      my_comment['permlink'])
                self.steem.commit.vote(post_id, power, self.poster['account'])
            except:
                self.log.info('Failed to upvote!')
        except Exception as e:
            self.log.info(e)
            result = False

        self.on_complete({
            'result': result,
            'wait_for': 20,
            'poster': self,
            'post': post
        })

    def generate_praise_message(self, post):
        rt = [
            '멋진', '섹시한', '훈훈한', '시크한', '알흠다운', '황홀한', '끝내주는', '요염한', '흥분되는',
            '짱재밌는', '잊지못할', '감동적인', '배꼽잡는', '러블리한', '쏘쿨한'
        ]
        if post['bot_signal'] == '@칭찬해':
            msg = ('%s @%s님 안녕하세요! %s @%s님 소개로 왔어요. 칭찬이 아주 자자 하시더라구요!! '
                   '%s 글 올려주신것 너무 감사해요. 작은 선물로 0.2 SBD를 보내드립니다 ^^' %
                   (random.choice(rt), post['parent_author'],
                    random.choice(rt), post['author'], random.choice(rt)))
        elif post['bot_signal'] == '@축하해':
            msg = ('%s @%s님 안녕하세요! %s @%s님이 그러는데 정말 %s 일이 있으시다고 하더라구요!! '
                   '정말 축하드려요!! 기분좋은 날 맛좋은 개껌 하나 사드시라고 0.2 SBD를 보내드립니다 ^^' %
                   (random.choice(rt), post['parent_author'],
                    random.choice(rt), post['author'], random.choice(rt)))
        elif post['bot_signal'] == '@감사해':
            msg = (
                '%s @%s님 안녕하세요! %s @%s님이 너무너무 고마워 하셔서 저도 같이 감사드리려고 이렇게 왔어요!! '
                '%s 하루 보내시라고 0.2 SBD를 보내드립니다 ^^' %
                (random.choice(rt), post['parent_author'], random.choice(rt),
                 post['author'], random.choice(rt)))
        msg = ('<table><tr><td>%s</td><td>%s</td></tr></table>' %
               (random.choice(self.poster['praise_photo']), msg))
        return msg

    def transfer(self, send_to, amount, memo):
        retry = 2
        while retry:
            try:
                self.steem.commit.transfer(to=send_to,
                                           amount=amount,
                                           asset='SBD',
                                           account=self.poster['account'],
                                           memo=memo)
                self.log.info('Transferred %s to %s: %s' %
                              (amount, send_to, memo))
                break
            except:
                retry -= 1
                self.log.info('Failed to transfer %s to %s: %s' %
                              (amount, send_to, memo))

    def leave_praise(self, post):
        self.log.info("ID: %s, %s (%s)" %
                      (post['identifier'], post, post['bot_signal']))
        result = True
        try:
            my_comment = self.steem.commit.post(
                title='guide puppy',
                body=self.generate_praise_message(post),
                author=self.poster['account'],
                permlink=None,
                reply_identifier=post['parent_post_id'],
                json_metadata=None,
                comment_options=None,
                community=None,
                tags=None,
                beneficiaries=None,
                self_vote=False)
            self.transfer(
                post['parent_author'], 0.2,
                '@%s 님께서 가이드독 활동을 통해 모은 포인트로 감사의 표시를 하였습니다.'
                '해당 글을 확인해 주세요! https://steemit.com/%s' %
                (post['author'], post['parent_post_id']))
            # upvote for promotion
            try:
                my_comment = my_comment['operations'][0][1]
                post_id = '@%s/%s' % (my_comment['author'],
                                      my_comment['permlink'])
                self.steem.commit.vote(post_id, 20, self.poster['account'])
            except:
                self.log.info('Failed to upvote!')
            time.sleep(2)

        except Exception as e:
            self.log.info(e)
            result = False
        self.on_complete({
            'result': result,
            'wait_for': 20,
            'poster': self,
            'post': post
        })

    def send_no_point_alarm(self, post):
        try:
            memo = '가이드독 포인트가 부족합니다. 스팸글 신고를 통해 포인트를 쌓아주세요. 자세한 정보는 저의 계정을 방문하셔서 최신 글을 읽어주세요.'
            self.steem.commit.transfer(to=post['author'],
                                       amount=0.001,
                                       asset='SBD',
                                       account=self.poster['account'],
                                       memo=memo)
        except Exception as e:
            self.log.info(e)
        self.on_complete({
            'result': True,
            'wait_for': 1,
            'poster': self,
            'post': post
        })
        "description":
        "Steem Pay is a new initiative for stimulating on/offline commerce using Steem Dollar.",
        "link":
        "https://steemit.com/utopian-io/@asbear/steempay-0-3-0-release-supporting-seven-more-currencies-usd-eur-gbp-jpy-cny-php-myr"
    }, {
        "name":
        "Steemian Health Check",
        "description":
        "Steemian Health Check is a tool for better Steem community. The tool helps to figure out who is using their Steem Power fairly or who might be abusing his SP. @clayop and I spent quite a lot of hours on this project.",
        "link":
        "https://steemit.com/steemdev/@asbear/project-update-steemian-health-check"
    }, {
        "name":
        "Witness Insight",
        "description":
        "Witness Insight is designed to improve the transparency all across the Steem witnesses. This tool is helpful for the Steemians and witnesses who wants to vote to the best witnesses, and also for investors.",
        "link":
        "https://steemit.com/utopian-io/@asbear/transparency-wins-witness-insight-v0-3-1"
    }],
    "nodes_locations":
    nodes_location
}

s = Steem(keys=[witness_account_active_key])
account_profile = json.loads(s.get_account(account)['json_metadata'])
if not account_profile:
    account_profile = {}
account_profile['witness'] = witness_profile
print("Updating to: " + str(account_profile))
s.commit.update_account_profile(account_profile, witness_account)
    week_cutoff[1]) + "-" + str(week_cutoff[2] - 1)
last_week_start = time.localtime(
    time.mktime(time.localtime()) - 3600 * 24 * 7 * 2)

print("Week Start = " + str(last_week_start) + " and Week End = " +
      str(last_week_end))
day_cutoff = time.localtime(time.mktime(time.localtime()) - 3600 * 24)
dist_pattern = '\d*[\.]*\d*\ km'
dist_table = {}  #store daily, weekly, and monthly kms for users
dist_table['RB_TOTAL_WEEK'] = {
    "weekrun": 0,
    "weekbike": 0,
    "weekother": 0,
    "weekrelative": 0
}
claimable = s.get_account('runburgundy')["reward_sbd_balance"]
#claimable = 0.909
val_pattern = '\d*[\.]\d*'
rewards = re.search(val_pattern, claimable).group(0).split(' ')
rewards = float(rewards[0])
#rewards = float(0.909)

s.claim_reward_balance(account='runburgundy')

open(post_path, 'w').close()
postfile = open(post_path, 'a')
postfile.write("Run Burgundy - Decentralized Fitness Group - REWARD TIME!: " +
               str(today) + ".\n")  ### This line is the title of the post
postfile.write("running runburgundy fitnation fitness training\n"
               )  ### This line holds the tags
postfile.write(
Exemple #19
0
        return ("Invalid")        


while True:
    
       
    try:
            
        gen1= ac.get_account_history(-1,100,filter_by=['transfer','vote'])
        gen2= ac.get_account_history(-1,100,filter_by=['vote'])
    
        for k in gen2:
            if (k['voter'] == acc_name):
                prev_time = datetime.datetime.strptime(k['timestamp'], "%Y-%m-%dT%H:%M:%S")
                break
        tt = timedelta(seconds=20+(10000-s.get_account(acc_name)['voting_power'])*43.2)
        print ("Previous vote time",prev_time)
        print ("Next vote time", prev_time + tt)
    
        if (datetime.datetime.utcnow() - prev_time>tt):
        #if (s.get_account(acc_name)['voting_power']>=10000):
            print ("Upvoting: votelist,total=",votelist,total)
            upvote(votelist,total)
            curr_round = []
            votelist = []
            total = 0
            trxlist.reverse()
            trxlist = trxlist[0:100]                               
            print ("After upvoting: trxlist=",trxlist)
            %store last_round
            %store curr_round
Exemple #20
0
from steem import Steem
from dateutil.parser import parse
from datetime import datetime


def get_voting_power(account_data):
    last_vote_time = parse(account_data["last_vote_time"])
    diff_in_seconds = (datetime.utcnow() - last_vote_time).seconds
    regenerated_vp = diff_in_seconds * 10000 / 86400 / 5
    total_vp = (account_data["voting_power"] + regenerated_vp) / 100
    if total_vp > 100:
        return 100
    return "%.2f" % total_vp


s = Steem()
account = s.get_account('whoami')  # 계정명 입력
print(get_voting_power(account))
Exemple #21
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from steem import Steem
import sys
import json

ENCODING = sys.stdout.encoding if sys.stdout.encoding else 'utf-8'
s = Steem(nodes=["https://api.steemit.com"])
followers = s.get_account(sys.argv[1])
location = json.loads(followers["json_metadata"])
print(location["profile"]["location"])
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from steem import Steem
import sys

ENCODING = sys.stdout.encoding if sys.stdout.encoding else 'utf-8'
s = Steem(nodes=["https://api.steemit.com"])
balance = s.get_account(sys.argv[1])
print(balance["balance"])
Exemple #23
0
def save_memo(information, to, account_from, active_key, transaction_size=0.001, asset="SBD", node="wss://steemd-int.steemit.com",try_thing = [0,0]):
    # This should send a memo and return the position

    print("AAAAAAAAaa",information)
    try:
        if information["account"] != to:
            while True:
                print("THIS")
                try:
                    # under testing rn, ignore
                    break

                    print("here1")
                    s = Steem(node=node)
                    thing = s.get_account(information["account"])
                    print(thing)
                    print("here2")
                    save_memo(information,information["account"],account_from,active_key,node=node)
                    break
                except:
                    try_num += 1
                    if try_num >3:
                        break

    except:
        pass
    print("HERE")
    index = None
    try:
        # creates connection and sends the transaction, it then checks if it can find the memo on the blockchain.
        print(0)
        #node_connection = create_connection(node)
        print(1)
        s = Steem(node=node, keys=active_key)

        memo = json.dumps(information)
        print("MEMO THINF MADE")
        print(to, transaction_size, asset, account_from, memo)
        s.transfer(to,transaction_size,asset=asset,account=account_from, memo=memo)
        print(2)
        try_thing[0] = 0
    except Exception as e:
        print(6)
        print(e)
        print(try_thing)
        if try_thing[0] > 5:
            try_thing[0] = 0
            return False
        print(1222)
        return save_memo(information, to, account_from,active_key,transaction_size,asset,node, [try_thing[0] +1,try_thing[1]])
    time.sleep(3)
    while index == None or index == []:
        try:
            if type(information) == list:
              pass
            elif information["type"] == "account":
                index = retrieve(account=account_from, sent_to=to, recent=1, step=50, keyword=[["account",str(information["account"])], ["type","account"]],node=node)
            elif information["type"] == "post":
                index = retrieve(account=account_from, sent_to=to, recent=1, step=50, keyword=[["type","post"],["post_link",information["post_link"]]],node=node)
                print("index")
            elif information["type"] == "vote-link":



                index = retrieve(account=account_from, sent_to=to, recent=1, step=50, keyword=[["type","vote-link"],["account",information["account"]]],node=node)



        except Exception as e:
            print("EXCEPTTT")
            print(e)
        try_thing[1] += 1
        if try_thing[1] > 5:
            try_thing[1] = 0
            print("FALSE1")
            return False




    return index[0][0]
Exemple #24
0
while True:

    try:

        ac = steem.account.Account(acc_name, s)
        gen1 = ac.get_account_history(-1, 500, filter_by=['transfer'])
        gen2 = ac.get_account_history(-1, 500, filter_by=['vote'])

        for k in gen2:
            if (k['voter'] == acc_name):
                prev_time = datetime.datetime.strptime(k['timestamp'],
                                                       "%Y-%m-%dT%H:%M:%S")
                break
        tt = timedelta(
            seconds=30 +
            (10000 - s.get_account(acc_name)['voting_power']) * 43.2)
        print("Current Time: " + str(datetime.datetime.utcnow()) +
              "|Prev vote: " + str(prev_time) + "|Next Vote: " +
              str(prev_time + tt))

        for i in gen1:

            if (i['trx_id'] in trxlist):
                print("Breaking at TrxID: ", i['trx_id'])
                break

            if (i['to'] == acc_name):
                bidder = i['from']
                memo = i['memo']
                amt, curr = i['amount'].split(" ")
                amt = float(amt)
Exemple #25
0
class GuideDog:
    log = logging.getLogger(__name__)

    def __init__(self, config, db):
        self.config = config
        self.db = db
        keypath = os.path.expanduser(self.config['keyfile_path'])
        with open(keypath) as key_file:
            key_file_json = json.load(key_file)
            self.steem = Steem(keys=key_file_json['krguidedog'])

        self.message1 = readFile(self.config['guidedog']['mild_warning_file'])
        self.message2 = readFile(
            self.config['guidedog']['moderate_warning_file'])
        self.message3 = readFile(self.config['guidedog']['hard_warning_file'])
        self.copyright = readFile(self.config['guidedog']['copyright_file'])
        self.copyright_eng = readFile(
            self.config['guidedog']['copyright_file_eng'])

        self.last_daily_report = None
        self.daily_report_generator = Publisher(self.db)
        self.daily_report_timestamp = None

    def claim_reward(self):
        self.steem.claim_reward_balance(account='krguidedog')

    def reputation(self, number, precision=2):
        rep = int(number)
        if rep == 0:
            return 25
        score = max([math.log10(abs(rep)) - 9, 0]) * 9 + 25
        if rep < 0:
            score = 50 - score
        return round(score, precision)

    def create_post(self, post_id, body, author='krguidedog'):
        comment = self.steem.commit.post(title='',
                                         body=body,
                                         author=author,
                                         permlink=None,
                                         reply_identifier=post_id,
                                         json_metadata=None,
                                         comment_options=None,
                                         community=None,
                                         tags=None,
                                         beneficiaries=None,
                                         self_vote=False)
        post_item = comment['operations'][0][1]
        post_id = '@%s/%s' % (post_item['author'], post_item['permlink'])

        limit = 3
        while True:
            sleep(1)
            try:
                double_check = Post(post_id)
                return comment
            except Exception as e:
                limit -= 1
                if limit == 0:
                    raise 'Posting check failure'
                else:
                    self.log.info(
                        'Failed to confirm the post creation. retry ' + limit)

    def vote(self, post_id, power, voter):
        try:
            self.steem.commit.vote(post_id, power, voter)
            self.log.info('%s voted on %s with %s percentage' %
                          (voter, post_id, power))
        except Exception as e:
            self.log.info("Failed to vote: " + str(e))
            pass

    def transfer(self, send_to, amount, memo):
        try:
            self.steem.commit.transfer(
                to=send_to,
                amount=amount,
                asset='SBD',
                account=self.config['guidedog']['account'],
                memo=memo)
            self.log.info('Transferred %s to %s: %s' % (amount, send_to, memo))
        except Exception as e:
            self.log.info("Failed to transfer: " + str(e))
            raise

    def resteem(self, post_id, resteemer):
        try:
            self.steem.commit.resteem(post_id, resteemer)
            self.log.info('Resteemed %s by %s' % (post_id, resteemer))
        except Exception as e:
            self.log.info("Failed to resteem: " + str(e))
            pass

    def daily_report(self):
        last_daily_report = None
        try:
            with open("db/daily_report", "r") as f:
                last_daily_report = f.read().splitlines()[0]
        except:
            self.log.info('Failed to read daily_report file!!')
            return
        try:
            theday = datetime.now() - timedelta(days=1)
            if last_daily_report == theday.strftime("%d %b %Y"):
                # Already created until the last available day
                return
            newday = datetime.strptime(last_daily_report,
                                       "%d %b %Y") + timedelta(days=1)
            result = self.daily_report_generator.generate_report(
                newday.strftime("%d %b %Y"))
            if result == None:
                self.log.info('No activiey is found in ' +
                              newday.strftime("%d %b %Y"))
            else:
                self.log.info('Creating a daily report for ' +
                              newday.strftime("%d %b %Y"))
                comment_options = {
                    'max_accepted_payout': '0.000 SBD',
                    'percent_steem_dollars': 0,
                    'allow_votes': True,
                    'allow_curation_rewards': True,
                    'extensions': []
                }
                comment = self.steem.commit.post(title=result['title'],
                                                 body=result['body'],
                                                 author='krguidedog',
                                                 permlink=str(uuid.uuid4()),
                                                 reply_identifier=None,
                                                 json_metadata=None,
                                                 comment_options=None,
                                                 community=None,
                                                 tags='kr krguidedog antispam',
                                                 beneficiaries=None,
                                                 self_vote=False)

            # All succeeded. Update the last report day
            with open("db/daily_report", "w") as f:
                f.write(newday.strftime("%d %b %Y"))

        except Exception as e:
            self.log.info(e)
            self.log.info('Failed to create a daily report for ' +
                          newday.strftime("%d %b %Y"))
            #traceback.print_exc(file=sys.stdout)
            return

    def work(self):
        data = self.db.queue_get('post')
        if data:
            try:
                self.handle_post(data['data'])
                self.db.queue_finish('post', data)
            except Exception as e:
                self.log.error('Failed: post (will retry)')
                self.log.error(data)
                self.log.error(e)

        data = self.db.queue_get('vote')
        if data:
            try:
                self.log.info(data)
                voting = data['data']
                self.vote(voting['post_id'], voting['power'], voting['voter'])
                self.db.queue_finish('vote', data)
            except Exception as e:
                self.log.error('Failed: vote (will retry)')
                self.log.error(data)
                self.log.error(e)

        data = self.db.queue_get('transfer')
        if data:
            try:
                transfer = data['data']
                self.transfer(transfer['send_to'], transfer['amount'],
                              transfer['memo'])
                self.db.queue_finish('transfer', data)
            except Exception as e:
                self.log.error('Failed: transfer (will retry)')
                self.log.error(data)
                self.log.error(e)

        data = self.db.queue_get('resteem')
        if data:
            try:
                resteem = data['data']
                self.resteem(resteem['post_id'], resteem['resteemer'])
                self.db.queue_finish('resteem', data)
            except Exception as e:
                self.log.error('Failed: resteem (will retry)')
                self.log.error(data)
                self.log.error(e)

        self.daily_report()
        # Prevent wasting the donated funds
        #self.claim_reward()

    def handle_post(self, post):
        self.log.info(
            "New Command [%s -> %s -> %s] : %s" %
            (post['author'], post['bot_signal'], post['parent_author'], post))
        if post['signal_type'] == 'spam':
            if self.db.is_reported(post):
                self.log.info('Skip request: already reported')
                return
            rep = self.reputation(
                self.steem.get_account(post['author'])['reputation'])
            if rep < 35:
                self.log.info('Skip request: reputation is too low (%s, %s) ' %
                              (post['author'], rep))
                return

            self.process_spam(
                post,
                self.db.get_reported_count(post['parent_author']) + 1)

        elif post['signal_type'] == 'praise':
            if self.db.is_already_consumed_comment(post):
                self.log.info('Skip request: already consumed comment')
                return

            point = self.db.get_usable_point(post['author'])
            self.log.info('Praise request - user: %s point: %s' %
                          (post['author'], point))
            if post['author'] in self.config["praise_curator"]:
                self.leave_praise(post)
            elif point >= 1:
                self.leave_praise(post)
                self.db.use_point(post['author'], 1)
            else:
                self.log.info('Not enough point! %s %s' %
                              (post['author'], point))
                # self.send_no_point_alarm(post)
        elif post['signal_type'] == 'promote':
            if self.db.is_promoted(post):
                self.log.info('Skip request: already promoted')
                return

            point = self.db.get_usable_point(post['author'])
            self.log.info('Promote request - user: %s point: %s' %
                          (post['author'], point))
            if post['author'] in self.config["promote_curator"]:
                self.promote(post)
            elif point >= 1:
                self.promote(post)
                self.db.use_point(post['author'], 1)
            else:
                self.log.info('Not enough point! %s %s' %
                              (post['author'], point))
                self.send_no_point_alarm(post)
        elif post['signal_type'] == 'welcome':
            if post['author'] not in self.config["welcome_curator"]:
                self.log.info('Skip request: Not allowed user')
                return
            if self.db.is_welcomed(post):
                self.log.info('Skip request: already welcomed')
                return

            rep = self.reputation(
                self.steem.get_account(post['parent_author'])['reputation'])
            if rep > 50:
                self.log.info(
                    'Skip request: reputation is too high (%s, %s) ' %
                    (post['parent_author'], rep))
                return
            self.log.info('Welcome %s (%s)!' % (post['parent_author'], rep))
            self.welcome(post)
        else:
            pass

    def generate_warning_message(self, post, reported_count):
        if post['bot_signal'] == "@저작권안내":
            greet = ('저작권 안내입니다.' if reported_count <= 1 else '%s 번째 안내입니다.' %
                     reported_count)
            greet_eng = ('this is the %s copyright warning.' %
                         ordinal(reported_count))
            lines = [
                'https://i.imgur.com/2PPRCJq.png',
                '#### Hey @%s, %s' % (post['parent_author'], greet_eng)
            ]
            lines.extend(self.copyright_eng)
            lines.append('---')
            lines.append('#### 안녕하세요 @%s님, %s' %
                         (post['parent_author'], greet))
            lines.extend(self.copyright)
            return '\n'.join(lines)
        else:
            if reported_count <= 5:
                greet = ('Nice to meet you!' if reported_count <= 1 else
                         'We have met %s times already!' % reported_count)
                lines = [
                    sys_random.choice(self.config['guidedog']['mild_photo']),
                    '## Woff, woff!',
                    '#### Hello @%s, %s' % (post['parent_author'], greet)
                ]
                lines.extend(self.message1)
                return '\n'.join(lines)
            elif reported_count <= 10:
                greet = ('We have met %s times already!' % reported_count)
                lines = [
                    sys_random.choice(
                        self.config['guidedog']['moderate_photo']),
                    '#### Hello @%s, %s' % (post['parent_author'], greet)
                ]
                lines.extend(self.message2)
                return '\n'.join(lines)
            else:
                greet = ('We have met %s times already!' % reported_count)
                lines = [
                    sys_random.choice(self.config['guidedog']['hard_photo']),
                    '#### Hey @%s, %s' % (post['parent_author'], greet)
                ]
                lines.extend(self.message3)
                return '\n'.join(lines)

    def vote_on_post(self, post, supporters):
        post = post['operations'][0][1]
        self.supporters_vote(post['author'], post['permlink'], supporters)

    def supporters_vote(self, author, permlink, supporters):
        votes = self.steem.get_active_votes(author, permlink)
        voters = set()
        for vote in votes:
            voters.add(vote['voter'])

        for supporter in supporters:
            # Skip already voted supporters
            if not supporter['account'] in voters:
                voting_power = self.steem.get_account(
                    supporter['account'])['voting_power']
                if voting_power > supporter['voteOver']:
                    self.db.queue_push(
                        'vote', {
                            'power': supporter['weight'],
                            'post_id': '@%s/%s' % (author, permlink),
                            'voter': supporter['account']
                        })
            else:
                self.log.info('%s already voted' % supporter)

    def process_spam(self, post, reported_count):
        my_comment = self.create_post(
            post['parent_post_id'],
            self.generate_warning_message(post, reported_count))
        self.db.store_report(post)
        self.vote_on_post(my_comment, self.config['spam_supporters'])
        if reported_count > 10:
            self.supporters_vote(post['parent_author'],
                                 post['parent_permlink'],
                                 self.config['spam_downvoters'])

    def generate_benefit_message(self, post):
        reward = "0.4 SBD"
        rt = [
            '멋진', '섹시한', '훈훈한', '시크한', '알흠다운', '황홀한', '끝내주는', '요염한', '흥분되는',
            '짱재밌는', '잊지못할', '감동적인', '배꼽잡는', '러블리한', '쏘쿨한', '분위기있는'
        ]
        pet = sys_random.choice(self.config['guidedog']['pets'])
        pet_name = '<a href="/%s">%s</a>' % (pet['parent'], pet['name'])
        pet_photo = sys_random.choice(pet['photo'])
        if post['bot_signal'] == '@칭찬해':
            msg = (
                '%s @%s님 안녕하세요! %s 입니다. %s @%s님 소개로 왔어요. 칭찬이 아주 자자 하시더라구요!! '
                '%s 글 올려주신것 너무 감사해요. 작은 선물로 %s를 보내드립니다 ^^' %
                (sys_random.choice(rt), post['parent_author'], pet_name,
                 sys_random.choice(rt), post['author'], sys_random.choice(rt),
                 reward))
        elif post['bot_signal'] == '@축하해':
            msg = (
                ('%s @%s님 안녕하세요! %s 입니다. %s @%s님이 그러는데 정말 %s 일이 있으시다고 하더라구요!! '
                 '정말 축하드려요!! 기분좋은 날 맛좋은 ' +
                 sys_random.choice(['개껌 하나', '개밥 한그릇', '개뼈다구 하나']) +
                 ' 사드시라고 %s를 보내드립니다 ^^') %
                (sys_random.choice(rt), post['parent_author'], pet_name,
                 sys_random.choice(rt), post['author'], sys_random.choice(rt),
                 reward))
        elif post['bot_signal'] == '@감사해':
            msg = (
                '%s @%s님 안녕하세요! %s 입니다. %s @%s님이 너무너무 고마워 하셔서 저도 같이 감사드리려고 이렇게 왔어요!! '
                '%s 하루 보내시라고 %s를 보내드립니다 ^^' %
                (sys_random.choice(rt), post['parent_author'], pet_name,
                 sys_random.choice(rt), post['author'], sys_random.choice(rt),
                 reward))
        elif post['bot_signal'] == '@위로해':
            msg = (
                ('@%s님 안녕하세요. %s 입니다. @%s께 이야기 다 들었습니다. ' + sys_random.choice(
                    ['세상사 다 그런것 아닐까요?. ', '인생지사 새옹지마라고 하잖아요. ']) +
                 '힘든일이 있으면 반드시 좋은일도 있대요! 기운 내시라고 %s를 보내드립니다.') %
                (post['parent_author'], pet_name, post['author'], reward))
        elif post['bot_signal'] == '@홍보해':
            msg = ((
                '@%s님 안녕하세요. %s 입니다. @%s님이 이 글을 너무 좋아하셔서, 저에게 홍보를 부탁 하셨습니다.' +
                ' 이 글은 @krguidedog에 의하여 리스팀 되었으며, 가이드독 서포터들로부터 보팅을 받으셨습니다. 축하드립니다!'
            ) % (
                post['parent_author'],
                pet_name,
                post['author'],
            ))
        msg = ('<table><tr><td>%s</td><td>%s</td></tr></table>' %
               (pet_photo, msg))
        return msg

    def leave_praise(self, post):
        my_comment = self.create_post(post['parent_post_id'],
                                      self.generate_benefit_message(post))
        self.db.store_praise(post)
        self.vote_on_post(my_comment, self.config['praise_supporters'])

        # Push transfer to queue
        self.db.queue_push(
            'transfer', {
                'send_to':
                post['parent_author'],
                'amount':
                0.4,
                'memo':
                '@%s 님께서 가이드독 활동을 통해 모은 포인트로 감사의 표시를 하였습니다.'
                '해당 글을 확인해 주세요! https://steemit.com/%s' %
                (post['author'], post['parent_post_id'])
            })

    def promote(self, post):
        my_comment = self.create_post(post['parent_post_id'],
                                      self.generate_benefit_message(post))
        self.db.store_promote(post)
        self.vote_on_post(my_comment, self.config['praise_supporters'])
        self.db.queue_push(
            'resteem', {
                'post_id': post['parent_post_id'],
                'resteemer': self.config['guidedog']['account']
            })
        self.supporters_vote(post['parent_author'], post['parent_permlink'],
                             self.config['promotion_supporters'])

    def welcome(self, post):
        # Message
        message = [
            "### @%s님 스팀잇에 오신것을 환영합니다!" % post['parent_author'],
            "스팀잇 정착을 도와드리기 위하여 @%s님의 부탁을 받고 찾아온 @easysteemit 입니다. 힘찬 출발을 응원하는 의미로 서포터 보팅을 해드립니다."
            % post['author'], "", "### [이지스팀잇]",
            "@easysteemit은 처음에는 낮설고 복잡해 보일수 있는 스팀잇을 더욱 쉽게 접할수 있도록 만들어진 스팀잇 안내서입니다. @easysteemit 을 팔로우하시고 필요한 것들을 하나하나 익혀보세요! 스팀잇 활동이 더욱 더 즐거워질거에요 :)",
            "",
            "<a href='/@easysteemit'><img src='https://steemitimages.com/300x0/https://steemitimages.com/DQmZmqw2L61Rrnvy92WAH5xSnn3Ud1ZcMJWWFcff141DPqV/daemoon.png'></a>"
        ]
        # Process
        my_comment = self.create_post(post['parent_post_id'],
                                      '\n'.join(message), 'easysteemit')
        self.db.store_welcome(post)
        self.supporters_vote(post['parent_author'], post['parent_permlink'],
                             self.config['welcome_supporters'])

    def send_no_point_alarm(self, post):
        memo = '가이드독 포인트가 부족합니다. 스팸글 신고를 통해 포인트를 쌓아주세요. 자세한 정보는 다음 링크에서 확인해 주세요. https://steemit.com/kr/@asbear/33kqka-kr'
        self.db.queue_push('transfer', {
            'send_to': post['author'],
            'amount': 0.001,
            'memo': memo
        })
Exemple #26
0
import datetime
import os
from steem import Steem

# grab config vars
steemPostingKey = os.environ.get('steemPostingKey')
steemAccountName = os.environ.get('steemAccountName')

s = Steem()
sbd = s.get_account(steemAccountName)['sbd_balance']
print(sbd)
Exemple #27
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from steem import Steem
import sys

ENCODING = sys.stdout.encoding if sys.stdout.encoding else 'utf-8'
s = Steem(nodes=["https://api.steemit.com"])
account = s.get_account(sys.argv[1])
votes = account["witness_votes"]
votelist = ""
for vote in votes:
    votelist += vote + ","
print(votelist)
Exemple #28
0
from steem import Steem
s = Steem()

# variables
ACCOUNT_NAME = 'jjb777'

# start code
print(s.get_account(ACCOUNT_NAME))


from steem import Steem
import sys
import math
from dateutil import parser
import datetime

account_name = sys.argv[1]
s = Steem()
account_info = s.get_account(account_name)

# for key, value in account_info.items():
# 	print('----------')
# 	print(key)
# 	print(value)

post_count = account_info['post_count']
voting_power = account_info['voting_power']
reputation = account_info['reputation']
last_post_date = account_info['last_root_post']

reputation = (math.log10(int(reputation))-9)*9+25
voting_power = int(voting_power)/100
last_post_date = parser.parse(last_post_date)
time_since_last_post = datetime.datetime.now() - last_post_date
days_since_last_post = time_since_last_post.days

display_message = '''
Username: \t{}
Reputation:\t{}
=============================
Total Posts:\t{}
Exemple #30
0
from steem import Steem
import sys

account_name = sys.argv[1]
s = Steem()
balance = s.get_account(account_name)['sbd_balance']
print(balance)