Esempio n. 1
0
def run(user_json):
    username = "******"
    wif = os.environ.get("UNLOCK")
    steem = Steem(wif=wif)
    blockchain = Blockchain()
    stream = map(Post, blockchain.stream(filter_by=["comment"]))

    print("Checking posts on the blockchain!")
    while True:
        try:
            for post in stream:
                title = post["title"]
                author = post["author"]
                print(author)
                if author in user_json:
                    #                if valid_post(post, user_json):
                    try:
                        title = post["title"]
                        author = post["author"]
                        print("Upvoting post {} by {}!".format(title, author))
                        post.upvote(weight=user_json[author]["upvote_weight"],
                                    voter=username)
                    except Exception as error:
                        print(repr(error))
                        continue

        except Exception as error:
            print(repr(error))
            continue
Esempio n. 2
0
def run():
    username = os.environ.get("STEEM_NAME")
    blockchain = Blockchain()
    stream = map(Post, blockchain.stream(filter_by=["comment"]))
    upvote_list = json.load(open('upvote_list.json'))
    wif = upvote_list["voters"][username]["wif"]
    steem = Steem(wif=wif)
    upvoted = {}
    date = int(time.strftime("%d"))
    hour = int(time.strftime("%-H"))

    print("Entering blockchain stream!")
    while True:
        try:
            for post in stream:
                if int(time.strftime("%d")) is not date:
                    upvoted = {}
                    date = int(time.strftime("%d"))
                if int(time.strftime("%-H")) is not hour:
                    upvote_list = json.load(open('upvote_list.json'))
                    hour = int(time.strftime("%-H"))

                if valid_post(post, upvote_list, upvoted):
                    try:
                        author = post["author"]
                        schedule_upvote(upvote_list, username, author)
                        print("Upvoted {}".format(author))
                        upvoted[author] += 1
                    except Exception as error:
                        print(repr(error))
                        continue

        except Exception as error:
            #print(repr(error))
            continue
Esempio n. 3
0
def validate_operations(mongo):
    """ Scan latest N blocks in the database and validate its operations. """
    blockchain = Blockchain(mode="irreversible")
    highest_block = mongo.Operations.find_one({}, sort=[('block_num', -1)
                                                        ])['block_num']
    lowest_block = max(1, highest_block - 250_000)

    for block_num in range(highest_block, lowest_block, -1):
        if block_num % 100 == 0:
            log.info('Validating block #%s' % block_num)
        block = list(
            blockchain.stream(start_block=block_num, end_block=block_num))

        # remove all invalid or changed operations
        conditions = {
            'block_num': block_num,
            '_id': {
                '$nin': [x['_id'] for x in block]
            }
        }
        mongo.Operations.delete_many(conditions)

        # insert any missing operations
        for op in block:
            with suppress(DuplicateKeyError):
                transform = compose(strip_dot_from_keys, json_expand, typify)
                mongo.Operations.insert_one(transform(op))

        # re-process comments (does not re-add deleted posts)
        for comment in (x for x in block if x['type'] == 'comment'):
            upsert_comment(mongo,
                           '%s/%s' % (comment['author'], comment['permlink']))
Esempio n. 4
0
def stream():
    REGEX = "(?<=^|(?<=[^a-zA-Z0-9-_\.]))!([A-Za-z]+[A-Za-z0-9]+)"  # REGEX code for '!' marker
    blockchain = Blockchain()  # blockchain instance
    stream = map(
        Post, blockchain.stream(filter_by=['comment']))  # stream comments only
    print('\033[37mSearching...')
    for post in stream:
        curator = post['author']
        p_parent = post['parent_permlink']
        a_parent = post['parent_author']
        f = regex.findall(REGEX, post['body'])  # REGEX searches for !'flag'
        # filters
        if post.is_comment():
            if curator in curators:
                if flag in f:
                    if p_parent in log:
                        continue
                    else:
                        # start action thread
                        acaoThread = threading.Thread(target=action,
                                                      args=(
                                                          a_parent,
                                                          p_parent,
                                                          curator,
                                                      ))
                        acaoThread.start()
