Example #1
0
async def get_info(msg):
    link = str(msg.content).split(' ')[0]
    p = Post(link.split('@')[1])
    if check_age(p, 2, 48):
        embed = discord.Embed(color=0xe3b13c)
        embed.add_field(name="Title", value=str(p.title), inline=False)
        embed.add_field(name="Author", value=str("@" + p.author), inline=True)
        embed.add_field(name="Nominator",
                        value=str('<@' + msg.author.id + '>'),
                        inline=True)
        embed.add_field(name="Age",
                        value=str(p.time_elapsed())[:-10] + " hours",
                        inline=False)
        embed.add_field(name="Payout", value=str(p.reward), inline=True)
        embed.add_field(name="Payout in USD",
                        value=await payout(p.reward, sbd_usd, ste_usd),
                        inline=True)
        embed.set_footer(
            text="Marshal - a Steem bot by Vctr#5566 (@jestemkioskiem)")
        return embed
    else:
        age_error = await client.send_message(
            msg.channel, 'Your post has to be between 2h and 48h old.')
        await client.delete_message(msg)
        await asyncio.sleep(6)
        await client.delete_message(age_error)
Example #2
0
    def upvote(self, op):
        try:
            post = Post(op['memo'])
        except ValueError:
            logger.info('Invalid identifier: %s', op['memo'])
            self.refund(op, message='invalid url')
            return
        try:
            weight = self.upvote_weight

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

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

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

        logger.info('Upvoted %s with weight: %s', op['memo'], weight)
Example #3
0
 def upvote(self, weight, identify):
     post = Post(post=identify, steemd_instance=self.s)
     voters_list = self.voters(identify)
     voted = {}
     for username in self.keys_username:
         try:
             post.vote(weight, username)
             voted[username] = {
                 "status": True,
                 "weight": weight,
                 "not": "voted"
             }
         except:
             if username in voters_list:
                 voted[username] = {
                     "status": False,
                     "weight": weight,
                     "not": "already voted"
                 }
             else:
                 voted[username] = {
                     "status": False,
                     "weight": weight,
                     "not": "Unknown"
                 }
     return voted
	def GetStats(self):
		start_time = time.time()
		comment_string = ""
		postdetails = self.url_var.split("/")
		#postdetails = ['', '', 'ekklesiagora', 'on-poverty-gentrification-addiction-and-homelessness']
		#authortemp = '@ekklesiagora'
		print(postdetails)
		temp_dict = {'author': postdetails[2], 'permlink': postdetails[3]}
		getpost = Post(temp_dict, steem)
		print(getpost.items())
		totalvotes = len(getpost['active_votes'])
		comment_string += "<h3> Hello @"+self.initiator+" | Here are the stats of the <a href='https://steemit.com"+self.url_var+"'> Main Post </a></h3>"
		comment_string += "<h5> Total Votes: "+str(totalvotes)+"</h5>"
		
		if totalvotes == 0:
			pass
		else:
			if totalvotes == 1:
				high_weight = self.Highest_Voting_Weight(getpost['active_votes'])
				comment_string += "<h5> Highest Voting Weight: @"+str(high_weight)+"</h5>"
			else:
				high_weight = self.Highest_Voting_Weight(getpost['active_votes'])
				comment_string += "<h5> Highest Voting Weight: @"+str(high_weight)+"</h5>"
				low_weight = self.Lowest_Voting_Weight(getpost['active_votes'])
				comment_string += "<h5> Lowest Voting Weight: @"+str(low_weight)+"</h5>"
		
		comment_string += "<h5>Votes Details: </h5>"
		post_creation_date = self.Get_Created_Date(getpost['created'])
		print(comment_string)
		author_adj = postdetails[2].replace("@","")
		resteems = steem.get_reblogged_by(author_adj, postdetails[3])
		print(len(resteems))
		print("================================================================\n")
		comments_detail = steem.get_content_replies(author_adj, postdetails[3])
		print(len(comments_detail))
