コード例 #1
0
    def test_comment_dict(self):
        bts = self.bts
        title = ''
        cnt = 0
        while title == '' and cnt < 5:
            c = Comment({
                'author': self.author,
                'permlink': self.permlink
            },
                        steem_instance=bts)
            c.refresh()
            title = c.title
            cnt += 1
            if title == '':
                c.steem.rpc.next()
                c.refresh()
                title = c.title

        self.assertEqual(c.author, self.author)
        self.assertEqual(c.permlink, self.permlink)
        self.assertEqual(c.authorperm, self.authorperm)
        self.assertEqual(c.category, self.category)
        self.assertEqual(c.parent_author, '')
        self.assertEqual(c.parent_permlink, self.category)
        self.assertEqual(c.title, self.title)
コード例 #2
0
 def test_comment_dict(self, node_param):
     if node_param == "non_appbase":
         bts = self.bts
     else:
         bts = self.appbase
     c = Comment({
         'author': self.author,
         'permlink': self.permlink
     },
                 steem_instance=bts)
     c.refresh()
     self.assertEqual(c.author, self.author)
     self.assertEqual(c.permlink, self.permlink)
     self.assertEqual(c.authorperm, self.authorperm)
     self.assertEqual(c.category, self.category)
     self.assertEqual(c.parent_author, '')
     self.assertEqual(c.parent_permlink, self.category)
     self.assertEqual(c.title, self.title)
コード例 #3
0
 def test_comment(self):
     bts = self.bts
     with self.assertRaises(exceptions.ContentDoesNotExistsException):
         Comment("@abcdef/abcdef", steem_instance=bts)
     title = ''
     cnt = 0
     while title == '' and cnt < 5:
         c = Comment(self.authorperm, steem_instance=bts)
         title = c.title
         cnt += 1
         if title == '':
             c.blockchain.rpc.next()
             c.refresh()
             title = c.title
     self.assertTrue(isinstance(c.id, int))
     self.assertTrue(c.id > 0)
     self.assertEqual(c.author, self.author)
     self.assertEqual(c.permlink, self.permlink)
     self.assertEqual(c.authorperm, self.authorperm)
     # self.assertEqual(c.category, self.category)
     self.assertEqual(c.parent_author, '')
     # self.assertEqual(c.parent_permlink, self.category)
     # self.assertEqual(c.title, self.title)
     self.assertTrue(len(c.body) > 0)
     self.assertTrue(isinstance(c.json_metadata, dict))
     self.assertTrue(c.is_main_post())
     self.assertFalse(c.is_comment())
     if c.is_pending():
         self.assertFalse(
             (c.time_elapsed().total_seconds() / 60 / 60 / 24) > 7.0)
     else:
         self.assertTrue(
             (c.time_elapsed().total_seconds() / 60 / 60 / 24) > 7.0)
     # self.assertTrue(isinstance(c.get_reblogged_by(), list))
     # self.assertTrue(len(c.get_reblogged_by()) > 0)
     votes = c.get_votes()
     self.assertTrue(isinstance(votes, list))
     self.assertTrue(len(votes) > 0)
     self.assertTrue(isinstance(votes[0], Vote))
コード例 #4
0
ファイル: test_comment.py プロジェクト: vogel76/beem
    def test_comment_dict(self, api):
        bts = self.bts
        title = ''
        cnt = 0
        while title == '' and cnt < 5:
            c = Comment({
                'author': self.author,
                'permlink': self.permlink
            },
                        api=api,
                        blockchain_instance=bts)
            c.refresh()
            title = c.title
            cnt += 1
            if title == '':
                c.blockchain.rpc.next()
                c.refresh()
                title = c.title

        self.assertEqual(c.author, self.author)
        self.assertEqual(c.permlink, self.permlink)
        self.assertEqual(c.authorperm, self.authorperm)
        # self.assertEqual(c.category, self.category)
        self.assertEqual(c.parent_author, '')
コード例 #5
0
                else:
                    ops = accountTrx[account["name"]].get_newest(
                        oldest_timestamp, op_types=["comment"], limit=50)
                blog = []
                posts = []
                for op in ops[::-1]:
                    try:
                        comment = (json.loads(op["op_dict"]))
                        created = formatTimeString(comment["timestamp"])
                    except:
                        op_dict = op["op_dict"]
                        comment = json.loads(op_dict[:op_dict.find("body") -
                                                     3] + '}')
                    try:
                        comment = Comment(comment, steem_instance=stm)
                        comment.refresh()
                        created = comment["created"]
                    except:
                        continue
                    if comment.is_pending():
                        continue
                    if comment["author"] != account["name"]:
                        continue

                    if comment["parent_author"] == "" and created > addTzInfo(
                            last_paid_post):
                        print("add post %s" % comment["authorperm"])
                        blog.append(comment["authorperm"])
                    elif comment["parent_author"] != "" and created > addTzInfo(
                            last_paid_comment):
                        print("add comment %s" % comment["authorperm"])
