def test_constructAuthorperm(self): self.assertEqual(construct_authorperm("A", "B"), "@A/B") self.assertEqual( construct_authorperm({ 'author': "A", 'permlink': "B" }), "@A/B")
def summoncharbot(): print(f'[Starting Character Bot]') REGEX = '(?<=^|(?<=[^a-zA-Z0-9-.]))@([A-Za-z]+[A-Za-z0-9]+)' username = '******' REGCHA = '(?<=^|(?<=[^a-zA-Z0-9-.]))!([A-Za-z]+[A-Za-z0-9]+)' newchar = 'generate' while True: try: for post in chain.stream(opNames="comment", threading=True, thread_num=5): mentions = re.findall(REGEX, post["body"]) gen_new_char = re.findall(REGCHA, post["body"]) comment = Comment(post) perm = comment.authorperm parent = construct_authorperm( Comment(perm).parent_author, Comment(perm).parent_permlink) author = post['author'] if Comment(perm).is_comment(): if username in mentions: comment.reply( "Character Generator Bot Summoned! \nUse `!generate` to create a random character.", "", username) commentlink = comment.permlink print("Mention found - Comment made: " + commentlink) finally: print("Exiting Bot")
def benchmark_calls(node, authorpermvoter, num_retries=10, num_retries_call=10, timeout=60): block_count = 0 history_count = 0 access_time = timeout follow_time = 0 sucessfull = False error_msg = None start_total = timer() account_name = "gtg" [author, permlink, voter] = resolve_authorpermvoter(authorpermvoter) authorperm = construct_authorperm(author, permlink) try: stm = Steem(node=node, num_retries=num_retries, num_retries_call=num_retries_call, timeout=timeout) start = timer() Vote(authorpermvoter, steem_instance=stm) stop = timer() vote_time = stop - start start = timer() c = Comment(authorperm, steem_instance=stm) if c.title == '': raise AssertionError("title must not be empty!") stop = timer() comment_time = stop - start start = timer() acc = Account(author, steem_instance=stm) # if acc.json()["json_metadata"] == '': # raise AssertionError("json_metadata must not be empty!") stop = timer() account_time = stop - start sucessfull = True access_time = (vote_time + comment_time + account_time) / 3.0 except NumRetriesReached: error_msg = 'NumRetriesReached' sucessfull = False except KeyboardInterrupt: error_msg = 'KeyboardInterrupt' # quit = True except Exception as e: error_msg = str(e) sucessfull = False total_duration = float("{0:.2f}".format(timer() - start_total)) access_time = float("{0:.3f}".format(access_time)) return { 'sucessfull': sucessfull, 'node': node, 'error': error_msg, 'total_duration': total_duration, 'access_time': access_time, 'count': None }
def get_author_perm(self): if self.author_perm is None: if self.url is not None: self.author_perm = "/".join(self.url.split("/")[-2:]) elif self.ops is not None: self.author_perm = construct_authorperm(self.ops) return self.author_perm
def summon_upvotebot(): print(f"[Starting up]") while True: try: for post in chain.stream(opNames="comment", threading=True, thread_num=5): mentions = re.findall(REGEX, post["body"]) comment = Comment(post) perm = comment.authorperm parent = construct_authorperm( Comment(perm).parent_author, Comment(perm).parent_permlink) author = post["author"] if Comment(perm).is_comment and botname in mentions: print( f"[{author} just mentioned {botname} in {perm} in reply to {parent}]" ) if author in followees: Comment(parent).upvote(weight=weight, voter=botname) print( f"[{botname} voted {weight}% on {parent} per {author}'s request]" ) else: print( f"[{author} tried to summon {botname} but is not in the whitelist]" ) except Exception as error: print(repr(error)) continue
def check_beneficiaries(self, author, permlink): if author not in self.accounts: return if self.accounts[author]["delegated_hp"] == 0: return if self.accounts[author]["delegation_revoked"]: return if not self.config["beneficiaryRemoval"]: return comment = None cnt = 0 while comment is None and cnt < 10: cnt += 1 try: comment = Comment(construct_authorperm(author, permlink), blockchain_instance=self.hive) except: comment = None time.sleep(3) referrer_ok = False for bene in comment["beneficiaries"]: if bene["account"] == self.config["referrerAccount"] and bene[ "weight"] == self.accounts[author]["weight"]: referrer_ok = True if not referrer_ok: self.remove_delegation(author) self.notify_account(author, self.config["delegationBeneficiaryMsg"])
def setUpClass(cls): nodelist = NodeList() nodelist.update_nodes(steem_instance=Steem(node=nodelist.get_nodes(hive=True), num_retries=10)) cls.bts = Steem( node=nodelist.get_nodes(hive=True), nobroadcast=True, keys={"active": wif}, num_retries=10 ) # from getpass import getpass # self.bts.wallet.unlock(getpass()) set_shared_steem_instance(cls.bts) cls.bts.set_default_account("test") acc = Account("fullnodeupdate", steem_instance=cls.bts) n_votes = 0 index = 0 entries = acc.get_blog_entries(limit=30)[::-1] while n_votes == 0: comment = Comment(entries[index], steem_instance=cls.bts) votes = comment.get_votes() n_votes = len(votes) index += 1 last_vote = votes[0] cls.authorpermvoter = construct_authorpermvoter(last_vote['author'], last_vote['permlink'], last_vote["voter"]) [author, permlink, voter] = resolve_authorpermvoter(cls.authorpermvoter) cls.author = author cls.permlink = permlink cls.voter = voter cls.authorperm = construct_authorperm(author, permlink)
def report(): """Posting a report post with the flaggers set as beneficiaries.""" cursor.execute('DELETE FROM flaggers;') cursor.execute( 'INSERT INTO flaggers SELECT DISTINCT flagger FROM steemflagrewards WHERE included == 0 ORDER BY created ASC LIMIT 8;') sql = cursor.execute( 'SELECT \'[Comment](https://steemit.com/\' || post || \'#\' || comment || \')\', \'@\' || flagger, \'$\' || ROUND(payout, 3), category' \ 'FROM steemflagrewards WHERE included == 0 AND flagger IN flaggers;') db.commit() table = '|Link|Flagger|Removed Rewards|Category|\n|:----|:-------|:---------------:|:--------|' for q in sql.fetchall(): table += '\n|{}|{}|{}|{}|'.format(q[0], q[1], q[2], q[3]) body = '## This post triggers once we have approved flags from 8 distinct flaggers via the SteemFlagRewards Abuse ' \ 'Fighting Community on our [Discord](https://discord.gg/7pqKmg5) ' \ '\n\nhttps://steemitimages.com/DQmTJj2SXdXcYLh3gtsziSEUXH6WP43UG6Ltoq9EZyWjQeb/frpaccount.jpg\n\nFlaggers ' \ 'have been designated as post beneficiaries. Our goal is to empower abuse fighting plankton and minnows ' \ 'and promote a Steem that is less-friendly to abuse. It is simple. Building abuse fighters equals less ' \ 'abuse.\n\n\n{}'.format(table) logging.info('Generated post body') benlist = [] sql = cursor.execute( '''SELECT flagger, COUNT(*) * 95 * 10 / (SELECT COUNT(*) FROM steemflagrewards WHERE included == 0 AND flagger IN flaggers) FROM steemflagrewards WHERE flagger in flaggers AND included == 0 GROUP BY flagger ORDER BY flagger;''') # Exchange 100 in line 99 with the percentage of the post rewards you want the flaggers to receive for q in sql.fetchall(): benlist.append({'account': q[0], 'weight': int(q[1])*10}) rep = stm.post( 'Steem Flag Rewards Report - 8 Flagger Post - {}'.format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")), body, 'steemflagrewards', tags=['steemflagrewards', 'abuse', 'steem', 'steemit', 'flag'], beneficiaries=benlist, parse_body=True, self_vote=False, community='busy', app='busy/2.5.4') cursor.execute('UPDATE steemflagrewards SET included = 1 WHERE flagger in flaggers;') db.commit() return construct_authorperm(rep)
def setUpClass(cls): nodelist = NodeList() cls.bts = Steem(node=nodelist.get_nodes(appbase=False), nobroadcast=True, keys={"active": wif}, num_retries=10) cls.appbase = Steem(node=nodelist.get_nodes(normal=False, appbase=True), nobroadcast=True, keys={"active": wif}, num_retries=10) # from getpass import getpass # self.bts.wallet.unlock(getpass()) set_shared_steem_instance(cls.bts) cls.bts.set_default_account("test") acc = Account("holger80", steem_instance=cls.bts) votes = acc.get_account_votes() last_vote = votes[0] cls.authorpermvoter = '@' + last_vote['authorperm'] + '|' + acc["name"] [author, permlink, voter] = resolve_authorpermvoter(cls.authorpermvoter) cls.author = author cls.permlink = permlink cls.voter = voter cls.authorperm = construct_authorperm(author, permlink)
def post_detail(request, author, permlink, **args): author_perm = construct_authorperm(author, permlink) post = Comment(author_perm, blockchain_instance=hv) if post: replies = post.get_replies(raw_data=True) post = strip(post) for reply in replies: reply = strip(reply) return render(request, 'blog/post_detail.html', {'post': post, 'replies': replies})
def checkExists(auth, pLink): """ Test if a pLink value has been posted by this author before Returns True False. if True also returns the content body """ authPLink = construct_authorperm(auth, pLink) try: c = Comment(authorperm=authPLink) except ContentDoesNotExistsException: return False, '' return True , c.body
def diff_files_into_text_areas(self): try: content = open(self.rightFile, "r", encoding="utf8").read() except Exception as e: showerror("Unable to read " + self.rightFile, str(e)) content = '' rightFileContents, parameter = seperate_yaml_dict_from_body(content) if "permlink" in parameter: authorperm = construct_authorperm(parameter["author"], parameter["permlink"]) else: authorperm = construct_authorperm(parameter["author"], derive_permlink(parameter["title"], with_suffix=False)) self.__main_window_ui.leftFileLabel.config(text=authorperm) try: comment = Comment(authorperm) leftFileContents = comment.body except: leftFileContents = '' self.show_content(leftFileContents, rightFileContents)
def monitor(): table = db.load_table("leaderboard") vote_table = db["vote_history"] print("[Monitor Starting up...]") # Read the live stream and filter out only transfers for post in stream: try: q = table.find_one(user=post["author"]) if q is not None and post["author"] == q["user"]: perm = construct_authorperm(post["author"], post["permlink"]) c = Comment(perm, blockchain_instance=hive) if c.is_main_post(): today = datetime.now(timezone.utc) week_tally = tally(post["author"]) print(f"[Post Found! By: {q['user']} Rank: {q['rank']}]") vote_weight = math.ceil( ((160 - q["rank"]) * 2.5) / (week_tally)) vote_weight = 100 if vote_weight >= 100 else vote_weight vote_weight = 1 if vote_weight <= 1 else vote_weight print( f"[{week_tally} post(s) a week. - {perm} should be voted with a {vote_weight}% upvote.]" ) # Trying to catch about the 4 minute mark for curation. time.sleep(240) tx = c.upvote(weight=vote_weight, voter=voter) reply_body = f"Your current Rank ({q['rank']}) in the battle Arena of Holybread has granted you an Upvote of {vote_weight}%" # print(tx) reply_tx = c.reply(reply_body, title="Leaderboard Vote", author=voter) # print(reply_tx) vote_table.insert( dict( user=q["user"], rank=q["rank"], post=perm, vote_weight=vote_weight, vote_time=today, )) except Exception as e: print(f"[Error: {e}]")
def setUpClass(cls): cls.bts = Steem(node=get_node_list(appbase=False), nobroadcast=True, keys={"active": wif}, num_retries=10) cls.appbase = Steem(node=get_node_list(appbase=True), nobroadcast=True, keys={"active": wif}, num_retries=10) # from getpass import getpass # self.bts.wallet.unlock(getpass()) set_shared_steem_instance(cls.bts) cls.bts.set_default_account("test") cls.authorpermvoter = u"@gtg/ffdhu-gtg-witness-log|gandalf" [author, permlink, voter] = resolve_authorpermvoter(cls.authorpermvoter) cls.author = author cls.permlink = permlink cls.voter = voter cls.authorperm = construct_authorperm(author, permlink)
def setUpClass(cls): nodelist = NodeList() nodelist.update_nodes(steem_instance=Steem(node=nodelist.get_nodes( normal=True, appbase=True), num_retries=10)) cls.bts = Steem(node=nodelist.get_nodes(), nobroadcast=True, keys={"active": wif}, num_retries=10) cls.testnet = Steem(node="https://testnet.steemitdev.com", nobroadcast=True, keys={"active": wif}, num_retries=10) # from getpass import getpass # self.bts.wallet.unlock(getpass()) set_shared_steem_instance(cls.bts) cls.bts.set_default_account("test") acc = Account("holger80", steem_instance=cls.bts) n_votes = 0 index = 0 while n_votes == 0: comment = acc.get_feed(limit=30)[::-1][index] votes = comment.get_votes() n_votes = len(votes) index += 1 last_vote = votes[0] cls.authorpermvoter = construct_authorpermvoter( last_vote['author'], last_vote['permlink'], last_vote["voter"]) [author, permlink, voter] = resolve_authorpermvoter(cls.authorpermvoter) cls.author = author cls.permlink = permlink cls.voter = voter cls.authorperm = construct_authorperm(author, permlink)
ops = accountTrx[acc_name].get_all(op_types=["transfer"]) cnt = 0 for o in ops: cnt += 1 if cnt % 10000 == 0: print("%d/%d" % (cnt, len(ops))) op = json.loads(o["op_dict"]) if op["memo"] == "": continue try: c = Comment(op["memo"], steem_instance=stm) except: continue if c["author"] not in accounts: continue authorperm = construct_authorperm(c["author"], c["permlink"]) if authorperm not in comments_transfer: comments_transfer.append(authorperm) print("%d comments with transfer found" % len(comments_transfer)) del ops ops = accountTrx[acc_name].get_all(op_types=["comment"]) cnt = 0 for o in ops: cnt += 1 if cnt % 10000 == 0: print("%d/%d" % (cnt, len(ops))) op = json.loads(o["op_dict"]) c = Comment(op, steem_instance=stm) if c["author"] not in accounts:
max_batch_size=max_batch_size, threading=threading, thread_num=8): #print(ops) timestamp = ops["timestamp"] # timestamp = timestamp.replace(tzinfo=None) # continue if ops["author"] not in member_accounts: continue if ops["block_num"] <= latest_update_block: continue if ops["block_num"] - last_block_print > 50: last_block_print = ops["block_num"] print("blocks left %d - post found: %d" % (ops["block_num"] - stop_block, len(posts_dict))) authorperm = construct_authorperm(ops) c = None cnt = 0 use_tags_api = True while c is None and cnt < 5: cnt += 1 try: c = Comment(authorperm, use_tags_api=use_tags_api, steem_instance=stm) except: c = None use_tags_api = False continue if c is None: continue
command = ",".join(ops["memo"].split(",")[1:]) commandsTrx.add({ "authorperm": authorperm, "command": command, "account": ops["from"], "valid": True, "created": ops["timestamp"].replace(tzinfo=None), "in_progress": False, "done": False, "block": ops["block_num"] }) continue elif ops["type"] == "transfer": continue elif ops["type"] == "vote": authorperm = construct_authorperm(ops["author"], ops["permlink"]) unprocessed_vote = broadcastVoteTrx.get_unprocessed( ops["voter"], authorperm) if unprocessed_vote is not None: broadcastVoteTrx.update_processed(ops["voter"], authorperm, ops["trx_id"], True, False) timestamp = ops["timestamp"].replace(tzinfo=None) weight = ops["weight"] / STEEM_100_PERCENT * 100 voteTrx.add({ "authorperm": authorperm, "voter": ops["voter"], "block": ops["block_num"], "timestamp": timestamp, "weight": weight })
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
def get_author_perm(self): if self.author_perm is None: self.author_perm = construct_authorperm(self.ops) return self.author_perm
def vote(self, vote_event): def process_vote_content(event): start_rshares = 0.0 for vote in event["active_votes"]: if vote["voter"] == vote_event["voter"] and float( vote["rshares"]) < 0: if start_rshares + float(vote["rshares"]) < 0: flag_power = 0 - start_rshares - float(vote["rshares"]) else: flag_power = 0 downvote_power = 0 - vote["rshares"] - flag_power self.wtw.update(vote["voter"], vote_event["author"], downvote_power, flag_power) def lookup_accounts(acclist): def user_info(accounts): if len(acclist) != len(accounts): print("OOPS:", len(acclist), len(accounts), acclist) for index in range(0, len(accounts)): a = accounts[index] account = acclist[index] vp = (a["vesting_shares"].amount + a["received_vesting_shares"].amount - a["delegated_vesting_shares"].amount) / 1000000.0 fish = "redfish" if vp >= 1.0: fish = "minnow" if vp >= 10.0: fish = "dolphin" if vp >= 100: fish = "orca" if vp > 1000: fish = "whale" racc = None proxy = None related = list() if a["recovery_account"] != "steem" and a[ "recovery_account"] != "": related.append(a["recovery_account"]) if a["proxy"] != "": related.append(a["proxy"]) self.wtw.set_account_info(account, fish, related) accl2 = list() if racc is not None and racc not in self.looked_up: accl2.append(racc) if proxy is not None and proxy not in self.looked_up: accl2.append(proxy) if len(accl2) > 0: lookup_accounts(accl2) accounts = [] for a in acclist: accounts.append(Account(a)) user_info(accounts) if vote_event["weight"] < 0: authorperm = construct_authorperm(vote_event["author"], vote_event["permlink"]) # print(authorperm) try: process_vote_content(Comment(authorperm)) except exceptions.ContentDoesNotExistsException: print("Could not find Comment: %s" % (authorperm)) al = list() if not vote_event["voter"] in self.looked_up: al.append(vote_event["voter"]) self.looked_up.add(vote_event["voter"]) if not vote_event["author"] in self.looked_up: al.append(vote_event["author"]) self.looked_up.add(vote_event["author"]) if len(al) > 0: lookup_accounts(al)
def benchmark_node(node, how_many_minutes=10, how_many_seconds=30): block_count = 0 history_count = 0 access_time = 0 follow_time = 0 blockchain_version = u'0.0.0' successful = True error_msg = None start_total = timer() max_batch_size = None threading = False thread_num = 16 authorpermvoter = u"@gtg/steem-pressure-4-need-for-speed|gandalf" [author, permlink, voter] = resolve_authorpermvoter(authorpermvoter) authorperm = construct_authorperm(author, permlink) last_block_id = 19273700 try: stm = Steem(node=node, num_retries=3, num_retries_call=3, timeout=30) blockchain = Blockchain(steem_instance=stm) blockchain_version = stm.get_blockchain_version() last_block = Block(last_block_id, steem_instance=stm) stopTime = last_block.time() + timedelta(seconds=how_many_minutes * 60) total_transaction = 0 start = timer() for entry in blockchain.blocks(start=last_block_id, max_batch_size=max_batch_size, threading=threading, thread_num=thread_num): block_no = entry.identifier block_count += 1 if "block" in entry: trxs = entry["block"]["transactions"] else: trxs = entry["transactions"] for tx in trxs: for op in tx["operations"]: total_transaction += 1 if "block" in entry: block_time = parse_time(entry["block"]["timestamp"]) else: block_time = parse_time(entry["timestamp"]) if block_time > stopTime: last_block_id = block_no break if timer() - start > how_many_seconds or quit_thread: break except NumRetriesReached: error_msg = 'NumRetriesReached' block_count = -1 except KeyboardInterrupt: error_msg = 'KeyboardInterrupt' # quit = True except Exception as e: error_msg = str(e) block_count = -1 try: stm = Steem(node=node, num_retries=3, num_retries_call=3, timeout=30) account = Account("gtg", steem_instance=stm) blockchain_version = stm.get_blockchain_version() start = timer() for acc_op in account.history_reverse(batch_size=100): history_count += 1 if timer() - start > how_many_seconds or quit_thread: break except NumRetriesReached: error_msg = 'NumRetriesReached' history_count = -1 successful = False except KeyboardInterrupt: error_msg = 'KeyboardInterrupt' history_count = -1 successful = False # quit = True except Exception as e: error_msg = str(e) history_count = -1 successful = False try: stm = Steem(node=node, num_retries=3, num_retries_call=3, timeout=30) account = Account("gtg", steem_instance=stm) blockchain_version = stm.get_blockchain_version() start = timer() Vote(authorpermvoter, steem_instance=stm) stop = timer() vote_time = stop - start start = timer() Comment(authorperm, steem_instance=stm) stop = timer() comment_time = stop - start start = timer() Account(author, steem_instance=stm) stop = timer() account_time = stop - start start = timer() account.get_followers() stop = timer() follow_time = stop - start access_time = (vote_time + comment_time + account_time + follow_time) / 4.0 except NumRetriesReached: error_msg = 'NumRetriesReached' access_time = -1 except KeyboardInterrupt: error_msg = 'KeyboardInterrupt' # quit = True except Exception as e: error_msg = str(e) access_time = -1 return {'successful': successful, 'node': node, 'error': error_msg, 'total_duration': timer() - start_total, 'block_count': block_count, 'history_count': history_count, 'access_time': access_time, 'follow_time': follow_time, 'version': blockchain_version}
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
posting_auth = False for a in voter_acc["posting"]["account_auths"]: if a[0] == "rewarding": posting_auth = True already_voted = False for v in c_comment.get_votes(): if v["voter"] == rewarding_account: already_voted = True if already_voted: continue if c_comment.is_main_post(): c = c_comment else: c = Comment(construct_authorperm(c_comment["parent_author"], c_comment["parent_permlink"]), steem_instance=stm) if not (c.is_pending() and valid_age(c)): body = "The reward of this comment goes 100 %% to the author %s. This is done by setting the beneficiaries of this comment to 100 %%.\n\n" % ( c["author"]) comment_beneficiaries = [{"account": c["author"], "weight": 10000}] permlink = derive_permlink("rewarding %s" % c["author"], c_comment["permlink"]) stm.post("rewarding %s" % c["author"], body, author=rewarding_account, permlink=permlink, reply_identifier=c_comment["authorperm"], beneficiaries=comment_beneficiaries) time.sleep(3)
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
def update_account_hist(self): if self.hist_account is None: return votes = [] daily_curation = 0 daily_author_SP = 0 daily_author_SBD = 0 daily_author_STEEM = 0 self.append_account_hist() new_op_found = False start_block = self.account_hist_info["start_block"] if start_block == 0: first_call = True else: first_call = False trx_ids = self.account_hist_info["trx_ids"] for op in self.account_history: if op["block"] < start_block: # last_block = op["block"] continue elif op["block"] == start_block: if op["trx_id"] in trx_ids: continue else: trx_ids.append(op["trx_id"]) else: trx_ids = [op["trx_id"]] start_block = op["block"] new_op_found = True op_timedelta = formatTimedelta( addTzInfo(datetime.utcnow()) - formatTimeString(op["timestamp"])) op_local_time = formatTimeString(op["timestamp"]).astimezone( tz.tzlocal()) # print("Read %d" % op["index"]) if op["type"] == "vote": if op["voter"] == self.hist_account["name"]: continue if op["weight"] >= 0: self.lastUpvotesListWidget.insertItem( 0, "%s - %s (%.2f %%) upvote %s" % (op_timedelta, op["voter"], op["weight"] / 100, op["permlink"])) hist_item = "%s - %s - %s (%.2f %%) upvote %s" % ( op_local_time, op["type"], op["voter"], op["weight"] / 100, op["permlink"]) tray_item = "%s - %s (%.2f %%) upvote %s" % ( op["type"], op["voter"], op["weight"] / 100, op["permlink"]) else: hist_item = "%s - %s - %s (%.2f %%) downvote %s" % ( op_local_time, op["type"], op["voter"], op["weight"] / 100, op["permlink"]) tray_item = "%s - %s (%.2f %%) downvote %s" % ( op["type"], op["voter"], op["weight"] / 100, op["permlink"]) self.accountHistListWidget.insertItem(0, hist_item) elif op["type"] == "curation_reward": curation_reward = self.stm.vests_to_sp( Amount(op["reward"], steem_instance=self.stm)) self.lastCurationListWidget.insertItem( 0, "%s - %.3f HP for %s" % (op_timedelta, curation_reward, construct_authorperm(op["comment_author"], op["comment_permlink"]))) hist_item = "%s - %s - %.3f HP for %s" % ( op_local_time, op["type"], curation_reward, construct_authorperm(op["comment_author"], op["comment_permlink"])) tray_item = "%s - %.3f HP for %s" % ( op["type"], curation_reward, construct_authorperm(op["comment_author"], op["comment_permlink"])) self.accountHistListWidget.insertItem(0, hist_item) elif op["type"] == "author_reward": sbd_payout = (Amount(op["sbd_payout"], steem_instance=self.stm)) steem_payout = (Amount(op["steem_payout"], steem_instance=self.stm)) sp_payout = self.stm.vests_to_sp( Amount(op["vesting_payout"], steem_instance=self.stm)) self.lastAuthorListWidget.insertItem( 0, "%s - %s %s %.3f HP for %s" % (op_timedelta, str(sbd_payout), str(steem_payout), sp_payout, op["permlink"])) hist_item = "%s - %s - %s %s %.3f SP for %s" % ( op_local_time, op["type"], str(sbd_payout), str(steem_payout), sp_payout, op["permlink"]) tray_item = "%s - %s %s %.3f SP for %s" % ( op["type"], str(sbd_payout), str(steem_payout), sp_payout, op["permlink"]) self.accountHistListWidget.insertItem(0, hist_item) elif op["type"] == "custom_json": hist_item = "%s - %s - %s" % (op_local_time, op["type"], op["id"]) tray_item = "%s - %s" % (op["type"], op["id"]) self.accountHistListWidget.insertItem(0, hist_item) elif op["type"] == "transfer": hist_item = "%s - %s - %s from %s" % ( op_local_time, op["type"], str(Amount(op["amount"], steem_instance=self.stm)), op["from"]) tray_item = "%s - %s from %s" % ( op["type"], str(Amount(op["amount"], steem_instance=self.stm)), op["from"]) self.accountHistListWidget.insertItem(0, hist_item) elif op["type"] == "comment": comment_type = "post" if op["parent_author"] != "": hist_item = "%s - comment on %s - %s from %s" % ( op_local_time, construct_authorperm( op["parent_author"], op["parent_permlink"]), op["title"], op["author"]) tray_item = "comment from %s: %s on %s" % ( op["author"], op["body"][:100], op["title"]) else: hist_item = "%s - post - %s from %s" % ( op_local_time, op["title"], op["author"]) tray_item = "post from %s: %s" % (op["author"], op["title"]) self.accountHistListWidget.insertItem(0, hist_item) else: hist_item = "%s - %s" % (op_local_time, op["type"]) tray_item = "%s" % (op["type"]) self.accountHistListWidget.insertItem(0, hist_item) if self.accountHistNotificationCheckBox.isChecked( ) and not first_call: self.tray.showMessage(self.hist_account["name"], tray_item) if new_op_found: self.account_hist_info["start_block"] = start_block self.account_hist_info["trx_ids"] = trx_ids for op in self.account_history: if op["type"] == "vote": if op["voter"] == self.hist_account["name"]: continue votes.append(op) elif op["type"] == "curation_reward": curation_reward = self.stm.vests_to_sp( Amount(op["reward"], steem_instance=self.stm)) daily_curation += curation_reward elif op["type"] == "author_reward": sbd_payout = (Amount(op["sbd_payout"], steem_instance=self.stm)) steem_payout = (Amount(op["steem_payout"], steem_instance=self.stm)) sp_payout = self.stm.vests_to_sp( Amount(op["vesting_payout"], steem_instance=self.stm)) daily_author_SP += sp_payout daily_author_STEEM += float(steem_payout) daily_author_SBD += float(sbd_payout) reward_text = "Curation reward (last 24 h): %.3f HP\n" % daily_curation reward_text += "Author reward (last 24 h):\n" reward_text += "%.3f HP - %.3f HIVE - %.3f HBD" % ( daily_author_SP, (daily_author_STEEM), (daily_author_SBD)) self.text2.setText(reward_text)
def update_account_hist(self): if self.hist_account is None: return votes = [] daily_curation = 0 daily_author_SP = 0 daily_author_SBD = 0 daily_author_STEEM = 0 self.append_account_hist() new_op_found = False start_block = self.account_hist_info["start_block"] if start_block == 0: first_call = True b = Blockchain() start_block = b.get_current_block_num() - 20 * 60 * 24 * 7 self.account_hist_info["start_block"] = start_block else: first_call = False ops = self.db.load_account_hist(start_block) for op in ops: if op["block"] < start_block: # last_block = op["block"] continue start_block = op["block"] new_op_found = True tray_item = None op_timedelta = formatTimedelta(addTzInfo(datetime.utcnow()) - addTzInfo(op["timestamp"])) op_local_time = addTzInfo(op["timestamp"]).astimezone(tz.tzlocal()) # print("Read %d" % op["index"]) self.accountHistTableWidget.insertRow(0) self.accountHistTableWidget.setItem(0, 4, QTableWidgetItem(str(op_local_time))) if op["type"] == "vote": if op["voter"] == self.hist_account["name"]: self.accountHistTableWidget.setItem(0, 0, QTableWidgetItem("Vote")) self.accountHistTableWidget.setItem(0, 1, QTableWidgetItem(op["author"])) elif op["weight"] >= 0: self.accountHistTableWidget.setItem(0, 0, QTableWidgetItem("Vote Post")) self.accountHistTableWidget.setItem(0, 1, QTableWidgetItem(op["voter"])) tray_item = "%s - %s (%.2f %%) vote %s" % (op["type"], op["voter"], op["weight"] / 100, op["permlink"]) else: self.accountHistTableWidget.setItem(0, 0, QTableWidgetItem("Dowvote Post")) self.accountHistTableWidget.setItem(0, 1, QTableWidgetItem(op["voter"])) # hist_item.setToolTip(0, op["permlink"]) tray_item = "%s - %s (%.2f %%) downvote %s" % (op["type"], op["voter"], op["weight"] / 100, op["permlink"]) self.accountHistTableWidget.setItem(0, 2, QTableWidgetItem("%.2f %%" % (op["weight"] / 100))) elif op["type"] == "curation_reward": self.accountHistTableWidget.setItem(0, 0, QTableWidgetItem(op["type"])) curation_reward = self.stm.vests_to_sp(Amount(op["reward"], steem_instance=self.stm)) self.accountHistTableWidget.setItem(0, 1, QTableWidgetItem("%.3f HP" % curation_reward)) self.accountHistTableWidget.setItem(0, 2, QTableWidgetItem(construct_authorperm(op["comment_author"], op["comment_permlink"]))) hist_item = "%s - %s - %.3f HP for %s" % (op_local_time, op["type"], curation_reward, construct_authorperm(op["comment_author"], op["comment_permlink"])) tray_item = "%s - %.3f HP for %s" % (op["type"], curation_reward, construct_authorperm(op["comment_author"], op["comment_permlink"])) elif op["type"] == "author_reward": self.accountHistTableWidget.setItem(0, 0, QTableWidgetItem(op["type"])) sbd_payout = (Amount(op["sbd_payout"], steem_instance=self.stm)) steem_payout = (Amount(op["steem_payout"], steem_instance=self.stm)) sp_payout = self.stm.vests_to_sp(Amount(op["vesting_payout"], steem_instance=self.stm)) hist_item = "%s - %s - %s %s %.3f SP for %s" % (op_local_time, op["type"], str(sbd_payout), str(steem_payout), sp_payout, op["permlink"]) tray_item = "%s - %s %s %.3f SP for %s" % (op["type"], str(sbd_payout), str(steem_payout), sp_payout, op["permlink"]) elif op["type"] == "custom_json": self.accountHistTableWidget.setItem(0, 0, QTableWidgetItem(op["type"])) self.accountHistTableWidget.setItem(0, 1, QTableWidgetItem(op["json_id"])) json_data = QTableWidgetItem(op["json"]) json_data.setToolTip(op["json"]) self.accountHistTableWidget.setItem(0, 2, json_data) hist_item = "%s - %s - %s" % (op_local_time, op["type"], op["id"]) tray_item = "%s - %s" % (op["type"], op["json_id"]) elif op["type"] == "transfer": self.accountHistTableWidget.setItem(0, 0, QTableWidgetItem(op["type"])) hist_item = "%s - %s - %s from %s" % (op_local_time, op["type"], str(Amount(op["amount"], steem_instance=self.stm)), op["from"]) tray_item = "%s - %s from %s" % (op["type"], str(Amount(op["amount"], steem_instance=self.stm)), op["from"]) elif op["type"] == "comment": if op["parent_author"] != "": comment_type = "comment" hist_item = "%s - comment on %s - %s from %s" % (op_local_time, construct_authorperm(op["parent_author"], op["parent_permlink"]), op["title"], op["author"]) tray_item = "comment from %s: %s on %s" % (op["author"], op["body"][:100], op["title"]) self.accountHistTableWidget.setItem(0, 0, QTableWidgetItem(op["type"])) self.accountHistTableWidget.setItem(0, 1, QTableWidgetItem(op["author"])) body = QTableWidgetItem(op["body"]) body.setToolTip(op["body"]) self.accountHistTableWidget.setItem(0, 2, body) else: comment_type = "post" hist_item = "%s - post - %s from %s" % (op_local_time, op["title"], op["author"]) tray_item = "post from %s: %s" % (op["author"], op["title"]) self.accountHistTableWidget.setItem(0, 0, QTableWidgetItem(comment_type)) elif op["type"] == "producer_reward": self.accountHistTableWidget.setItem(0, 0, QTableWidgetItem(op["type"])) self.accountHistTableWidget.setItem(0, 1, QTableWidgetItem(" %.3f HP" % float(self.stm.vests_to_sp(Amount(op["vesting_shares"]))))) hist_item = "%s - %s" % (op_local_time, op["type"]) tray_item = "%s - %.3f HP" % (op["type"], float(self.stm.vests_to_sp(Amount(op["vesting_shares"])))) else: self.accountHistTableWidget.setItem(0, 0, QTableWidgetItem(op["type"])) hist_item = "%s - %s" % (op_local_time, op["type"]) tray_item = "%s" % (op["type"]) if self.accountHistNotificationCheckBox.isChecked() and not first_call and tray_item is not None: self.tray.showMessage(self.hist_account["name"], tray_item) if new_op_found: self.account_hist_info["start_block"] = start_block for op in ops: if op["type"] == "vote": if op["voter"] == self.hist_account["name"]: continue votes.append(op) elif op["type"] == "curation_reward": curation_reward = self.stm.vests_to_sp(Amount(op["reward"], steem_instance=self.stm)) daily_curation += curation_reward elif op["type"] == "author_reward": sbd_payout = (Amount(op["sbd_payout"], steem_instance=self.stm)) steem_payout = (Amount(op["steem_payout"], steem_instance=self.stm)) sp_payout = self.stm.vests_to_sp(Amount(op["vesting_payout"], steem_instance=self.stm)) daily_author_SP += sp_payout daily_author_STEEM += float(steem_payout) daily_author_SBD += float(sbd_payout) reward_text = "Curation reward (last 24 h): %.3f HP\n" % daily_curation reward_text += "Author reward (last 24 h):\n" reward_text += "%.3f HP - %.3f HIVE - %.3f HBD" % (daily_author_SP, (daily_author_STEEM), (daily_author_SBD)) self.text2.setText(reward_text)
from beem.comment import Comment from beem.vote import Vote from beemgrapheneapi.rpcutils import NumRetriesReached log = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) if __name__ == "__main__": how_many_seconds = 15 how_many_minutes = 10 max_batch_size = None threading = False thread_num = 16 authorpermvoter = u"@gtg/ffdhu-gtg-witness-log|gandalf" [author, permlink, voter] = resolve_authorpermvoter(authorpermvoter) authorperm = construct_authorperm(author, permlink) nodes = get_node_list(appbase=False) + get_node_list(appbase=True) t = PrettyTable( ["node", "N blocks", "N acc hist", "dur. call in s", "version"]) t.align = "l" for node in nodes: print("Current node:", node) try: stm = Steem(node=node, num_retries=2, num_retries_call=3, timeout=5) blockchain = Blockchain(steem_instance=stm)
def triggeredPreview(self): self.authorLabel.setText(self.post["author"]) self.titleLabel.setText(self.post["title"]) self.auhorpermLineEdit.setText(construct_authorperm(self.post["author"], self.post["permlink"])) self.thread.start()
if member_data[op["author"]]["last_post"] is None: member_data[op["author"]]["comment_upvote"] = 1 elif addTzInfo(member_data[op["author"]]["last_post"]) < date_7_before: member_data[op["author"]]["comment_upvote"] = 1 elif member_data[op["author"]]["comment_upvote"] == 1: member_data[op["author"]]["comment_upvote"] = 0 member_data[op["author"]]["updated_at"] = c["created"] updated_member_data.append(member_data[op["author"]]) elif op["type"] == "vote": if op["author"] not in accounts and op["author"] not in member_accounts: continue if op["voter"] not in member_accounts and op["voter"] not in accounts: continue if op["author"] in member_accounts and op["voter"] in accounts: vote = Vote(op["voter"], authorperm=construct_authorperm(op["author"], op["permlink"]), steem_instance=stm) print("member %s upvoted with %d" % (op["author"], int(vote["rshares"]))) member_data[op["author"]]["rewarded_rshares"] += int(vote["rshares"]) member_data[op["author"]]["balance_rshares"] -= int(vote["rshares"]) updated_member_data.append(member_data[op["author"]]) data["permlink"] = op["permlink"] data["author"] = op["author"] data["voter"] = op["voter"] data["weight"] = op["weight"] vote_cnt += 1 else: continue if op["type"] == "vote": db_data.append(data) last_trx_id = op["trx_id"]