Example #5
0
    def designated_post_for_self_vote_report(self):
        today = datetime.utcnow().date().strftime("%Y-%m-%d")
        post_title = self.self_voter_report_options.get("title").format(
            date=today)
        permlink = "self-voter-list-%s" % today

        try:
            return Post(
                "%s/%s" % (self.bot_account, permlink),
                steemd_instance=self.steemd_instance,
            )
        except steembase.exceptions.PostDoesNotExist:
            pass

        try:
            self.steemd_instance.commit.post(
                post_title,
                open(self.self_voter_report_options.get(
                    "post_template")).read(),
                self.bot_account,
                tags=self.self_voter_report_options.get("tags"),
                permlink=permlink,
            )
        except Exception as e:
            if 'You may only post once every 5 minutes' in e.args[0]:
                logger.info("Sleeping for 300 seconds to create a new post.")
                time.sleep(300)
                return self.designated_post_for_self_vote_report
            raise

        return Post("%s/%s" % (self.bot_account, permlink),
                    steemd_instance=self.steemd_instance)
Example #6
0
 def content_save(self, request, *args, **kwargs):  # for me
     self.community = request.community_model
     self.tag = self.ready_tags()
     self.dor = self.durationofread(self.content + self.title)
     self.permlink = slugify(self.title.lower())
     self.definition = self.prepare_definition(self.content)
     while True:  # hem coogger'da hemde sistem'de olmaması gerek ki kayıt sırasında sorun çıkmasın.
         try:  # TODO:  buralarda sorun var aynı adres steemit de yokken coogger'da vardı ve döngüden çıkamadı.
             Content.objects.filter(
                 user=self.user, permlink=self.permlink)[0]  # db de varsa
             try:
                 Post(post=self.get_absolute_url()).url  # sistem'de varsa
                 self.new_permlink(
                 )  # change to self.permlink / link değişir
             except:
                 pass
         except:
             try:
                 Post(post=self.get_absolute_url()).url  # sistem'de varsa
                 self.new_permlink(
                 )  # change to self.permlink / link değişir
             except:
                 break
     steem_save = self.steemconnect_post(self.permlink, "save")
     if steem_save.status_code == 200:
         super(Content, self).save(*args, **kwargs)
     return steem_save
Example #7
0
    def get_post(self, post):
        if not post.author or post.author != self.author:
            return
        kwargs = {'author': post.author, 'permlink': post.slug}

        try:
            blockchain_post = Post(post=kwargs, steemd_instance=self.steem)
        except:
            return
        votes = blockchain_post.get(
            'net_votes')  # len(post.get('active_votes'))
        post.votes = votes

        # pending reward
        reward_pending_amount = blockchain_post.get(
            'total_pending_payout_value')
        amount = reward_pending_amount.get('amount')
        asset = reward_pending_amount.get('asset')
        if amount > 0:
            post.reward = amount

        self.set_asset(post, asset)

        # payouts reward
        total_payout_value = blockchain_post.get('total_payout_value')
        amount = total_payout_value.get('amount')
        asset = total_payout_value.get('asset')
        self.set_asset(post, asset)

        if amount > 0:
            post.reward = amount
            post.complete = True

        if not post.reward:
            post.save()
            return

        if post.provider == 'golos':
            # calc BTC
            local_course = self.get_local_course()
            if local_course:
                base_course = local_course.get('base')
                if base_course:
                    gbg_course = float(base_course.split(' ')[0])
                    gbg_golos = post.reward / gbg_course

                    api = Bittrex(settings.BITTREX_KEY,
                                  settings.BITTREX_SECRET)
                    btc_cost = api.get_ticker('BTC-GOLOS').get('result').get(
                        'Ask')
                    post.btc = btc_cost * gbg_golos

                    # calc RUB reward
                    rub_course = Coinapult().get_current_price(currency='RUB')
                    post.rub = post.btc * float(rub_course)
        else:
            return  # TODO set it for steem

        post.save()