コード例 #6
0
                voter = "steembasicincome"

            if nobroadcast and voter is not None:
                print(c["authorperm"])
                print("Comment Vote %s from %s with %.2f %%" %
                      (author, voter, vote_percentage))
            elif voter is not None:
                print("Comment Upvote %s from %s with %.2f %%" %
                      (author, voter, vote_percentage))
                vote_sucessfull = False
                cnt = 0
                while not vote_sucessfull and cnt < 5:
                    try:
                        c.upvote(vote_percentage, voter=voter)
                        time.sleep(4)
                        c.refresh()
                        for v in c["active_votes"]:
                            if voter == v["voter"]:
                                vote_sucessfull = True
                    except:
                        time.sleep(4)
                        if cnt > 0:
                            c.steem.rpc.next()
                        print("retry to vote %s" % c["authorperm"])
                    cnt += 1
                if vote_sucessfull:
                    upvote_counter[author] += 1
                postTrx.update_voted(author, created, vote_sucessfull)
        else:
            highest_pct = 0
            voter = None
コード例 #7
0
    def run(self, start_block, stop_block):
        self.hive.wallet.unlock(self.config["wallet_password"])
        self.blockchain = Blockchain(mode='head',
                                     blockchain_instance=self.hive)
        current_block = self.blockchain.get_current_block_num()
        if stop_block is None or stop_block > current_block:
            stop_block = current_block

        if start_block is None:
            start_block = current_block
            last_block_num = current_block - 1
        else:
            last_block_num = start_block - 1

        self.log_data["start_block_num"] = start_block
        for op in self.blockchain.stream(start=start_block,
                                         stop=stop_block,
                                         opNames=["comment"]):
            self.log_data = print_block_log(self.log_data, op,
                                            self.config["print_log_at_block"])
            last_block_num = op["block_num"]

            if op["type"] == "comment":
                token = None

                for key in self.token_config:
                    if op["body"].find(
                            self.token_config[key]["comment_command"]) >= 0:
                        token = key
                if token is None:
                    continue
                if op["author"] == self.token_config[token]["token_account"]:
                    continue
                cnt = 0
                c_comment = None
                c_parent = None
                authorperm = construct_authorperm(op)
                use_tags_api = True
                while c_comment is None and cnt < 10:
                    cnt += 1
                    try:
                        c_comment = Comment(authorperm,
                                            use_tags_api=use_tags_api,
                                            blockchain_instance=self.hive)
                        c_comment.refresh()
                    except:
                        if cnt > 5:
                            use_tags_api = False
                        nodelist = NodeList()
                        nodelist.update_nodes()
                        self.hive = Hive(node=nodelist.get_hive_nodes(),
                                         num_retries=5,
                                         call_num_retries=3,
                                         timeout=15)
                        time.sleep(3)
                if cnt == 10 or c_comment is None:
                    logger.warn("Could not read %s/%s" %
                                (op["author"], op["permlink"]))
                    continue
                if 'depth' in c_comment:
                    if c_comment['depth'] == 0:
                        continue
                else:
                    if c_comment["parent_author"] == '':
                        continue

                if abs((c_comment["created"] -
                        op['timestamp']).total_seconds()) > 9.0:
                    logger.warn("Skip %s, as edited" % c_comment["authorperm"])
                    continue

                already_voted = False
                if self.token_config[token]["upvote_token_receiver"]:
                    parent_identifier = construct_authorperm(
                        c_comment["parent_author"],
                        c_comment["parent_permlink"])
                    c_parent = Comment(parent_identifier,
                                       blockchain_instance=self.hive)
                    for v in c_parent.get_votes(raw_data=True):
                        if self.token_config[token]["token_account"] == v[
                                "voter"]:
                            already_voted = True
                else:
                    for v in c_comment.get_votes(raw_data=True):
                        if self.token_config[token]["token_account"] == v[
                                "voter"]:
                            already_voted = True
                if already_voted:
                    continue

                already_replied = None
                cnt = 0
                if self.token_config[token]["usage_upvote_percentage"] == 0:

                    while already_replied is None and cnt < 5:
                        cnt += 1
                        try:
                            already_replied = False
                            for r in c_comment.get_all_replies():
                                if r["author"] == self.token_config[token][
                                        "token_account"]:
                                    already_replied = True
                        except:
                            already_replied = None
                            self.hive.rpc.next()
                    if already_replied is None:
                        already_replied = False
                        for r in c_comment.get_all_replies():
                            if r["author"] == self.token_config[token][
                                    "token_account"]:
                                already_replied = True

                    if already_replied:
                        continue

                muting_acc = Account(self.token_config[token]["token_account"],
                                     blockchain_instance=self.hive)
                blocked_accounts = muting_acc.get_mutings()
                if c_comment["author"] in blocked_accounts:
                    logger.info("%s is blocked" % c_comment["author"])
                    continue

                # Load bot token balance
                bot_wallet = Wallet(self.token_config[token]["token_account"],
                                    blockchain_instance=self.hive)
                symbol = bot_wallet.get_token(
                    self.token_config[token]["symbol"])

                # parse amount when user_can_specify_amount is true
                amount = self.token_config[token]["default_amount"]
                if self.token_config[token]["user_can_specify_amount"]:
                    start_index = c_comment["body"].find(
                        self.token_config[token]["comment_command"])
                    stop_index = c_comment["body"][start_index:].find("\n")
                    if stop_index >= 0:
                        command = c_comment["body"][start_index +
                                                    1:start_index + stop_index]
                    else:
                        command = c_comment["body"][start_index + 1:]

                    command_args = command.replace('  ', ' ').split(" ")[1:]

                    if len(command_args) > 0:
                        try:
                            amount = float(command_args[0])
                        except Exception as e:
                            exc_type, exc_obj, exc_tb = sys.exc_info()
                            fname = os.path.split(
                                exc_tb.tb_frame.f_code.co_filename)[1]
                            logger.warn("%s - %s - %s" %
                                        (str(exc_type), str(fname),
                                         str(exc_tb.tb_lineno)))
                            logger.info("Could not parse amount")
                    if self.token_config[token][
                            "maximum_amount_per_comment"] and amount > self.token_config[
                                token]["maximum_amount_per_comment"]:
                        amount = self.token_config[token][
                            "maximum_amount_per_comment"]

                if not self.config["no_broadcast"] and self.hive.wallet.locked(
                ):
                    self.hive.wallet.unlock(self.config["wallet_password"])

                self.log_data["new_commands"] += 1
                wallet = Wallet(c_comment["author"],
                                blockchain_instance=self.hive)
                token_in_wallet = wallet.get_token(
                    self.token_config[token]["symbol"])
                balance = 0
                if token_in_wallet is not None:
                    logger.info(token_in_wallet)
                    if self.token_config[token]["count_only_staked_token"]:
                        balance = 0
                    else:
                        balance = float(token_in_wallet["balance"])
                    if "stake" in token_in_wallet:
                        balance += float(token_in_wallet['stake'])
                    if 'delegationsIn' in token_in_wallet and float(
                            token_in_wallet['delegationsIn']) > 0:
                        balance += float(token_in_wallet['delegationsIn'])
                    if 'pendingUnstake' in token_in_wallet and float(
                            token_in_wallet['pendingUnstake']) > 0:
                        balance += float(token_in_wallet['pendingUnstake'])

                    if balance > self.token_config[token][
                            "min_token_in_wallet"]:
                        if self.token_config[token][
                                "token_in_wallet_for_each_outgoing_token"] > 0:
                            max_token_to_give = int(
                                balance / self.token_config[token]
                                ["token_in_wallet_for_each_outgoing_token"])
                        else:
                            max_token_to_give = self.token_config[token][
                                "maximum_amount_per_comment"]
                    else:
                        max_token_to_give = 0
                else:
                    max_token_to_give = 0
                logger.info("token to give for %s: %f" %
                            (c_comment["author"], max_token_to_give))

                db_data = read_data(self.data_file)
                if "accounts" in db_data and c_comment["author"] in db_data[
                        "accounts"] and token in db_data["accounts"][
                            c_comment["author"]]:
                    if db_data["accounts"][c_comment["author"]][token][
                            "last_date"] == date.today(
                            ) and self.token_config[token][
                                "token_in_wallet_for_each_outgoing_token"] > 0:
                        max_token_to_give = max_token_to_give - db_data[
                            "accounts"][c_comment["author"]][token]["amount"]

                if amount > max_token_to_give:
                    amount = max_token_to_give
                if amount > self.token_config[token][
                        "maximum_amount_per_comment"]:
                    amount = self.token_config[token][
                        "maximum_amount_per_comment"]

                if token_in_wallet is None or balance < self.token_config[
                        token]["min_token_in_wallet"]:
                    reply_body = self.token_config[token]["fail_reply_body"]
                elif max_token_to_give < 1:
                    reply_body = self.token_config[token][
                        "no_token_left_for_today"]
                elif c_comment["parent_author"] == c_comment["author"]:
                    reply_body = "You cannot sent token to yourself."
                elif float(symbol["balance"]) < amount:
                    reply_body = self.token_config[token]["no_token_left_body"]
                else:
                    if "{}" in self.token_config[token]["sucess_reply_body"]:
                        reply_body = (self.token_config[token]
                                      ["sucess_reply_body"]).format(
                                          c_comment["parent_author"])
                    else:
                        reply_body = self.token_config[token][
                            "sucess_reply_body"]
                    if "{}" in self.token_config[token]["token_memo"]:
                        token_memo = (
                            self.token_config[token]["token_memo"]).format(
                                c_comment["author"])
                    else:
                        token_memo = self.token_config[token]["token_memo"]

                    sendwallet = Wallet(
                        self.token_config[token]["token_account"],
                        blockchain_instance=self.hive)

                    try:
                        logger.info(
                            "Sending %.2f %s to %s" %
                            (amount, self.token_config[token]["symbol"],
                             c_comment["parent_author"]))
                        sendwallet.transfer(c_comment["parent_author"], amount,
                                            self.token_config[token]["symbol"],
                                            token_memo)

                        if "accounts" in db_data:
                            accounts = db_data["accounts"]
                        else:
                            accounts = {}
                        if c_comment["author"] not in accounts:
                            accounts[c_comment["author"]] = {}
                            accounts[c_comment["author"]][token] = {
                                "last_date": date.today(),
                                "n_comments": 1,
                                "amount": amount
                            }
                        elif token not in accounts[c_comment["author"]]:
                            accounts[c_comment["author"]][token] = {
                                "last_date": date.today(),
                                "n_comments": 1,
                                "amount": amount
                            }
                        else:
                            if accounts[c_comment["author"]][token][
                                    "last_date"] < date.today():
                                accounts[c_comment["author"]][token] = {
                                    "last_date": date.today(),
                                    "n_comments": 1,
                                    "amount": amount
                                }
                            else:
                                accounts[c_comment["author"]][token][
                                    "n_comments"] += 1
                                accounts[c_comment["author"]][token][
                                    "amount"] += amount

                        store_data(self.data_file, "accounts", accounts)
                        logger.info(
                            "%s - %s" %
                            (c_comment["author"],
                             str(accounts[c_comment["author"]][token])))

                    except Exception as e:
                        exc_type, exc_obj, exc_tb = sys.exc_info()
                        fname = os.path.split(
                            exc_tb.tb_frame.f_code.co_filename)[1]
                        logger.warn(
                            "%s - %s - %s" %
                            (str(exc_type), str(fname), str(exc_tb.tb_lineno)))
                        logger.warn("Could not send %s token" %
                                    self.token_config[token]["symbol"])
                        continue

                reply_identifier = construct_authorperm(
                    c_comment["parent_author"], c_comment["parent_permlink"])
                if self.config["no_broadcast"]:
                    logger.info("%s" % reply_body)
                else:
                    try:
                        self.hive.post(
                            "",
                            reply_body,
                            author=self.token_config[token]["token_account"],
                            reply_identifier=reply_identifier)
                        if self.token_config[token][
                                "usage_upvote_percentage"] <= 0:
                            time.sleep(5)
                            self.hive.post(
                                "",
                                "Command accepted!",
                                author=self.token_config[token]
                                ["token_account"],
                                reply_identifier=c_comment["authorperm"])
                    except Exception as e:
                        exc_type, exc_obj, exc_tb = sys.exc_info()
                        fname = os.path.split(
                            exc_tb.tb_frame.f_code.co_filename)[1]
                        logger.warn(
                            "%s - %s - %s" %
                            (str(exc_type), str(fname), str(exc_tb.tb_lineno)))
                        logger.warn("Could not reply to post")
                        continue
                    if self.token_config[token]["usage_upvote_percentage"] > 0:
                        time.sleep(5)
                        upvote_percentge = self.token_config[token][
                            "usage_upvote_percentage"]
                        if self.token_config[token]["scale_upvote_weight"]:
                            upvote_percentge = upvote_percentge * amount / self.token_config[
                                token]["maximum_amount_per_comment"]
                        print("Upvote with %.2f %%" % upvote_percentge)
                        if self.token_config[token]["upvote_token_receiver"]:
                            if c_parent is None:
                                c_parent = Comment(
                                    parent_identifier,
                                    blockchain_instance=self.hive)
                            try:
                                c_parent.upvote(upvote_percentge,
                                                voter=self.token_config[token]
                                                ["token_account"])
                            except Exception as e:
                                exc_type, exc_obj, exc_tb = sys.exc_info()
                                fname = os.path.split(
                                    exc_tb.tb_frame.f_code.co_filename)[1]
                                logger.warn("%s - %s - %s" %
                                            (str(exc_type), str(fname),
                                             str(exc_tb.tb_lineno)))
                                logger.warn("Could not upvote comment")
                        else:
                            try:
                                c_comment.upvote(upvote_percentge,
                                                 voter=self.token_config[token]
                                                 ["token_account"])
                            except Exception as e:
                                exc_type, exc_obj, exc_tb = sys.exc_info()
                                fname = os.path.split(
                                    exc_tb.tb_frame.f_code.co_filename)[1]
                                logger.warn("%s - %s - %s" %
                                            (str(exc_type), str(fname),
                                             str(exc_tb.tb_lineno)))
                                logger.warn("Could not upvote comment")

                time.sleep(4)
        return last_block_num
