Example #1
0
 def test_comment(self, node_param):
     if node_param == "non_appbase":
         bts = self.bts
     else:
         bts = self.appbase
     with self.assertRaises(exceptions.ContentDoesNotExistsException):
         Comment("@abcdef/abcdef", steem_instance=bts)
     c = Comment(self.authorperm, steem_instance=bts)
     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)
     self.assertTrue(isinstance(c.get_votes(), list))
     if node_param == "appbase":
         self.assertTrue(len(c.get_votes()) > 0)
         self.assertTrue(isinstance(c.get_votes()[0], Vote))
Example #2
0
 def test_comment(self, node_param):
     if node_param == "non_appbase":
         bts = self.bts
     else:
         bts = self.appbase
     with self.assertRaises(
         exceptions.ContentDoesNotExistsException
     ):
         Comment("@abcdef/abcdef", steem_instance=bts)
     c = Comment(self.authorperm, steem_instance=bts)
     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)
     for key in ['tags', 'users', 'image', 'links', 'app', 'format']:
         self.assertIn(key, list(c.json_metadata.keys()))
     self.assertTrue(c.is_main_post())
     self.assertFalse(c.is_comment())
     self.assertTrue(isinstance(c.get_reblogged_by(), list))
     self.assertTrue(len(c.get_reblogged_by()) > 0)
     self.assertTrue(isinstance(c.get_votes(), list))
     if node_param == "appbase":
         self.assertTrue(len(c.get_votes()) > 0)
         self.assertTrue(isinstance(c.get_votes()[0], Vote))
Example #3
0
    def read_posts(self, start=0):
        if not self.exists:
            return []

        c_list = {}
        posts = []

        if self.reblog:
            blogs = self.account.history_reverse(only_ops=["custom_json"])
        elif self.limit:
            blogs = self.account.get_blog(start_entry_id=start,
                                          limit=self.limit)
        else:
            blogs = self.account.blog_history(start=start,
                                              limit=self.limit,
                                              reblogs=self.reblog)

        days_done = False
        for c in blogs:
            if self.reblog:
                if c['id'] == "follow":
                    json_data = json.loads(c['json'])
                    if len(json_data) > 0 and json_data[0] == "reblog":
                        info = json_data[1]
                        authorperm = "@{}/{}".format(info["author"],
                                                     info["permlink"])
                        timestamp = c["timestamp"]
                        c = Comment(authorperm)
                        c["reblogged"] = timestamp
                    else:
                        continue
                else:
                    continue
            if c.authorperm in c_list:
                continue
            if not c.is_comment():
                if ((not self.reblog) and c.author == self.username) or (
                        self.reblog and c.author != self.username):
                    sc = SteemComment(comment=c)
                    tags = sc.get_tags()
                    if self.tag is None or self.tag in tags:
                        if self.keyword is None or self.keyword in c.title:
                            days_done = self.days is not None and not in_recent_n_days(
                                c, self.days, self.reblog)
                            if days_done:
                                break
                            else:
                                c = sc.refresh()
                                sc.log()
                                c_list[c.authorperm] = 1
                                posts.append(c)

        print('{} posts are fetched'.format(len(posts)))
        return posts
Example #4
0
def update_comment(post):
    """
    Updates the comment left by the bot to reflect that the contribution was
    unvoted.
    """
    body = (f"Hey @{post.author}, your contribution was unvoted because we "
            "found out that it did not follow the "
            "[Utopian rules](https://join.utopian.io/rules).\n\n Upvote this "
            "comment to help Utopian grow its power and help other Open "
            "Source contributions like this one.\n\n**Want to chat? Join us "
            "on [Discord](https://discord.gg/Pc8HG9x).**")

    # Iterate over replies until bot's comment is found
    for comment in get_replies(post):
        comment = Comment(comment)
        if comment.author == ACCOUNT and comment.is_comment():
            try:
                logger.info(f"Updating comment {comment.authorperm}")
                comment.edit(body, replace=True)
            except Exception as error:
                logger.error(error)
            return
Example #5
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))
Example #6
0
            if h["to"] != upvote_account:
                continue
            last_steem_block = int(h["block"])
            if len(whitelist) > 0 and h["from"] not in whitelist:
                print("%s is not in the whitelist, skipping" % h["from"])
                continue
            if float(h["quantity"]) < min_token_amount:
                print("Below min token amount skipping...")
                continue
            try:
                c = Comment(h["memo"], steem_instance=stm)
            except:
                print("%s is not a valid url, skipping" % h["memo"])
                continue

            if c.is_comment() and only_main_posts:
                print("%s from %s is a comment, skipping" %
                      (c["permlink"], c["author"]))
                continue
            if (c.time_elapsed().total_seconds() / 60 / 60 /
                    24) > max_post_age_days:
                print("Post is to old, skipping")
                continue
            if (c.time_elapsed().total_seconds() / 60) < min_post_age:
                print("Post is to new, skipping")
                continue
            tags_ok = True
            if len(blacklist_tags) > 0 and "tags" in c:
                for t in blacklist_tags:
                    if t in c["tags"]:
                        tags_ok = False