async def on_message(message):
    msg = message
    msgcon = msg.content
    msgaut = '@' + msg.author.name

    if bot_role not in [
        y.name.lower() for y in message.author.roles] and \
                    message.channel.id in allowed_channels:

        if message.content.startswith('https://steemit') or \
                message.content.startswith('steemit'):
            smsgcon = msgcon.split('@')[1]
            tmsgcon = msgcon.split('/')[3]
            sp = Post(smsgcon)

            if sp.time_elapsed() > datetime.timedelta(hours=2) and \
                    sp.time_elapsed() < datetime.timedelta(hours=48):
                tempmsg = await client.send_message(
                    message.channel,
                    'The post is ' + str(sp.time_elapsed())[:-7] +
                    ' hours old and earned ' + str(sp.reward))

                res = await client.wait_for_reaction(['☑'], message=msg)
                if moderating_roles[0] in [
                        y.name.lower() for y in res.user.roles
                ] or moderating_roles[1] in [
                        y.name.lower() for y in res.user.roles
                ]:
                    await client.delete_message(msg)
                    await client.delete_message(tempmsg)

                    if tmsgcon in tag_list:
                        dest_channel = tag_list.index(tmsgcon)
                    else:
                        dest_channel = tag_list.len()

                    await client.send_message(
                        client.get_channel(channels_list[dest_channel]),
                        content=msgaut + ' sent: ' + msgcon)

            else:
                tempmsg = await client.send_message(
                    message.channel,
                    'Your post has to be between 2h and 48h old.')
                await client.delete_message(msg)

        elif message.content.startswith('!ping') and moderating_roles[0] in [
                y.name.lower() for y in message.author.roles
        ] or moderating_roles[1] in [
                y.name.lower() for y in message.author.roles
        ]:
            await client.send_message(message.channel, ':ping_pong: Pong!')

        elif bot_role not in [y.name.lower() for y in message.author.roles]:
            await client.delete_message(msg)
            await client.send_message(message.channel,
                                      content=msgaut +
                                      ' Your link has to start with '
                                      '"https://steemit" or "steemit"')
Example #9
0
 def get_video(self, name, path):
     video_metadata = User.get_video_unauthorized(name, path)
     self._cur_post = Post(
         {
             'author': video_metadata['author'],
             'permlink': video_metadata['name'],
         }, self._steem)
     return self._cur_post
Example #10
0
 def test_getPost(self):
     self.assertEqual(
         Post("@xeroc/piston", steem_instance=steem).url,
         "/piston/@xeroc/piston")
     self.assertEqual(
         Post({
             "author": "@xeroc",
             "permlink": "piston"
         },
              steem_instance=steem).url, "/piston/@xeroc/piston")
Example #11
0
def upsert_comment(mongo, identifier):
    """ Upsert root post or comment. """
    with suppress(PostDoesNotExist):
        p = Post(identifier)
        update = {'$set': strip_dot_from_keys(p.export())}
        if p.is_comment():
            return mongo.Comments.update(
                {'identifier': p.identifier},
                update, upsert=True)
        return mongo.Posts.update({'identifier': p.identifier}, update, upsert=True)
Example #12
0
    def handle_curation(self, op_type, op_value):

        curators = [c["account"] for c in get_curators()]

        # we're only interested in votes
        if op_type != "vote":
            return

        # if the voter is not a trusted curator, skip it.
        if op_value.get("voter") not in curators:
            return

        # check the post if we have already voted?
        p = Post("%s/%s" % (op_value.get("author"), op_value.get("permlink")),
                 steemd_instance=self.s)

        # we're only interested in main posts
        if not p.is_main_post():
            return

        # the post is tagged with the tags we defined?
        if len(set(self.expected_tags).intersection(p.get("tags"))) == 0:
            return

        # is the author in the blacklist?
        if is_blacklisted(op_value.get("author")):
            return

        score = 0
        already_voted = False
        curators_on_the_post = []
        for active_vote in p.get("active_votes", []):
            if active_vote.get("voter") == self.bot_account:
                already_voted = True
            if active_vote.get("voter") in curators:
                score += active_vote.get("percent")
                curators_on_the_post.append({
                    "curator":
                    active_vote.get("voter"),
                    "weight":
                    active_vote.get("percent"),
                })

        # if we already voted on that, skip.
        if already_voted:
            return

        # if the score is lower then the threshold, skip.
        if score < int(get_option(THRESHOLD_OPTION_ID)["value"]):
            return

        bot_account = Account(self.bot_account, steemd_instance=self.s)
        weight = bot_account.voting_power()
        self.upvote(p, weight, self.bot_account)
        self.post_to_webhooks(p, curators_on_the_post, score, weight)