コード例 #8
0
    def run(self, start_block):
        self.stm.wallet.unlock(self.config["wallet_password"])
        self.blockchain = Blockchain(mode='head', steem_instance=self.stm)
        stop_block = self.blockchain.get_current_block_num()

        if start_block is not None:
            last_block_num = start_block - 1
        self.log_data["start_block_num"] = start_block
        for op in self.blockchain.stream(start=start_block,
                                         stop=stop_block,
                                         opNames=["comment"],
                                         max_batch_size=50):
            self.log_data = print_block_log(self.log_data, op,
                                            self.config["print_log_at_block"])
            last_block_num = op["block_num"]

            if op["type"] == "comment":
                token = None

                for key in self.token_config:
                    if op["body"].find(
                            self.token_config[key]["comment_command"]) >= 0:
                        token = key
                if token is None:
                    continue
                if op["author"] == self.token_config[token]["token_account"]:
                    continue

                try:
                    c_comment = Comment(op, steem_instance=self.stm)
                    c_comment.refresh()
                except:
                    logger.warn("Could not read %s/%s" %
                                (op["author"], op["permlink"]))
                    continue
                if c_comment.is_main_post():
                    continue
                if abs((c_comment["created"] -
                        op['timestamp']).total_seconds()) > 9.0:
                    logger.warn("Skip %s, as edited" % c_comment["authorperm"])
                    continue
                already_replied = False
                for r in c_comment.get_all_replies():
                    if r["author"] == self.token_config[token][
                            "token_account"]:
                        already_replied = True
                if already_replied:
                    continue

                muting_acc = Account(self.token_config[token]["token_account"],
                                     steem_instance=self.stm)
                blocked_accounts = muting_acc.get_mutings()
                if c_comment["author"] in blocked_accounts:
                    logger.info("%s is blocked" % c_comment["author"])
                    continue

                # Load bot token balance
                bot_wallet = Wallet(self.token_config[token]["token_account"],
                                    steem_instance=self.stm)
                symbol = bot_wallet.get_token(
                    self.token_config[token]["symbol"])

                # parse amount when user_can_specify_amount is true
                amount = self.token_config[token]["default_amount"]
                if self.token_config[token]["user_can_specify_amount"]:
                    start_index = c_comment["body"].find(
                        self.token_config[token]["comment_command"])
                    stop_index = c_comment["body"][start_index:].find("\n")
                    if stop_index >= 0:
                        command = c_comment["body"][start_index +
                                                    1:start_index + stop_index]
                    else:
                        command = c_comment["body"][start_index + 1:]

                    command_args = command.replace('  ', ' ').split(" ")[1:]

                    if len(command_args) > 0:
                        try:
                            amount = float(command_args[0])
                        except Exception as e:
                            exc_type, exc_obj, exc_tb = sys.exc_info()
                            fname = os.path.split(
                                exc_tb.tb_frame.f_code.co_filename)[1]
                            logger.warn("%s - %s - %s" %
                                        (str(exc_type), str(fname),
                                         str(exc_tb.tb_lineno)))
                            logger.info("Could not parse amount")
                    if self.token_config[token][
                            "maximum_amount_per_comment"] and amount > self.token_config[
                                token]["maximum_amount_per_comment"]:
                        amount = self.token_config[token][
                            "maximum_amount_per_comment"]

                if not self.config["no_broadcast"] and self.stm.wallet.locked(
                ):
                    self.stm.wallet.unlock(self.config["wallet_password"])

                self.log_data["new_commands"] += 1
                wallet = Wallet(c_comment["author"], steem_instance=self.stm)
                token_in_wallet = wallet.get_token(
                    self.token_config[token]["symbol"])
                if token_in_wallet is not None:
                    balance = float(token_in_wallet["balance"])
                    if "stake" in token_in_wallet:
                        balance += float(token_in_wallet['stake'])
                    if 'delegationsIn' in token_in_wallet and float(
                            token_in_wallet['delegationsIn']) > 0:
                        balance += float(token_in_wallet['delegationsIn'])
                    if 'pendingUnstake' in token_in_wallet and float(
                            token_in_wallet['pendingUnstake']) > 0:
                        balance += float(token_in_wallet['pendingUnstake'])

                    if balance > self.token_config[token][
                            "min_token_in_wallet"]:
                        if self.token_config[token][
                                "token_in_wallet_for_each_outgoing_token"] > 0:
                            max_token_to_give = int(
                                balance / self.token_config[token]
                                ["token_in_wallet_for_each_outgoing_token"])
                        else:
                            max_token_to_give = self.token_config[token][
                                "maximum_amount_per_comment"]
                    else:
                        max_token_to_give = 0
                else:
                    max_token_to_give = 0

                db_data = read_data(self.data_file)
                if "accounts" in db_data and c_comment["author"] in db_data[
                        "accounts"] and token in db_data["accounts"][
                            c_comment["author"]]:
                    if db_data["accounts"][c_comment["author"]][token][
                            "last_date"] == date.today(
                            ) and self.token_config[token][
                                "token_in_wallet_for_each_outgoing_token"] > 0:
                        max_token_to_give = max_token_to_give - db_data[
                            "accounts"][c_comment["author"]][token]["amount"]

                if amount > max_token_to_give:
                    amount = max_token_to_give
                if amount > self.token_config[token][
                        "maximum_amount_per_comment"]:
                    amount = self.token_config[token][
                        "maximum_amount_per_comment"]

                if token_in_wallet is None or float(
                        token_in_wallet["balance"]
                ) < self.token_config[token]["min_token_in_wallet"]:
                    reply_body = self.token_config[token]["fail_reply_body"]
                elif max_token_to_give < 1:
                    reply_body = self.token_config[token][
                        "no_token_left_for_today"]
                elif c_comment["parent_author"] == c_comment["author"]:
                    reply_body = "You cannot sent token to yourself."
                elif float(symbol["balance"]) < amount:
                    reply_body = self.token_config[token]["no_token_left_body"]
                else:
                    if "{}" in self.token_config[token]["sucess_reply_body"]:
                        reply_body = (self.token_config[token]
                                      ["sucess_reply_body"]).format(
                                          c_comment["parent_author"])
                    else:
                        reply_body = self.token_config[token][
                            "sucess_reply_body"]
                    if "{}" in self.token_config[token]["token_memo"]:
                        token_memo = (
                            self.token_config[token]["token_memo"]).format(
                                c_comment["author"])
                    else:
                        token_memo = self.token_config[token]["token_memo"]

                    sendwallet = Wallet(
                        self.token_config[token]["token_account"],
                        steem_instance=self.stm)

                    try:
                        logger.info(
                            "Sending %.2f %s to %s" %
                            (amount, self.token_config[token]["symbol"],
                             c_comment["parent_author"]))
                        sendwallet.transfer(c_comment["parent_author"], amount,
                                            self.token_config[token]["symbol"],
                                            token_memo)

                        if "accounts" in db_data:
                            accounts = db_data["accounts"]
                        else:
                            accounts = {}
                        if c_comment["author"] not in accounts:
                            accounts[c_comment["author"]] = {}
                            accounts[c_comment["author"]][token] = {
                                "last_date": date.today(),
                                "n_comments": 1,
                                "amount": amount
                            }
                        elif token not in accounts[c_comment["author"]]:
                            accounts[c_comment["author"]][token] = {
                                "last_date": date.today(),
                                "n_comments": 1,
                                "amount": amount
                            }
                        else:
                            if accounts[c_comment["author"]][token][
                                    "last_date"] < date.today():
                                accounts[c_comment["author"]][token] = {
                                    "last_date": date.today(),
                                    "n_comments": 1,
                                    "amount": amount
                                }
                            else:
                                accounts[c_comment["author"]][token][
                                    "n_comments"] += 1
                                accounts[c_comment["author"]][token][
                                    "amount"] += amount

                        store_data(self.data_file, "accounts", accounts)
                        logger.info(
                            "%s - %s" %
                            (c_comment["author"],
                             str(accounts[c_comment["author"]][token])))

                    except Exception as e:
                        exc_type, exc_obj, exc_tb = sys.exc_info()
                        fname = os.path.split(
                            exc_tb.tb_frame.f_code.co_filename)[1]
                        logger.warn(
                            "%s - %s - %s" %
                            (str(exc_type), str(fname), str(exc_tb.tb_lineno)))
                        logger.warn("Could not send %s token" %
                                    self.token_config[token]["symbol"])
                        continue

                reply_identifier = construct_authorperm(
                    c_comment["parent_author"], c_comment["parent_permlink"])
                if self.config["no_broadcast"]:
                    logger.info("%s" % reply_body)
                else:
                    try:
                        self.stm.post(
                            "",
                            reply_body,
                            author=self.token_config[token]["token_account"],
                            reply_identifier=reply_identifier)
                    except Exception as e:
                        exc_type, exc_obj, exc_tb = sys.exc_info()
                        fname = os.path.split(
                            exc_tb.tb_frame.f_code.co_filename)[1]
                        logger.warn(
                            "%s - %s - %s" %
                            (str(exc_type), str(fname), str(exc_tb.tb_lineno)))
                        logger.warn("Could not reply to post")
                        continue
                    if self.token_config[token]["usage_upvote_percentage"] > 0:
                        try:
                            c_comment.upvote(self.token_config[token]
                                             ["usage_upvote_percentage"],
                                             voter=self.token_config[token]
                                             ["token_account"])
                        except Exception as e:
                            exc_type, exc_obj, exc_tb = sys.exc_info()
                            fname = os.path.split(
                                exc_tb.tb_frame.f_code.co_filename)[1]
                            logger.warn("%s - %s - %s" %
                                        (str(exc_type), str(fname),
                                         str(exc_tb.tb_lineno)))
                            logger.warn("Could not upvote comment")

                time.sleep(4)
        return last_block_num
