Example #1
0
def upvote_post(msg, user):
    link = str(msg.content).split(' ')[0]
    p = Post(link.split('@')[1])
    try:
        p.upvote(float(voting_power[msg.channel.id]), voter=user)
    except KeyError:
        p.upvote(float(voting_power['base']), voter=user)
Example #2
0
    def upvote(self, op):
        try:
            post = Post(op['memo'])
        except ValueError:
            logger.info('Invalid identifier: %s', op['memo'])
            self.refund(op, message='invalid url')
            return
        try:
            weight = self.upvote_weight

            post.upvote(weight=weight, voter=self.watch_account)

        except VotingInvalidOnArchivedPost as e:
            logger.info('Archived post. Cannot upvote. %s', op['memo'])
            self.refund(op,
                        message='Couldnt vote. Archived post. %s' % op['memo'])
            return
        except Exception as e:
            if 'already voted' in e.args[0]:
                self.refund(op, message='Already upvoted. %s' % op['memo'])
                logger.info('Already voted: %s. Skipping.', op['memo'])
                return

            if 'Read timed' in e.args[0]:
                logger.info('Node is not responding. Trying again to upvote.')
                return self.upvote(op)

        logger.info('Upvoted %s with weight: %s', op['memo'], weight)
Example #3
0
class User:
    def __init__(self, username, password, steem):
        self._username = username
        self._passwd = password
        self._steem = steem
        self._ipfsapi = get_ipfsapi()
        self._cur_post = None

    @staticmethod
    def get_videos_list(query):
        return get_chain_master().get_videos_list(query)

    @staticmethod
    def get_video_unauthorized(name, path):
        video_metadata = get_chain_master().get_video_metadata(name)
        multihash = video_metadata['multihash']
        get_ipfsapi().get_video(multihash, path)
        return video_metadata

    def get_video(self, name, path):
        video_metadata = User.get_video_unauthorized(name, path)
        self._cur_post = Post(
            {
                'author': video_metadata['author'],
                'permlink': video_metadata['name'],
            }, self._steem)
        return self._cur_post

    def add_video(self, name, path, description=None, miniature_url=None):
        description = description or 'No description'
        miniature_url = miniature_url or self.get_miniature_url(path)

        result = self._ipfsapi.add_video(path)
        get_chain_master().add_video(name, self._username, description,
                                     result['Hash'])
        self._steem.commit.post(title=name,
                                body=description + '\n' + miniature_url,
                                author=self._username,
                                permlink=name,
                                default_parent_permlink='video')

    def vote_video(self, type):
        if not self._cur_post:
            raise RuntimeError('There is no post to vote')

        if type == VoteType.UP_VOTE:
            return self._cur_post.upvote(self._username)

        return self._cur_post.downvote(self._username)

    def get_miniature_url(self, path):
        return 'https://static.tumblr.com/5cc5658c2c9cd06cfc68747c9059bd6f/i9ytv5i/szXn6nvfq/tumblr_static_tumblr_static__640.jpg'
Example #4
0
# go through list of beneficiaries and upvote them
for idx, votinglist in enumerate(rewardees):
    for acc in votinglist:
        account = Account(acc, s)
        posts = getUpvoteCandidate(account)
        # confirm number of comments made
        if len(posts) >= min_limit:
            selection = random.shuffle(posts)
            voted = 0
            votingon = 0
            # vote on comments
            while voted < num_upvotes:
                things = posts[votingon]
                votingon += 1
                P = Post(things, upvoter)
                # make sure not already voted on
                if not accountname in P['active_votes']:
                    try:
                        print('upvote: ' + str(things) + ' / ' +
                              str(Vote_Power[idx]) + '%... ',
                              end='',
                              flush=True)
                        P.upvote(Vote_Power[idx], accountname)
                        voted += 1
                        print('Success')
                        # sleep for 5 seconds, make sure we can vote again
                        time.sleep(5)
                    except Exception as e:
                        print("Error Voting: " + str(e))