Example #7
0
def make_table():  # loading table of voted posts
    table_string = '\n| Account | Beitrag (Steemit.com) | Bild (Busy.org) | {}'\
                   '|---------|--------------| ---- | {}'\
        .format('Gewicht |\n' if config.getboolean('POSTER', 'show_weight') else '\n',
                '--- |\n' if config.getboolean('POSTER', 'show_weight') else '\n')

    latest_vote = config['POSTER']['last_post_vote']
    first = True
    posts = []
    hidden_authors = []
    try:
        with open(file=config['POSTER']['hidden_votes_file'],
                  mode='r') as file:
            hidden_authors = file.read().split('\n')
    except FileNotFoundError as e:
        log.exception(e)

    # generate table
    if config['POSTER']['last_post_vote'] == '':
        config['POSTER']['last_post_vote'] = (
            datetime.now() - timedelta(days=1)).strftime('%Y-%m-%dT%H:%M:%S')

    for vote in a.history_reverse(start=t,
                                  stop=datetime.strptime(
                                      config['POSTER']['last_post_vote'],
                                      '%Y-%m-%dT%H:%M:%S'),
                                  only_ops=['vote']):
        log.debug(vote)
        if first:
            first = False
            latest_vote = vote['timestamp']

        if vote['voter'] != a.name:
            continue
        if vote['timestamp'] <= config['POSTER']['last_post_vote']:
            continue

        authorperm = '{}/{}'.format(vote['author'], vote['permlink'])

        if authorperm in posts:
            continue
        posts.append(authorperm)
        if vote['weight'] <= 0:
            continue
        if vote['author'] in hidden_authors:
            continue

        c = Comment(authorperm=authorperm)
        if c.is_comment() and not config.getboolean(
                'POSTER', 'list_comments'):  # abort comment votes
            log.debug('is comment')
            continue

        link_steemit = '[{}](https://steemit.com/{})'.format(
            c.title.replace('|',
                            '-').replace('[',
                                         '(').replace(']',
                                                      ')').replace('\n', ' '),
            c.authorperm)

        image = '[Kein Bild](https://busy.org/{})'.format(c.authorperm)

        # ========================================================

        try:
            image = '[![Lädt ...](https://steemitimages.com/500x0/{})](https://busy.org/{})'\
                .format(c.json_metadata['image'][0], c.authorperm)
        except KeyError or IndexError:
            log.info(
                'No images in JSON metadata. Searching markdown image links.')
            md.convert(c.body)
            img_count = len(md.images)
            while img_count:
                if md.images[0].startswith(('http://', 'https://')):
                    image = '[![Lädt ...](https://steemitimages.com/500x0/{})](https://busy.org/{})'\
                        .format(md.images[0], c.authorperm)
                    break
                else:
                    md.images.pop(0)
            else:
                log.info('No images in markdown. Searching HTML image links.')
                soup = BeautifulSoup(c.body)
                images = []
                for link in soup.findAll(
                        'img', attrs={'src': re.compile("^http(s?)://")}):
                    images.append(link.get('src'))
                img_count = len(images)
                while img_count:
                    if images[0].startswith(('http://', 'https://')):
                        image = '[![Lädt ...](https://steemitimages.com/500x0/{})](https://busy.org/{})'\
                            .format(images[0], c.authorperm)
                        break
                    else:
                        images.pop(0)
                else:
                    log.info('No images found.')

        # ========================================================

        table_string += '| @{} | {} | {} |'.format(c.author, link_steemit,
                                                   image)
        table_string += '{!s}%|\n'.format(
            vote['weight'] /
            100) if config.getboolean('POSTER', 'show_weight') else '\n'

    if not config.getboolean('GENERAL', 'testing'):
        with open(file='config.ini', mode='w') as file:
            config['POSTER']['last_post_vote'] = latest_vote
            config.write(file)
    return table_string
            # print(rule)
            if not string_included(rule["include_authors"], post["author"]):
                print("Skip %s - include_authors" % rule["account"])
                continue
            if not string_excluded(rule["exclude_authors"], post["author"]):
                print("Skip %s - exclude_authors" % rule["account"])
                continue

            if not tags_included(rule["include_tags"], post["tags"]):
                print("Skip %s - include_tags %s" %
                      (rule["account"], rule["include_tags"]))
                continue
            if not tags_excluded(rule["exclude_tags"], post["tags"]):
                print("Skip %s - exclude_tags" % rule["account"])
                continue
            if rule["only_main_post"] and post.is_comment():
                print("Skip %s - only_main_post" % rule["account"])
                continue
            if rule["exclude_authors_with_vote_rule"]:
                vote_rule = voteRulesTrx.get(rule["account"], post["author"],
                                             not post.is_comment())
                if vote_rule is not None and vote_rule["enabled"]:
                    print("Skip %s - exclude_authors_with_vote_rule" %
                          rule["account"])
                    continue
            if "exclude_declined_payout" in rule and "max_accepted_payout" in post and rule[
                    "exclude_declined_payout"] and int(
                        post["max_accepted_payout"]) == 0:
                print("Skip %s - exclude_declined_payout" % rule["account"])
                continue