Example #13
0
    def get_latest_flags(self):
        flags = {}
        total_amount = 0
        account = Account(self.account_for_flag_report,
                          steemd_instance=self.steemd_instance)
        for vote in account.history_reverse(filter_by="vote"):
            if vote["weight"] > 0:
                continue
            if vote["voter"] != self.account_for_flag_report:
                continue
            ts = parse(vote["timestamp"])
            if ts < (datetime.utcnow() - timedelta(days=1)):
                break

            try:
                p = Post("%s/%s" % (vote["author"], vote["permlink"]),
                         steemd_instance=self.steemd_instance)
            except steembase.exceptions.PostDoesNotExist:
                logger.info("Couldnt load the post. %s" % vote["permlink"])
                continue

            if vote["author"] not in flags:
                flags[vote.get("author")] = {
                    "posts": 0,
                    "comments": 0,
                    "total_removed": 0
                }

            if p.is_main_post():
                flags[vote.get("author")].update(
                    {"posts": flags[vote.get("author")]["posts"] + 1})
            else:
                flags[vote.get("author")].update(
                    {"comments": flags[vote.get("author")]["comments"] + 1})

            logger.info("Analyzing %s" % self.url(p))

            for active_vote in p.get("active_votes"):
                if float(active_vote.get("rshares")) > 0:
                    continue

                if active_vote.get("voter") != self.account_for_flag_report:
                    continue

                amount_removed = self.get_payout_from_rshares(
                    active_vote.get("rshares"))
                total_amount += amount_removed

                flags[vote.get("author")].update({
                    "total_removed":
                    flags[vote.get("author")]["total_removed"] +
                    amount_removed,
                })

        return flags, round(total_amount, 2)
async def get_info(msg):
	link = str(msg.content).split(' ')[0]
	p = Post(link.split('@')[1])
	embed=discord.Embed(color=0xe3b13c)
	embed.add_field(name="Title", value=str(p.title), inline=False)
	embed.add_field(name="Author", value=str("@"+p.author), inline=True)
	embed.add_field(name="Nominator", value=str('<@'+ msg.author.id +'>'), inline=True)
	embed.add_field(name="Age", value=str(p.time_elapsed())[:-10] +" hours", inline=False)
	embed.add_field(name="Payout", value=str(p.reward), inline=True)
	embed.add_field(name="Payout in USD", value=await payout(p.reward,sbd_usd,ste_usd), inline=True)
	return embed
Example #15
0
def upsert_comment(mongo, identifier):
    """ Upsert root post or comment. """
    with suppress(PostDoesNotExist):
        p = Post(identifier)
        if p.is_comment():
            return mongo.Comments.update({'identifier': p.identifier},
                                         p.export(),
                                         upsert=True)
        return mongo.Posts.update({'identifier': p.identifier},
                                  p.export(),
                                  upsert=True)
Example #16
0
def update_last_post(post_id):
    global _last_post_id
    global _last_post_created

    identifier = construct_identifier(post_id['username'], post_id['permlink'])

    if identifier is not _last_post_id:
        steemd_instance = get_steem_conn()
        steem_post = Post(identifier, steemd_instance=steemd_instance)

        _last_post_id = identifier
        _last_post_created = steem_post.get('created')
async def check_age(msg,low,high):
	link = str(msg.content).split(' ')[0]
	p = Post(link.split('@')[1])

	if p.time_elapsed() > datetime.timedelta(hours=low) and p.time_elapsed() < datetime.timedelta(hours=high):
		return True
	else:
		age_error = await client.send_message(msg.channel, 'Your post has to be between 2h and 48h old.')
		await client.delete_message(msg)
		await asyncio.sleep(6)
		await client.delete_message(age_error)
		return False
