Beispiel #1
0
    def upvote_winner(self, winner):
        winning_post = Post(winner, steem_instance=self.steem)
        winning_post.upvote(voter=self.voter)
        self.upvoted_winners.append(winner)
        print('winning post: {}'.format(winner))

        # cannot post two consecutive votes less than 3 seconds apart
        time.sleep(3)
Beispiel #2
0
 def test_getPost(self):
     self.assertEqual(
         Post("@xeroc/piston", steem_instance=steem).url,
         "/piston/@xeroc/piston")
     self.assertEqual(
         Post({
             "author": "@xeroc",
             "permlink": "piston"
         },
              steem_instance=steem).url, "/piston/@xeroc/piston")
Beispiel #3
0
    def upvote_winners(self, winners):
        for winner in winners:
            if len(self.upvoted_winners) < self.vote_limit:
                winning_post = Post(winner)
                winning_post.upvote(voter=self.mongo_steem.steem_client.voter)
                self.upvoted_winners.append(winner)
                print('winning post: {}'.format(winner))

                # cannot post two consecutive votes less than 3 seconds apart
                time.sleep(3)
Beispiel #4
0
    def comment(self, comment):
        """ Update or create comment """
        post = Post(comment, steem_instance=self.rpc)

        try:
            if post.is_comment():
                self.upgrade_comment(post)
            else:
                if post.parent_permlink == APP_FETCH_FROM:
                    self.upgrade_post(post)

        except PostDoesNotExist:
            pass
        except BannedAccount:
            logger.warning('banned account %s' % post.author)
Beispiel #5
0
 def refresh(self):
     state = self.steem.rpc.get_state("/@%s/blog" % self.name)
     posts = state["accounts"].get(self.name, {}).get("blog", [])
     r = []
     for p in posts:
         post = state["content"][p]
         r.append(Post(post, steem_instance=self.steem))
     super(Blog, self).__init__(r)
Beispiel #6
0
    def stream_posts_from_mongo(self, query=None, limit=None):
        if query is None:
            query = {}
        post_query = self.db.posts.find(query)
        if limit:
            post_query = post_query.limit(limit)
        try:
            for post_data in post_query:
                yield Post(post_data['identifier'], steem_instance=self.steem)

        except Exception as e:
            print(e)
Beispiel #7
0
    def all(self):
        self.current_index = Account(
            self.name, steem_instance=self.steem).virtual_op_count()

        # prevent duplicates
        self.seen_items = set()

        while True:
            # fetch the next batch
            if self.current_index == 0:
                raise StopIteration

            limit = 1000
            if self.current_index < 1000:
                # avoid duplicates on last batch
                limit = 1000 - self.current_index
                self.current_index = 1000

            h = self.steem.rpc.get_account_history(self.name,
                                                   self.current_index,
                                                   limit,
                                                   api='database_api')
            if not h:
                raise StopIteration

            self.current_index -= 1000

            # filter out irrelevant items
            def blogpost_only(item):
                op_type, op = item[1]['op']
                return op_type == 'comment' and not is_comment(op)

            hist = filter(blogpost_only, h)
            hist = map(lambda x: x[1]['op'][1], hist)
            hist = [x for x in hist if x['author'] == self.name]

            # filter out items that have been already passed on
            # this is necessary because post edits create multiple entries in the chain
            hist_uniq = []
            for item in hist:
                if item['permlink'] not in self.seen_items:
                    self.seen_items.add(item['permlink'])
                    hist_uniq.append(item)

            for p in hist_uniq:
                yield Post(p, steem_instance=self.steem)
Beispiel #8
0
def getUpvoteCandidate():
    """ Gets link to post/comment author has not voted on but is within voting window
    Args:
        account: A Steem Account object.
        s      : SteemInstance
    Returns:
        identifier of posts/comments within voting window not already voted on
    """
    # Make sure we have the latest data
    account.refresh()
    epoch_last_vote = 0
    
    # Get last 2000 votes from account
    history = account.history2(filter_by='comment', take=2000)

    current_time = epochDiff()
    oldest_id = []
    
    for event in history:
        # Not really needed due to filter
        if(event['type'] == 'comment'):
            # Double confirmation of comment
            if event['permlink'].startswith("re-"):
                # Make sure we are the author
                if(event['author'] == accountname):
                    epoch_last_vote = epochVote(event)
                    elapsed_time = current_time - epoch_last_vote
                    # Is post in within time limit
                    if elapsed_time < cutofftime:
                        # Get comment info
                        identifier = "@" + event['author'] + "/" + event['permlink']
                        postid = Post(identifier,s)
                        # If we haven't already voted, add to list
                        if accountname not in postid['active_votes']:
                            oldest_id.append(identifier)
                        
    print(oldest_id)
    return oldest_id