コード例 #9
0
    def run(self, start_block):
        self.stm.wallet.unlock(self.config["wallet_password"])  
        self.blockchain = Blockchain(mode='head', steem_instance=self.stm)
        stop_block = self.blockchain.get_current_block_num()

        if start_block is not None:
            last_block_num = start_block - 1
        self.log_data["start_block_num"] = start_block
        for op in self.blockchain.stream(start=start_block, stop=stop_block, opNames=["comment"],  max_batch_size=50):
            self.log_data = print_block_log(self.log_data, op, self.config["print_log_at_block"])
            last_block_num = op["block_num"]
            
            if op["type"] == "comment":
                token = None
                
                for key in self.token_config:
                    if op["body"].find(self.token_config[key]["comment_command"]) >= 0:
                        token = key
                if token is None:
                    continue
                if op["author"] == self.token_config[token]["scot_account"]:
                    continue

                try:
                    c_comment = Comment(op, steem_instance=self.stm)
                    c_comment.refresh()
                except:
                    logger.warn("Could not read %s/%s" % (op["author"], op["permlink"]))
                    continue
                if c_comment.is_main_post():
                    continue
                if abs((c_comment["created"] - op['timestamp']).total_seconds()) > 9.0:
                    logger.warn("Skip %s, as edited" % c_comment["authorperm"])
                    continue
                already_replied = False
                for r in c_comment.get_all_replies():
                    if r["author"] == self.token_config[token]["scot_account"]:
                        already_replied = True
                if already_replied:
                    continue
                # Load scot token balance
                scot_wallet = Wallet(self.token_config[token]["scot_account"], steem_instance=self.stm)
                scot_token = scot_wallet.get_token(self.token_config[token]["scot_token"])

                # parse amount when user_can_specify_amount is true
                amount = self.token_config[token]["maximum_amount"]
                if self.token_config[token]["user_can_specify_amount"]:
                    start_index = c_comment["body"].find(self.token_config[token]["comment_command"])
                    stop_index = c_comment["body"][start_index:].find("\n")
                    if stop_index >= 0:
                        command = c_comment["body"][start_index + 1:start_index + stop_index]
                    else:
                        command = c_comment["body"][start_index + 1:]
                        
                    command_args = command.replace('  ', ' ').split(" ")[1:]          
                    
                    if len(command_args) > 0:
                        try:
                            amount = float(command_args[0])
                        except Exception as e:
                            exc_type, exc_obj, exc_tb = sys.exc_info()
                            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                            logger.warn("%s - %s - %s" % (str(exc_type), str(fname), str(exc_tb.tb_lineno)))                        
                            logger.info("Could not parse amount")
                
                if not self.config["no_broadcast"] and self.stm.wallet.locked():
                    self.stm.wallet.unlock(self.config["wallet_password"])                
                
                self.log_data["new_commands"] += 1
                wallet = Wallet(c_comment["author"], steem_instance=self.stm)
                token_in_wallet = wallet.get_token(self.token_config[token]["scot_token"])
                if token_in_wallet is None or float(token_in_wallet["balance"]) < self.token_config[token]["min_staked_token"]:
                    reply_body = self.token_config[token]["fail_reply_body"]
                elif c_comment["parent_author"] == c_comment["author"]:
                    reply_body = "You cannot sent token to yourself."
                elif float(scot_token["balance"]) < amount:
                    reply_body = self.token_config[token]["no_token_left_body"]
                else:
                    if "%s" in self.token_config[token]["sucess_reply_body"]:
                        reply_body = self.token_config[token]["sucess_reply_body"] % c_comment["parent_author"]
                    else:
                        reply_body = self.token_config[token]["sucess_reply_body"]
                    if "%s" in self.token_config[token]["token_memo"]:
                        token_memo = self.token_config[token]["token_memo"] % c_comment["author"]
                    else:
                        token_memo = self.token_config[token]["token_memo"]
                        
                    sendwallet = Wallet(self.token_config[token]["scot_account"], steem_instance=self.stm)

                    try:
                        logger.info("Sending %.2f %s to %s" % (amount, self.token_config[token]["scot_token"], c_comment["parent_author"]))
                        sendwallet.transfer(c_comment["parent_author"], amount, self.token_config[token]["scot_token"], token_memo)
                    except Exception as e:
                        exc_type, exc_obj, exc_tb = sys.exc_info()
                        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                        logger.warn("%s - %s - %s" % (str(exc_type), str(fname), str(exc_tb.tb_lineno)))                     
                        logger.warn("Could not send %s token" % self.token_config[token]["scot_token"])
                        continue
                        
                reply_identifier = construct_authorperm(c_comment["parent_author"], c_comment["parent_permlink"])
                if self.config["no_broadcast"]:
                    logger.info("%s" % reply_body)
                else:
                    try:
                        self.stm.post("", reply_body, author=self.token_config[token]["scot_account"], reply_identifier=reply_identifier)
                    except Exception as e:
                        exc_type, exc_obj, exc_tb = sys.exc_info()
                        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                        logger.warn("%s - %s - %s" % (str(exc_type), str(fname), str(exc_tb.tb_lineno)))                     
                        logger.warn("Could not reply to post")
                        continue
                    if self.token_config[token]["usage_upvote_percentage"] > 0:
                        try:
                            c_comment.upvote(self.token_config[token]["usage_upvote_percentage"], voter=self.token_config[token]["scot_account"])
                        except Exception as e:
                            exc_type, exc_obj, exc_tb = sys.exc_info()
                            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                            logger.warn("%s - %s - %s" % (str(exc_type), str(fname), str(exc_tb.tb_lineno)))                        
                            logger.warn("Could not upvote comment")
                            
                time.sleep(4)
        return last_block_num