Example #18
0
def pending_payout(username):
    context = {}
    for post in steem.get_blog(username, 500, 500):
        post = Post(post["comment"])
        if post.is_main_post() and post["author"] == username:
            if "1970-01-01 00:00:00" == str(post["last_payout"]):
                payout = Amount(post["pending_payout_value"]).amount
                if payout == 0:
                    payout = (Amount(post["total_payout_value"]).amount +
                              Amount(post["curator_payout_value"]).amount)
                context[post.title] = payout * 0.56 * 0.5
    return context
Example #19
0
def getUpvoteCandidate(account):
    """ Gets link to comments author has not voted on but is within voting window
    Args:
        account: A Steem Account object.
    Returns:
        identifier of posts/comments within voting window not already voted on
    """
    # Make sure we have the latest data
    account.refresh()
    epoch_last_vote = 0

    # Get last 2000 votes from account
    history = account.get_account_history(-1, 1000, filter_by='comment')

    current_time = epochDiff()
    oldest_id = []
    print('got history, now filtering...')
    for event in history:
        try:
            # Make sure we are the author
            if (event['author'] == account.name):
                # Not really needed due to filter
                if (event['type'] == 'comment'):
                    # Double confirmation of comment
                    if event['permlink'].startswith("re-"):
                        epoch_last_vote = epochVote(event)
                        elapsed_time = current_time - epoch_last_vote
                        # Is post in within time limit
                        if elapsed_time < cutofftime:
                            # Get details of main post
                            identifier = "@" + event[
                                'parent_author'] + "/" + event[
                                    'parent_permlink']
                            parent = Post(identifier, s)
                            while not parent.is_main_post():
                                identifier = "@" + parent[
                                    'parent_author'] + "/" + parent[
                                        'parent_permlink']
                                parent = Post(identifier, s)
                            # Make sure Original post is in desired tag
                            if targeted_tag in parent['tags']:
                                identifier = "@" + event[
                                    'author'] + "/" + event['permlink']
                                # Store comment if it meets conditions
                                oldest_id.append(identifier)
                        else:
                            # Everything else will be older than cutoff
                            break
        except Exception as e:
            print('issue with history: ' + str(e))
#    print(oldest_id)
    print('completed history search')
    return list(reversed(oldest_id))
Example #20
0
class User:
    def __init__(self, username, password, steem):
        self._username = username
        self._passwd = password
        self._steem = steem
        self._ipfsapi = get_ipfsapi()
        self._cur_post = None

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

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

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

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

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

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

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

        return self._cur_post.downvote(self._username)

    def get_miniature_url(self, path):
        return 'https://static.tumblr.com/5cc5658c2c9cd06cfc68747c9059bd6f/i9ytv5i/szXn6nvfq/tumblr_static_tumblr_static__640.jpg'
Example #21
0
def upsert_post(mongo, post_identifier, steem=None):
    with suppress(PostDoesNotExist):
        p = Post(post_identifier, steem_instance=steem)

        # scrape post and its replies
        entry = {
            **p.export(),
            'replies': [],
            # 'replies': [x.export() for x in _fetch_comments_flat(p)],
        }
        return mongo.Posts.update({'identifier': p.identifier},
                                  entry,
                                  upsert=True)
Example #22
0
def steemi_vote_up_steempython(post_id):
    identifier = construct_identifier(post_id['username'], post_id['permlink'])
    steemd_instance = get_steem_conn()

    steem_post = Post(identifier, steemd_instance=steemd_instance)

    already_voted = False
    for active_vote in steem_post.get("active_votes", []):
        if active_vote.get("voter") == STEEM_BOT_ACCOUNT:
            already_voted = True
            break

    if not already_voted:
        steem_post.vote(100, STEEM_BOT_ACCOUNT)
Example #23
0
def profile_as_json():

    steemd_instance = get_steemd_instance()

    if request.method == "GET":
        links = request.args.get("links")
    else:
        links = request.form.get("links")

    rewards = []
    links = links.split(",")
    for link in links:
        try:
            post = Post(link, steemd_instance=steemd_instance)
        except PostDoesNotExist:
            abort(404)

        total, curation, author, beneficiaries, sbd_amount, sp_amount, \
            usd_amount = calculate_rewards(steemd_instance, post)

        rewards.append({
            "link":
            link,
            "total":
            total,
            "curation":
            curation,
            "author":
            author,
            "beneficiaries":
            beneficiaries,
            "cashout_time":
            post["cashout_time"],
            "is_main_post":
            post.is_main_post(),
            "title":
            post["title"],
            "elapsed_seconds":
            int(post.time_elapsed().total_seconds()),
            "sbd_amount":
            sbd_amount,
            "sp_amount":
            sp_amount,
            "usd_amount":
            usd_amount,
        })

    rewards = sorted(rewards, key=lambda k: k['elapsed_seconds'])

    return jsonify({"rewards": rewards})