def run():
    account     = "sttest1"
    account      = Account(account)
    wif          = os.environ.get("UNLOCK")
    steem        = Steem(wif=wif)
    blockchain   = Blockchain()
    stream       = map(Post, blockchain.stream(filter_by=["comment"]))
    upvote_list  = json.load(open('upvote_list.json'))
    upvoted      = {}
    upvote_queue = {}
    date         = int(time.strftime("%d"))
    hour         = int(time.strftime("%-H"))

    print("Entering blockchain stream!")
    while True:
        try:
            for post in stream:

                time_string = str(post.time_elapsed())
                post_age = time_string.split(":")

                try:
                    # Omit posts older than 10 min
                    if int(post_age[0]) > 0 or int(post_age[1]) > 10:
                        break
                except Exception as e:
                    #print (repr(e))
                    break

                # start upvoting cycle at 100% voting power
                if account.voting_power() == 100:
                    start_upvote_cycle(upvote_queue, account, steem)

                # check for new date
                if int(time.strftime("%d")) is not date:
                    upvoted = {}
                    date = int(time.strftime("%d"))
                #check for new hour
                if int(time.strftime("%-H")) is not hour:
                    upvote_list  = json.load(open('upvote_list.json'))
                    hour = int(time.strftime("%-H"))

                # verify post and add to queue
                if valid_post(post, upvote_list, upvoted):
                    try:
                        author = post["author"]
                        print ("\nAdding to queue{}\nPermlink: {}".format(author, post['identifier']))
                        if post['identifier'] not in upvote_queue:
                            upvote_queue[post['identifier']] = upvote_list[author]["upvote_weight"]
                            print ("Upvoted {} for {}%".format(author, upvote_list[author]["upvote_weight"]))
                            upvoted[author] += 1
                    except Exception as error:
                        print(repr(error))
                        continue

        except Exception as error:
            #print(repr(error))
            continue
Esempio n. 6
0
def run(tags):
    log.info("Follow mode activated", tags=tags)

    if tags is None or len(tags) < 1:
        raise ValueError("You must specify at least one tag")

    log.debug("initializing...")
    steem = Steem(keys=[cred.key])
    account = Account(cred.id, steem)
    chain = Blockchain(steem)
    log.debug("ready", steem=steem, account=account, blockchain=chain)

    log.info("Gathering our following list...")
    following = account.get_following()
    pending = []
    log.info("Following list retrieved", count=len(following))

    log.info("Watching for new posts...")
    while True:
        stream = map(Post, chain.stream(filter_by=['comment']))

        try:
            for post in stream:
                count = len(pending)
                if count > 0:
                    copy = list(pending)
                    for i in range(count):
                        if have_bandwidth(steem, account):
                            user = copy[i]
                            log.info("following user", user=user)
                            steem.follow(user, account=cred.id)
                            del pending[0]

                        else:
                            log.warn("Waiting for more bandwidth before following another user")
                            break


                if post.is_main_post():
                    log.debug("found a top-level post", author=post.author, tags=post.tags)

                    if post.author != cred.id:
                        for tag in tags:
                            if tag in post.tags:
                                if post.author not in following:
                                    pending.append(post.author)
                                    following.append(post.author)
                                    break

        except PostDoesNotExist as e:
            log.debug("Post has vanished", exception=e)

        except RPCError as e:
            log.error("RPC problem while streaming posts", exception=e)
def stream_blockchain():
    blockchain = Blockchain()
    stream = map(Post, blockchain.stream(filter_by=['comment']))
    while True:
        try:
            for post in stream:
                tags = post["tags"]
                if post.is_main_post() and "utopian-io" in tags:
                    author = post["author"]
                    title = post["title"]
                    print("{} posted {}".format(author, title))
        except Exception as error:
            print(repr(error))
            continue