Example #5
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")
Example #6
0
class Mechanism(Interface):
	"""This class covers the internal features of SteemiTAG.
	In particular, it connects Interface to the Steem libraries."""

	def __init__(self, authorsLiked, who, mainWin):

		self.authorsLiked = authorsLiked
		self.tagsLiked = ['polish']
		self.who = who

		self.b = Blockchain()
		self.stream = self.b.stream()
		self.mainWin = mainWin

	def localBool(self, x):

		if x is False:
			return x
		else:
			return True

	def machine(self, tagDefined=False, authorDefined=False):


		self.tagDefined = tagDefined
		self.authorDefined = authorDefined

		if not self.tagDefined and not self.authorDefined:
			pass

		else:
			next(self.yieldBlock())
			self.setTagFound = False
			if self.tagDefined:
				self.tagMachine()
			if self.block['type'] == 'comment' and self.block['parent_author'] == '' and (self.setTagFound == self.localBool(self.tagDefined)):
				if self.authorDefined:
					self.authorMachine('suppressed')
				else:
					self.suppressedVote()

			self.mainWin.after(100, lambda: self.machine(self.tagDefined, self.authorDefined))

	def yieldBlock(self):

		for self.block in self.stream:
			yield self.block

	def suppressedVote(self):

		with suppress(steembase.exceptions.PostDoesNotExist, steembase.exceptions.RPCError):
			self.unsuppressedVote()

	def unsuppressedVote(self):

		self.post = Post('@{}/{}'.format(self.block['author'], self.block['permlink']))
		self.up = self.post.upvote(voter=self.who)

	def authorMachine(self, mode):

		self.mode = mode
		self.atAuthor = '@{}'.format(self.block['author'])

		if self.atAuthor in self.authorsLiked:
			if self.mode == 'suppressed':
				self.suppressedVote()
			elif self.mode == 'unsuppressed':
				self.unsuppressedVote()

	def tagMachine(self):

		if 'json_metadata' in self.block and self.block['json_metadata'] != '':
			self.fullMeta = self.block['json_metadata']
			self.fullMeta = ast.literal_eval(self.fullMeta)

			if 'tags' in self.fullMeta:
				for one in self.tagsLiked:
					if one in self.fullMeta['tags']:
						self.setTagFound = True
						return self.setTagFound

	def tracedUsers(self):
		self.block = {}
		self.block['author'] = 'haiyangdeperci'
		self.block['permlink'] = 're-haiyangdeperci-oryginalna-sobota-1-lut-czarnego-prawa-besztany-20171006t210844114z'
		self.suppressedVote()
        print "- Posts pendentes de voto: "
        for post_unit in post_stack:
            url = post_unit[0]
            tempo = time.ctime(int(post_unit[1]))
            count += 1
            print "[%i] [%s] %s \n" % (count, tempo, url)

    for post_unit in post_stack:
        post_url = post_unit[0]
        post_timestamp = post_unit[1]

        if now >= post_timestamp:
            print "\nVotando no post %s" % post_url
            try:
                upvote = Post(post_url)
                upvote.upvote(weight=+5, voter=username)
                print "Enviando comentario no post..."
                upvote.reply(
                    body=
                    "Obrigado por postar! Esse coment&aacute;rio &eacute; o novo bot que dar&aacute; upvote 5% para todos os posts que usam a tag #pt. [Ainda n&atilde;o votou em mim como witness? Clique aqui e d&ecirc; o seu voto! &Eacute; r&aacute;pido!](https://app.steemconnect.com/sign/account-witness-vote?witness=tiagoferezin&approve=true)",
                    title="",
                    author=username)
                print "OK! Proximo...\n"
                post_stack.remove(post_unit)
            except:
                print "Esse post ja foi votado! Proximo...\n"
                post_stack.remove(post_unit)

    # Verifica se ha post diferente do anterior na query
    try:
        novo_post = s.get_discussions_by_created(query)
            reply_post = None

            # 대댓글 달기
            try:
                reply_post = Post('@' + reply[1]['op'][1]['author'] + '/' +
                                  reply[1]['op'][1]['permlink'])
            except Exception as e:
                pass

            while (True):
                try:
                    reply_post.reply(body="금손봇", author=acc_name)
                    break
                except Exception as e:
                    print(e)
                    time.sleep(17)

            # 보팅하기
            reply_post.upvote(10, acc_name)

            # 대댓글과 보팅한 댓글을 저장
            voted_permlink.insert(0, reply[1]['op'][1]['permlink'])

        # 확인 기록(past_seq_num) 갱신
        past_seq_num = recent_seq_num
        print(voted_permlink)

    # 적절한 휴식
    print(recent_seq_num, past_seq_num)
    time.sleep(3)
Example #9
0
query = {
    'author': 'steem-bot'
}

df_banned_posts = pd.DataFrame([x for x in raw_posts_col.find(query)])

print(df_banned_posts.shape)

# Refresh all posts, if hr1 in voters, unvote
counter = 0

for i in range(df_banned_posts.shape[0]):
    try:
        target = Post(df_banned_posts.iloc[i]['_id'], steemd_instance=steemd)
    except PostDoesNotExist:
        print('Doesnt exist:', df_banned_posts.iloc[i]['_id'])
        continue

    diff = datetime.utcnow() - target['created']
    voters = set()
    hr1_strength = [x['percent'] for x in target.active_votes if x['voter'] == 'hr1']

    if hr1_strength and hr1_strength[0] > 0 and diff < timedelta(days=7):
        target.upvote(-1, 'hr1')
        time.sleep(3)

        print(target['url'])
        counter += 1

print(counter)