def upsert_comment_chain(mongo, identifier, recursive=False):
    """ Upsert given comments and its parent(s).
    
    Args:
        mongo: mongodb instance
        identifier: Post identifier
        recursive: (Defaults to False). Recursively update all parent comments.
    """
    with suppress(PostDoesNotExist):
        p = Post(identifier)
        upsert_comment(mongo, p.identifier)
        if recursive and p.is_comment():
            parent_identifier = '@%s/%s' % (p.parent_author, p.parent_permlink)
            upsert_comment_chain(mongo, parent_identifier, recursive)
Example #25
0
def test_post_refresh():
    """ Post should load correctly if passed a dict or string identifier. """
    p1 = Post('https://steemit.com/marketing/@steemitblog/'
              'marketing-w-mitchell-a-steem-ecosystem')
    p2 = Post({
        'author': 'steemitblog',
        'permlink': 'marketing-w-mitchell-a-steem-ecosystem'
    })

    # did post load?
    assert 'json_metadata' in p1 and 'json_metadata' in p2

    # are posts the same
    assert p1.export() == p2.export()
Example #26
0
    def __next__(self):
        while not self.history:
            self.refresh()

        while self.history:
            # consume an item from history
            next_item = first(self.history)
            self.history = list(rest(self.history))

            # stay in while loop until we find a post that exists
            with suppress(PostDoesNotExist):
                p = Post(next_item)
                p.refresh()
                return p
Example #27
0
    def handle_data(self, plain_post):
        # Skip long comments
        if len(plain_post.get('body', '')) > 1024:
            return
        # Skip comments with no signal
        signal_found = self.check_signal(plain_post)
        if not signal_found:
            return

        post = Post(plain_post)
        # Skip comments of which depth is not 1
        if post.get('depth', 0) != 1:
            return
        parent_post_id = '@%s/%s' % (post['parent_author'],
                                     post['parent_permlink'])
        try:
            parent_post = Post(parent_post_id)
        except:
            self.log.error('Failed to get the parent post %s' % parent_post_id)
            return

        tags = parent_post.json_metadata.get('tags')
        if tags == None:
            self.log.error("No tag: " + parent_post)
            return

        if tags and self.config['main_tag'] in tags or \
            any(x.startswith(self.config['tag_prefix']) for x in tags):
            self.log.info('Found a matching comment: %s' %
                          plain_post.get('body'))
            # Save signal
            plain_post['bot_signal'] = signal_found
            plain_post['parent_post_id'] = parent_post_id
            # Select signal type
            if plain_post['bot_signal'] in self.config['report_signals']:
                plain_post['signal_type'] = 'spam'
            elif plain_post['bot_signal'] in self.config['praise_signals']:
                plain_post['signal_type'] = 'praise'
            elif plain_post['bot_signal'] in self.config['promote_signals']:
                plain_post['signal_type'] = 'promote'
            elif plain_post['bot_signal'] in self.config['welcome_signals']:
                plain_post['signal_type'] = 'welcome'
            else:
                plain_post['signal_type'] = 'unknown'
            if not self.is_valid(plain_post):
                self.log.info('Ignore not valid request')
                return
            # sink down
            self.db.queue_push('post', plain_post)
Example #28
0
async def get_info(msg):
    link = str(msg.content).split(' ')[0]
    p = Post(link.split('@')[1])

    embed = discord.Embed(color=0xe3b13c)
    embed.add_field(name="Title", value=str(p.title), inline=False)
    embed.add_field(name="Author", value=str("@" + p.author), inline=True)
    embed.add_field(name="Nominator",
                    value=str('<@' + msg.author.id + '>'),
                    inline=True)
    embed.add_field(name="Age",
                    value=str(p.time_elapsed())[:-10] + " hours",
                    inline=False)
    embed.set_footer(text="Onelovebot")
    return embed