Esempio n. 8
0
def run():
    # upvote posts with 30% weight
    upvote_pct = 30
    whoami = 'makerhacks'

    # stream comments as they are published on the blockchain
    # turn them into convenient Post objects while we're at it
    b = Blockchain()
    stream = map(Post, b.stream(filter_by=['comment']))

    for post in stream:
        if post.json_metadata:
            mentions = post.json_metadata.get('users', [])

            # if post mentions more than 10 people its likely spam
            if mentions and len(mentions) < 10:
                post.upvote(weight=upvote_pct, voter=whoami)
Esempio n. 9
0
def run():
    steem = Steem()
    blockchain = Blockchain()
    stream = blockchain.stream(filter_by=["transfer"])

    username = "******"

    while True:
        try:
            for transfer in stream:
                if transfer["to"] == username:
                    url, permlink = transfer["memo"].split("@")
                    if "https://steemit.com/" in url:
                        steem.vote(f"@{permlink}", 100)
        except Exception as error:
            print(repr(error))
            continue
Esempio n. 10
0
def run():
    steem = Steem()
    blockchain = Blockchain()
    stream = map(Post, blockchain.stream(filter_by=["comment"]))

    REGEX = "(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9]+)"
    username = "******"

    while True:
        try:
            for post in stream:
                mentions = re.findall(REGEX, post["body"])
                if username in mentions:
                    print(f"Replying to {post['author']}")
                    post.reply(f"Hey @{post['author']}, you mentioned me?")

        except Exception as error:
            print(repr(error))
            continue
Esempio n. 11
0
def stream_blockchain():
    blockchain = Blockchain()
    stream = map(Post, blockchain.stream(filter_by=['comment']))

    while True:
        try:
            for post in stream:

                #print("Diff {}".format( (EXECUTIONSTART + MAXEXECUTION) - time.time() ))

                # did we go too long?
                if time.time() > (EXECUTIONSTART + MAXEXECUTION):
                    print("Diff {}".format((EXECUTIONSTART + MAXEXECUTION) -
                                           time.time()))
                    exit()

                # do the thing
                tags = post["tags"]
                if post.is_main_post():  # and "utopian-io" in tags:
                    author = post["author"]
                    title = post["title"]
                    body = post["body"]

                    haystack = ""
                    haystack = author + " " + title  #+ " " + body

                    # this could take a long time as the list grows
                    my_keywords = get_records()

                    for this_word in my_keywords:
                        if haystack.lower().find(this_word) > 0:
                            thislink = "https://steemit.com" + post.url
                            msg = (
                                "***{}*** found! - *{}* posted {}\n{}".format(
                                    this_word, author, title, thislink))
                            send(msg, url)
        except Exception as error:
            # print(repr(error))
            continue
Esempio n. 12
0
def run(user_json):
    username = "******"
    wif = os.environ.get("UNLOCK")
    steem = Steem(wif=wif)
    blockchain = Blockchain()
    stream = map(Post, blockchain.stream(filter_by=["comment"]))

    print("Entering blockchain stream!")
    while True:
        try:
            for post in stream:
                if valid_post(post, user_json):
                    try:
                        author = post["author"]
                        post.upvote(weight=user_json[author]["upvote_weight"],
                                    voter=username)
                    except Exception as error:
                        print(repr(error))
                        continue

        except Exception as error:
            # print(repr(error))
            continue
Esempio n. 13
0
def run():
    username = "******"
    wif = os.environ.get("UNLOCK")
    steem = Steem(wif=wif)
    blockchain = Blockchain()
    stream = map(Post, blockchain.stream(filter_by=["comment"]))
    upvote_list = json.load(open('upvote_list.json'))
    upvoted = {}
    date = int(time.strftime("%d"))
    hour = int(time.strftime("%-H"))

    print("Entering blockchain stream!")
    while True:
        try:
            for post in stream:
                if int(time.strftime("%d")) is not date:
                    upvoted = {}
                    date = int(time.strftime("%d"))
                if int(time.strftime("%-H")) is not hour:
                    upvote_list = json.load(open('upvote_list.json'))
                    hour = int(time.strftime("%-H"))

                if valid_post(post, upvote_list, upvoted):
                    try:
                        author = post["author"]
                        post.upvote(
                            weight=upvote_list[author]["upvote_weight"],
                            voter=username)
                        print("Upvoted {}".format(author))
                        upvoted[author] += 1
                    except Exception as error:
                        print(repr(error))
                        continue

        except Exception as error:
            #print(repr(error))
            continue