コード例 #10
0
            rules = trailDownVoteRulesTrx.get_rules(voter)

        if len(rules) == 0:
            continue
        # print(rules)
        fitting_rules = []

        cnt = 0
        post = None
        while post is None and cnt < 5:
            cnt += 1
            try:
                post = Comment(authorperm,
                               use_tags_api=False,
                               steem_instance=stm)
                post.refresh()
            except:
                nodelist = NodeList()
                nodelist.update_nodes()
                stm = Steem(node=nodelist.get_nodes(),
                            num_retries=5,
                            call_num_retries=3,
                            timeout=15,
                            nobroadcast=nobroadcast)
                time.sleep(1)
        if cnt == 5:
            print("Could not read %s" % (authorperm))
            continue

        for rule in rules:
            # print(rule)
コード例 #11
0
ファイル: scot.py プロジェクト: passionbull/steem-scot
    def get_token_to_sent(self, start_block, stop_block, token_per_100_vote):
        token_to_authors = {}
        b = Blockchain(steem_instance=self.stm)
        for op in b.stream(start=start_block,
                           stop=stop_block,
                           opNames=["vote"],
                           max_batch_size=50):
            if op["voter"] not in token_per_100_vote:
                continue
            if not self.config["downvotes"] and op["weight"] < 0:
                continue
            if not self.config["upvotes"] and op["weight"] > 0:
                continue
            comment = Comment(op, steem_instance=self.stm)
            try:
                comment.refresh()
            except:
                print("Could not fetch %s" % comment["authorperm"])
                continue
            json_metadata = comment["json_metadata"]
            app = None
            SETokensSupported = None
            if isinstance(json_metadata, str):
                json_metadata = json.loads(json_metadata)
            if "app" in json_metadata:
                app = json_metadata["app"]
                if isinstance(app, dict) and "name" in app:
                    app = app["name"]
                elif isinstance(app, dict):
                    app = ""
            if "SETokensSupported" in json_metadata:
                SETokensSupported = json_metadata["SETokensSupported"]

            app_or_symbol = False
            if app is not None and len(
                    self.config["included_apps"]
            ) > 0 and app != "" and app in self.config["included_apps"]:
                app_or_symbol = True
            elif self.config["include_token_as_tag"] and self.scot_token[
                    "symbol"] in comment["tags"]:
                app_or_symbol = True
            elif SETokensSupported is not None and len(
                    SETokensSupported
            ) > 0 and self.scot_token["symbol"] in SETokensSupported:
                app_or_symbol = True
            if not app_or_symbol and not self.config["include_all_posts"]:
                continue

            token_amount = abs(
                op["weight"]) / 10000 * token_per_100_vote[op["voter"]]
            if op["weight"] < 0:
                if op["voter"] not in token_to_authors:
                    token_to_authors[op["voter"]] = token_amount
                else:
                    token_to_authors[op["voter"]] += token_amount
            else:
                if op["author"] not in token_to_authors:
                    token_to_authors[op["author"]] = token_amount
                else:
                    token_to_authors[op["author"]] += token_amount
        return token_to_authors