Example #29
0
def curate(mysql_uri, vote_caster, posting_key, weight=+50,
         self_vote=False, limit=20, apply_to_categories=None,
         vote_delay=+30, nodes=None):
    last_posts = get_last_approved_posts(limit)
    s = Steem(keys=[posting_key], nodes=nodes)
    for utopian_post in last_posts:

        if utopian_post["author"] == vote_caster and not self_vote:
            logger.info("Skipping %s. No self-vote.", post.identifier)
            continue

        post = Post(
            "@%s/%s" % (utopian_post["author"], utopian_post["permlink"]))

        elapsed_minutes = int(post.time_elapsed().seconds / 60)
        if elapsed_minutes < vote_delay:
            logger.info(
                "Skipping %s. I will wait until %s minutes.",
                post.identifier,
                vote_delay - elapsed_minutes
            )
            continue

        if already_voted(mysql_uri, post):
            logger.info("Skipping %s. Already voted.", post.identifier)
            continue

        if apply_to_categories:
            if utopian_post["json_metadata"]["type"] \
                    not in apply_to_categories:
                logger.info(
                    "Skipping %s, This posts category: %s",
                    post.identifier,
                    utopian_post["json_metadata"]["type"]
                )
                continue

        try:
            s.commit.vote(post.identifier, weight, account=vote_caster)
            add_log(mysql_uri, post)
            logger.info(
                "Casted vote on: %s with weight: %s", post.identifier, weight)
            time.sleep(3)
        except Exception as error:
            if 'already voted' in error.args[0]:
                add_log(mysql_uri, post)
            logger.error(error)
            continue
Example #30
0
async def authorize_post(msg, user):
    dest_channel = None
    msg_tag = msg.content.split('/')[3]
    p = Post(msg.content.split('@')[1])

    for channel in channels:
        if channel['name'] == msg_tag:
            dest_channel = channel['id_verified']
            break
    if dest_channel == None:
        dest_channel = channels[len(channels) -
                                1]['id_verified']  # others as default

    embed = await get_info(msg)
    if embed:
        await client.send_message(client.get_channel(dest_channel),
                                  content=msg.content)  # send original message
        await client.send_message(client.get_channel(dest_channel),
                                  embed=embed)  # send embed
        await client.send_message(client.get_channel(dest_channel),
                                  content="This post was accepted by <@" +
                                  user.id + ">")  # send comment

        # delete old messages
        for msg_id in react_dict[msg.id]:
            msg = await client.get_message(msg.channel, msg_id)
            await client.delete_message(msg)

        if dest_channel:
            response = await client.send_message(
                msg.channel,
                "Post was moved to channel <#" + dest_channel + ">")
            await asyncio.sleep(6)
            await client.delete_message(response)
Example #31
0
async def sort_post(msg):
    dest_channel = None
    msg_tag = msg.content.split('/')[3]
    p = Post(msg.content.split('@')[1])

    for channel in channels:
        if channel['name'] == msg_tag:
            dest_channel = channel['id_community']
            break
    if dest_channel == None:
        dest_channel = channels[len(channels) -
                                1]['id_community']  # others as default

    embed = await get_info(msg)
    if embed:
        new_msg = await client.send_message(client.get_channel(dest_channel),
                                            content=msg.content
                                            )  # send original message
        embed_msg = await client.send_message(client.get_channel(dest_channel),
                                              embed=embed)  # send embed
        comment_msg = await client.send_message(
            client.get_channel(dest_channel),
            content="This post was submitted in the server by <@" +
            msg.author.id + ">")  # send comment

        react_dict[new_msg.id] = [new_msg.id, embed_msg.id,
                                  comment_msg.id]  # store new messages ids
        await client.delete_message(msg)  # delete old message

        if dest_channel:
            response = await client.send_message(
                msg.channel,
                "Post was moved to channel <#" + dest_channel + ">")
            await asyncio.sleep(6)
            await client.delete_message(response)