Esempio n. 14
0
    def run(self):
        blockchain = Blockchain(steemd_instance=self.steem)
        # stream of comments
        stream = blockchain.stream(filter_by=['comment'])
        while True:
            try:
                for comment in stream:
                    post = Post(comment, steemd_instance=self.steem)
                    if not post.is_main_post() and post['url']:
                        main_post = self.main_post(post)
                        # if self.tags is empty bot analyzes all tags
                        # otherwise bot analyzes only comments that contains at least one of given tag
                        if self.filter_by_tag(main_post['tags']):

                            # users on whitelist are ignored
                            if post['author'] in self.whitelist:
                                print('Ignored:', post['author'])
                                continue

                            # users on scamlist are flagged without immediately
                            elif post['author'] in self.scamlist:
                                print('Scam:', post['author'])
                                self.reply(
                                    post, 'Scam alert! Do not click in link!')
                                self.vote(post)

                            else:
                                message = get_message_from_post(post)
                                spam_probability = self.model.spam_probability(
                                    message)
                                blog = Blog(account_name=post['author'],
                                            comments_only=True,
                                            steemd_instance=self.steem)
                                average_spam_probability, generic_comment, rep = self.model.average_spam_probability(
                                    blog, self.num_previous_comments)
                                print('*' if average_spam_probability >
                                      self.probability_threshold else ' ',
                                      end='')
                                self.log(spam_probability,
                                         average_spam_probability,
                                         post['author'], message)

                                if spam_probability > self.probability_threshold and average_spam_probability > self.probability_threshold:
                                    self.append_to_blacklist(post['author'])
                                    self.append_message('spam', message)
                                    response = self.response(
                                        average_spam_probability,
                                        generic_comment, rep)
                                    inp = input(
                                        'y/n\n'
                                    )  # currently I approve manually
                                    if inp == 'y':
                                        if self.reply_mode:
                                            self.reply(post, response)
                                        if self.vote_mode:
                                            self.vote(post)
            except PostDoesNotExist as pex:
                continue
            except Exception as ex:
                print(repr(ex))
                continue
Esempio n. 15
0
    l("-------------------------------")

    # Ensure the account's json is initialized
    current = Account(donation_account)
    if (not isinstance(current['json_metadata'], dict)
            or 'extensions' not in current['json_metadata']
            or 'ico' not in current['json_metadata']['extensions']):
        saveState()
        l("Initialized empty participants within `json_metadata`.")
        l("-------------------------------")
    else:
        global state
        state = current['json_metadata']['extensions']['ico']
        l(state)
        l("Loaded previous participants from `json_metadata`.")
        l("-------------------------------")

    # Scheduled tasks to perform every few minutes
    scheduler = BackgroundScheduler()
    scheduler.add_job(commitParticipants,
                      'interval',
                      minutes=1,
                      id='commitParticipants')
    scheduler.add_job(processQueue, 'interval', seconds=10, id='processQueue')
    scheduler.start()

    # Watch the Blockchain
    b = Blockchain()
    for op in b.stream():
        processOp(op)
Esempio n. 16
0
# Define your tag or multiple ones
keywords = ["introduceyourself", "adventure"]

# Define your username
steemuser = <your steem user account>
# Do you want to vote on post too? Fill out user & voting weight (power).
voting = 1
power = 100