Beispiel #9
0
myfile = open('author_rewards.csv', 'w')
wr = csv.writer(myfile, delimiter=';')
wr.writerow(['date', 'reward', 'btc', 'eur', 'post'])

i = 10000000
while i > 1:
    a = Account(user, s)
    tx = a.rawhistory(i, 1000)
    tx = list(tx)

    for ndx, member in enumerate(tx):
        i = member[0] - 1
        if member[1]['op'][0] == 'author_reward':
            id = '@' + member[1]['op'][1]['author'] + '/' + member[1]['op'][1][
                'permlink']
            p = Post(id, s)
            reward = float(str(p.reward)[:-4])
            post = p.export()
            dt = post['last_payout']
            unixtime = time.mktime(dt.timetuple())
            value = datetime.datetime.fromtimestamp(unixtime)
            year = int(value.strftime('%Y'))
            month = int(value.strftime('%m'))
            date = value.strftime('%Y-%m-%d')
            if year < lastyear:
                myfile.close()
                sys.exit('DONE')

            if year != skipyear:
                btc = round(reward / avg[date], 8)
                euros = round(reward / eur[date], 3)
Beispiel #10
0
 def __init__(self, *args, **kwargs):
     super(Testcases, self).__init__(*args, **kwargs)
     self.post = Post(identifier, steem_instance=steem)
Beispiel #11
0
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)
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_upvote(self):
        try:
            self.post.upvote(voter=testaccount)
        except VotingInvalidOnArchivedPost:
            pass
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_downvote(self, weight=-100, voter=testaccount):
        try:
            self.post.downvote(voter=testaccount)
        except VotingInvalidOnArchivedPost:
            pass
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_edit(self):
        try:
            steem.edit(identifier, "Foobar")
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_post(self):
        try:
            steem.post("title",
                       "body",
                       meta={"foo": "bar"},
                       author=testaccount)
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_create_account(self):
        try:
            steem.create_account("xeroc-create",
                                 creator=testaccount,
                                 password="******",
                                 storekeys=False)
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_transfer(self):
        try:
            steem.transfer("fabian", 10, "STEEM", account=testaccount)
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_withdraw_vesting(self):
        try:
            steem.withdraw_vesting(10, account=testaccount)
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_transfer_to_vesting(self):
        try:
            steem.transfer_to_vesting(10, to=testaccount, account=testaccount)
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_get_replies(self):
        steem.get_replies(author=testaccount)

    def test_get_posts(self):
        steem.get_posts()

    def test_get_categories(self):
        steem.get_categories(sort="trending")

    def test_get_balances(self):
        steem.get_balances(testaccount)

    def test_getPost(self):
        self.assertEqual(
            Post("@xeroc/piston", steem_instance=steem).url,
            "/piston/@xeroc/piston")
        self.assertEqual(
            Post({
                "author": "@xeroc",
                "permlink": "piston"
            },
                 steem_instance=steem).url, "/piston/@xeroc/piston")
Beispiel #12
0
 def __init__(self, *args, **kwargs):
     super(Testcases, self).__init__(*args, **kwargs)
     self.post = Post(identifier, steem_instance=steem)
Beispiel #13
0
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)
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_upvote(self):
        try:
            self.post.upvote(voter=testaccount)
        except VotingInvalidOnArchivedPost:
            pass
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_downvote(self, weight=-100, voter=testaccount):
        try:
            self.post.downvote(voter=testaccount)
        except VotingInvalidOnArchivedPost:
            pass
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_edit(self):
        try:
            steem.edit(identifier, "Foobar")
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_post(self):
        try:
            steem.post("title", "body", meta={"foo": "bar"}, author=testaccount)
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_create_account(self):
        try:
            steem.create_account("xeroc-create",
                                 creator=testaccount,
                                 password="******",
                                 storekeys=False
                                 )
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_transfer(self):
        try:
            steem.transfer("fabian", 10, "STEEM", account=testaccount)
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_withdraw_vesting(self):
        try:
            steem.withdraw_vesting(10, account=testaccount)
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_transfer_to_vesting(self):
        try:
            steem.transfer_to_vesting(10, to=testaccount, account=testaccount)
        except InsufficientAuthorityError:
            pass
        except MissingKeyError:
            pass

    def test_get_replies(self):
        steem.get_replies(author=testaccount)

    def test_get_posts(self):
        steem.get_posts()

    def test_get_balances(self):
        steem.get_balances(testaccount)

    def test_getPost(self):
        self.assertEqual(Post("@xeroc/piston", steem_instance=steem).url,
                         "/piston/@xeroc/piston")
        self.assertEqual(Post({"author": "@xeroc", "permlink": "piston"}, steem_instance=steem).url,
                         "/piston/@xeroc/piston")
Beispiel #14
0
def upvote_reply(params, author):
    """
    upvote and reply the post
    :param dict the parameters (same with initialize_params), including:
                config<dict>:     configurations loaded from file 'confi'
                steem<Steem>:     the steem instance which contains private kyes
                manager<Manager>: the multi-thread manager
                tz<timezone>:     the time zone instance
                massage<dict>:    the replied messages, where keys are supported locales and 
                                                           values are the message in different languages
                cners<dict>:      snapshot of all CN users and queue of undetected users
                posts<dict>:      snapshot of all posts and queue of un-upvoted posts
                upvote<Value>:    number of upvotes today
    :param dict the author's information, see: https://uploadbeta.com/api/steemit/wechat/?cache
    """
    if params['posts']['queue'].empty():
        return
    pst = params['posts']['queue'].get()
    # Restore the serialized version to original
    for k, v in pst.items():
        if type(v) is str and v.startswith('my_serialized_datetime'):
            value = v.split('=')[-1]
            if _debug:
                assert value.isdigit()
            pst[k] = datetime.fromtimestamp(int(value))
        elif type(v) is str and v.startswith('my_serialized_boolean'):
            value = v.split('=')[-1]
            if _debug:
                assert value in ['True', 'False']
            pst[k] = v.split('=')[-1] == 'True'
        pass  # elif - if
    pass  # for k, v in pst.items()
    db = params['config']['database']
    cnx = mysql.connector.connect(user=db['user'], password=params['keys']['dbkey'], \
                                  host='127.0.0.1', database=db['name'])
    cursor = cnx.cursor()
    try:
        post = Post(pst, steem_instance=params['steem'])
        # Up-vote operation here
        post_urls = list(params['posts']['snapshot'])
        if _debug:
            assert len(post_urls) == len(list(
                set(post_urls))) and pst['url'] in post_urls
        pass  # if _debug
        n = params['upvoted'].value
        vote_weight = 100 * (0.1 if n == 0 else 0.1 * (1.001**(2 * n - 3)))
        params['upvoted'] = params['manager'].Value('i', n + 1)
        if _debug:
            fp = open('console.log', 'a')
            log = '%3d: %.8f - %s' % (n, vote_weight, pst['author'])
            print(log)
            fp.write(log + '\n')
            fp.close()
        pass  # if _debug
        if _release:
            post.upvote(weight=vote_weight, voter=params['config']['me'])
        pass  # if _release
        sql = 'INSERT INTO upvote_upvote (author, post_url, post_time, vote_sp, vote_weight, vote_power, vote_time)\
                                  VALUES (\'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\');'                                                                                                    % \
                                         (pst['author'], pst['url'], pst['created'].strftime('%Y-%m-%d %H:%M:%S'), \
                             author['sp'], vote_weight, author['vp'], pst['upvote_time'].strftime('%Y-%m-%d %H:%M:%S'))
        cursor.execute(sql)
        cnx.commit()
        if _debug:
            fp = open('console.log', 'a')
            print(sql)
            fp.write(sql + '\n')
            fp.close()
        pass  # if _debug

        # Replay operation here
        # TODO: cnbuddy - reply message is improper
        msg = params['message']['zh_CN']
        #         if _release:
        #             post.reply(msg, author=params['config']['me'])
        #         pass # if _release
        reply_time = datetime.now(params['tz'])
        sql = 'INSERT INTO upvote_reply (root_url, parent_author, parent_link, body, reply_time) \
                                 VALUES (\'%s\',\' %s\', \'%s\', \'%s\', \'%s\');'                                                                                   % \
                                (pst['url'], pst['author'], pst['url'], msg, reply_time.strftime('%Y-%m-%d %H:%M:%S'))
        cursor.execute(sql)
        cnx.commit()
        if _debug:
            fp = open('console.log', 'a')
            print(sql)
            fp.write(sql + '\n')
            fp.close()
        pass  # if _debug

        if _debug:
            fp = open('console.log', 'a')
            log = 'upvote_reply<%s>: %s--%s' % (datetime.now(
                params['tz']), pst['author'], pst['url'])
            print(log)
            fp.write(log + '\n')
            fp.close()
            fp = open('posts.log', 'a')
            fp.write('%s\n' % pst['url'])
            fp.close()
        pass  # if _debug
    except:
        pass
    pass  # try - except

    cnx.close()