while True:
    try:
        # stream the blockchain
        stream = map(Post, b.stream(filter_by=['comment']))
        # go through all the posts in the block
        for post in stream:
            # get all the tags of the post
            postTags = post.json_metadata.get('tags', [])
            # check if one of predefined tags is in the list of tags. You can add more tags
            if keywords in postTags:
                title = post.title
                # check if the post/comment has a title
                if title == "":
                    #title is empty so it's most likely a comment
                    pass

                else:
                    #We have a title so it's a fresh posts so let's welcome them
                    post.reply("Welcome to Steemit {post['author']}!", "", "Yours @steemuser")
Esempio n. 17
0
import datetime
import json
import os

from get_activities import get_runalyze
from steem import Steem
from steem.blockchain import Blockchain
from steem.post import Post

blockchain = Blockchain()
members = open('members.json')
members = json.load(members)
stream = map(Post, blockchain.stream(filter_by=['comment']))


def converter(object_):
    if isinstance(object_, datetime.datetime):
        return object_.__str__()


post_list = []
post_age = []
while True:
    try:
        for post in stream:
            if post.is_main_post():
                ### IF MEMBER POSTS -- 25% UPVOTE! <-- PERCENTAGE SHOULD BE VARIABLE
                ### IF MEMBER POSTS WITH FITNATION TAG -- 50% UPVOTE! <-- PERCENTAGE SHOULD BE VARIABLE
                author = post["author"]
                title = post["title"]
                tags = ", ".join(post["tags"])
from steem import Steem
from steem.blockchain import Blockchain
from steem.post import Post

voting_trail = ["amosbastian", "juliank"]
template = "@{}/{}"

steem = Steem()
blockchain = Blockchain()
stream = blockchain.stream(filter_by=["vote"])

if __name__ == '__main__':
    while True:
        try:
            for vote in stream:
                voter = vote["voter"]
                author = vote["author"]
                permlink = vote["permlink"]

                if voter in voting_trail:
                    post = template.format(author, permlink)
                    if Post(post).is_main_post():
                        print("Voting on {} post that {} voted on!".format(
                            permlink, voter))
                        steem.vote(post, 100)
        except Exception as error:
            print(repr(error))
            continue
Esempio n. 19
0
from steem import Steem
from steem.blockchain import Blockchain
import time
import MySQLdb

steem = Steem(nodes=["https://httpsnode.steem.place"])
chain = Blockchain(steemd_instance=steem, mode='head')

MySQLHost = 'address'
MySQLDB = 'database'
MySQLUsername = '******'
MySQLPassword = '******'

while True:
    try:
        for op in chain.stream(filter_by=["vote"]):
            link = op["permlink"]
            author = op["author"]
            voter = op["voter"]
            weight = op["weight"] / 100
            conn = MySQLdb.connect(host=MySQLHost,
                                   db=MySQLDB,
                                   user=MySQLUsername,
                                   passwd=MySQLPassword)
            query = "INSERT INTO votes (author, permlink, voter, weight, date) VALUES (%s, %s, %s, %s, %s)"
            cursor = conn.cursor()
            cursor.execute(query, (author, link, voter, str(weight),
                                   time.strftime("%Y/%m/%d %H:%M:%S")))
            conn.commit()
            conn.close()
            print(time.ctime() + ": New vote from " + voter + " on post " +
data = []

try:
    with open("IntroduceYourselfLogged.txt", "r") as f:
        data = f.read().splitlines()
        f.close()

    for line in data:
        print(time.ctime() + " loaded user: "******" to list")
        already_commented.append(line)
except:
    pass

while True:
    try:
        for op in chain.stream(filter_by=["comment"]):
            permlink = op["permlink"]
            author = op["author"]
            post = Post("@" + author + "/" + permlink, steem)
            tags = (post["json_metadata"].get("tags", []))
            if post.is_main_post():
                if 'introduceyourself' in tags or 'introducemyself' in tags or 'introduction' in tags:
                    print(time.ctime() + ' New IntroduceYourself Post found:' +
                          author)
                    if not author in already_commented:
                        print(time.ctime() + ' Adding post from ' + author +
                              ' to database')
                        conn = MySQLdb.connect(host=MySQLHost,
                                               db=MySQLDatabase,
                                               user=MySQLUsername,
                                               passwd=MySQLPassword)
Esempio n. 21
0
class Mechanism(Interface):
	"""This class covers the internal features of SteemiTAG.
	In particular, it connects Interface to the Steem libraries."""

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

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

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

	def localBool(self, x):

		if x is False:
			return x
		else:
			return True

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


		self.tagDefined = tagDefined
		self.authorDefined = authorDefined

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

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

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

	def yieldBlock(self):

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

	def suppressedVote(self):

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

	def unsuppressedVote(self):

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

	def authorMachine(self, mode):

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

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

	def tagMachine(self):

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

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

	def tracedUsers(self):
		self.block = {}
		self.block['author'] = 'haiyangdeperci'
		self.block['permlink'] = 're-haiyangdeperci-oryginalna-sobota-1-lut-czarnego-prawa-besztany-20171006t210844114z'
		self.suppressedVote()
Esempio n. 22
0
def run():
    log.info("Timely post mode activated")

    log.debug("initializing...")
    steem = Steem(keys=[cred.key])
    account = Account(cred.id, steem)
    chain = Blockchain(steem)
    commit = Commit(steem)
    log.debug("ready", steem=steem, account=account, blockchain=chain, commit=commit)

    # Because subsequent edits to a post show up as separate post entries in the blockchain,
    # we'll keep a list of candidates keyed by the post identifier which the edits share.
    candidates = {}

    log.info("Checking post history...")
    history = map(Post, account.history(filter_by=['comment']))

    # FIXME: use steem.get_posts() instead?

    for post in history:
        if post.is_main_post():
            log.debug("found a top-level post", post=post, tags=post.tags)

            if post.tags[0] == cred.id and 'boiled' not in post.tags:
                candidates[post.identifier] = post

    if len(candidates) > 0:
        log.info("Found one or more historical posts to process", posts=candidates)

        deleting = []
        for key, post in candidates.items():
            result = process(commit, post)
            if result or result is None:
                deleting.append(key)
        for key in deleting:
            del candidates[key]

    log.info("Watching for new posts...")
    while True:
        stream = map(Post, chain.stream(filter_by=['comment']))

        try:
            for post in stream:
                if post.is_main_post() and post.author == cred.id:
                    log.debug("found a top-level post", post=post, tags=post.tags)

                    if len(post.tags) == 2 and post.tags[0] == cred.id and post.tags[1] == cred.id:
                        candidates[post.identifier] = post

                deleting = []
                for key, post in candidates.items():
                    result = process(commit, post)
                    if result or result is None:
                        deleting.append(key)
                for key in deleting:
                    del candidates[key]

        except PostDoesNotExist as e:
            log.debug("Post has vanished", exception=e)

        except RPCError as e:
            log.error("RPC problem while streaming posts", exception=e)
Esempio n. 23
0
startBet = 0.1
maxBet = 5
AboveOrBelow = 'Above' # can be 'Above' or 'Below'
OverUnderNum = 91

stopLose = 150 #set the amount(acount balance) you want to stop at when losing.
stopWin = 250 #set the amount(acount balance) you want to stop at when winning.

#betAmount = 1
#AboveOrBelow = 'Below' # can be 'Above' or 'Below'
#OverUnderNum = 95

s = Steem(node = nodes, keys=[PK])
blockchain = Blockchain()
stream = blockchain.stream()

nums = muchWon = 0
betAmount = startBet

count = roundBets = 1 #do not modify - is part of loop + display
minimumBet = 0.1
houseEdge = (1 - 0.02)

#get balance
userAcct = Account(accountname)
def didWin():
	nums = muchWon = tempWon = muchBet = 0
	whichAmt = fromWho = memoWhat = betAmount = accFrom = memoDatas = amountDatas = amountTX = tempSplit = ""
	winLose = fromEpic = None
	for post in stream: