Esempio n. 1
0
 def check_balances(self, account=None):
     if account is None:
         account = self.mainaccount
     try:
         self.votepower
     except:
         pass
     else:
         if account == self.checkedaccount:
             return [
                 self.sbdbal, self.steembal, self.steempower,
                 self.votepower, self.lastvotetime
             ]
     self.checkedaccount = account
     try:
         acct = self.steem_instance().get_account(account)
     except Exception as e:
         self.msg.error_message(e)
         return False
     else:
         c = Converter()
         self.sbdbal = Amount(acct['sbd_balance']).amount or 0
         self.steembal = Amount(acct['balance']).amount or 0
         self.votepower = acct['voting_power']
         self.lastvotetime = acct['last_vote_time']
         vs = Amount(acct['vesting_shares']).amount
         dvests = Amount(acct['delegated_vesting_shares']).amount
         rvests = Amount(acct['received_vesting_shares']).amount
         vests = (float(vs) - float(dvests)) + float(rvests)
         self.steempower = c.vests_to_sp(vests) or 0
         time.sleep(5)
         return [
             self.sbdbal, self.steembal, self.steempower, self.votepower,
             self.lastvotetime
         ]
Esempio n. 2
0
def getrsharesvalue(rshares):
    conv = Converter()
    rew_bal = float(
        Amount(steem.steemd.get_reward_fund()['reward_balance']).amount)
    rec_claim = float(steem.steemd.get_reward_fund()['recent_claims'])
    steemvalue = rshares * rew_bal / rec_claim
    return conv.steem_to_sbd(steemvalue)
Esempio n. 3
0
def main():

    parser = argparse.ArgumentParser(
        description='show user balances',
        epilog='Report bugs to: https://github.com/bitfag/golos-scripts/issues'
    )
    parser.add_argument('account', help='account name')
    parser.add_argument('-c',
                        '--config',
                        default='./common.yml',
                        help='specify custom path for config file')
    args = parser.parse_args()

    # parse config
    with open(args.config, 'r') as ymlfile:
        conf = yaml.load(ymlfile)

    golos = Steem(nodes=conf['nodes_new'], no_broadcast=True)

    a = Account(args.account, steemd_instance=golos)
    b = a.get_balances()
    pprint(b)

    vests = b['total']['GESTS']
    cv = Converter(golos)
    pprint('GP: {}'.format(cv.vests_to_sp(vests)))
Esempio n. 4
0
    def __init__(self, account_name, steem_instance=None):
        if not steem_instance:
            steem_instance = stm.Steem()
        self.steem = steem_instance

        self.name = account_name
        self.converter = Converter(self.steem)

        # caches
        self._blog = None
        self._props = None
Esempio n. 5
0
def getRshares(accountname='soteyapanbot'):
    s = steemlib()
    c = Converter()
    account = s.get_account(accountname)
    vests = samount(account['vesting_shares']).amount
    delegated_vests = samount(account['delegated_vesting_shares']).amount
    received_vests = samount(account['received_vesting_shares']).amount
    current_vests = float(vests) - float(delegated_vests) + float(
        received_vests)
    steem_power = c.vests_to_sp(current_vests)
    rshares = c.sp_to_rshares(steem_power)
    return (rshares)
Esempio n. 6
0
def calculate_producer_rewards(steemd_instance, witness_account):
    account = Account(witness_account, steemd_instance=steemd_instance)

    total_vests = 0

    for producer_reward in account.history_reverse(
            filter_by=["producer_reward"]):
        total_vests += Amount(producer_reward["vesting_shares"]).amount

    converter = Converter(steemd_instance=s)
    total_sp = converter.vests_to_sp(total_vests)

    return total_vests, total_sp
Esempio n. 7
0
def getrsharesvalue(rshares):
    """Converts a vote's rshares value to current SBD value.

    Args:
        rshares: the rshares value of an upvote.
    Returns:
        the current SBD upvote value.
    """
    conv = Converter()
    rew_bal = float(Amount(steem.steemd.get_reward_fund()['reward_balance']).amount)
    rec_claim = float(steem.steemd.get_reward_fund()['recent_claims'])
    steemvalue = rshares * rew_bal / rec_claim
    return conv.steem_to_sbd(steemvalue)
Esempio n. 8
0
def getBreakeven():
    s = steemlib()
    c = Converter()
    steemPrice = float(s.get_current_median_history_price()['base'].replace(
        "SBD", "")) / float(
            s.get_current_median_history_price()['quote'].replace("STEEM", ""))
    for i in range(400000, 500000, 1000):
        rshares = c.sp_to_rshares(i)
        claims = getClaims(rshares)
        steemRewards, steemRewardsOld = rwdComp(claims, rshares, i, steemPrice,
                                                s, c)
        if math.fabs(steemRewards - steemRewardsOld) <= 0.001:
            print(steemRewards, steemRewardsOld, i)
            break
    return (steemRewards, steemRewardsOld, i)
Esempio n. 9
0
 def current_vote_value(self, *kwargs):
     try:
         kwargs.items()
     except:
         pass
     else:
         for key, value in kwargs.items():
             setattr(self, key, value)
     try:
         self.lastvotetime
     except:
         self.lastvotetime = None
     try:
         self.steempower
     except:
         self.steempower = 0
     try:
         self.voteweight
     except:
         self.voteweight = 100
     try:
         self.votepower
     except:
         self.votepower = 0
     try:
         self.account
     except:
         self.account = None
     if self.account is None:
         self.account = self.mainaccount
     if (self.lastvotetime is None or self.steempower == 0
             or self.votepower == 0):
         self.check_balances(self.account)
     c = Converter()
     self.voteweight = self.util.scale_vote(self.voteweight)
     if self.votepower > 0 and self.votepower < 101:
         self.votepower = self.util.scale_vote(self.votepower)
     else:
         self.votepower = (self.votepower +
                           self.util.calc_regenerated(self.lastvotetime))
     self.vpow = round(self.votepower / 100, 2)
     self.rshares = c.sp_to_rshares(self.steempower, self.votepower,
                                    self.voteweight)
     self.votevalue = self.rshares_to_steem(self.rshares)
     return self.votevalue
Esempio n. 10
0
def run_delegate():
    s = Steem(keys=wif)
    vests = '{} VESTS'.format(Converter().sp_to_vests(2))
    for u in s.get_vesting_delegations('cnsteem', '', 1000):
        amount, units = u['vesting_shares'].split()
        if float(amount) > 5000:
            res = s.delegate_vesting_shares(u['delegatee'], vests, user)
            print("Done:", u['delegatee'])
            time.sleep(1)
Esempio n. 11
0
def post_topN_list(sorted_post_frame,
                   poster,
                   current_datetime,
                   overview_permalink,
                   N=10):
    """ Post the toplist to the blockchain

    Parameters
    ----------
    sorted_post_frame: DataFrame
    poster: Poster
    current_datetime: datetime
    N: int
        Size of top list

    Returns
    -------
    permalink to new post

    """
    df = sorted_post_frame.iloc[:N, :]

    logger.info('Creating top {} post'.format(N))
    first_image_urls = df.body.apply(lambda x: tftf.get_image_urls(x))

    steem_per_mvests = Converter(poster.steem).steem_per_mvests()
    truffle_link = 'https://steemit.com/steemit/@{}/{}'.format(
        poster.account, overview_permalink)

    title, body = tfbp.topN_post(topN_authors=df.author,
                                 topN_permalinks=df.permalink,
                                 topN_titles=df.title,
                                 topN_filtered_bodies=df.filtered_body,
                                 topN_image_urls=first_image_urls,
                                 topN_rewards=df.predicted_reward,
                                 topN_votes=df.predicted_votes,
                                 title_date=current_datetime,
                                 truffle_link=truffle_link,
                                 steem_per_mvests=steem_per_mvests)

    permalink = PERMALINK_TEMPLATE.format(
        date=current_datetime.strftime('%Y-%m-%d'))
    logger.info('Posting top post with permalink: {}'.format(permalink))
    poster.post(body=body,
                permalink=permalink,
                title=title,
                tags=tfbp.TAGS,
                self_vote=True)

    return permalink
Esempio n. 12
0
def check_vesting():
    s = Steem(keys=wif)
    date_7_days_ago = str(datetime.now() - timedelta(days=7))
    vests = '{}'.format(Converter().sp_to_vests(2))
    for u in s.get_vesting_delegations('cnsteem', '', 1000):
        acc = Account(u['delegatee'])
        amount, units = acc['vesting_shares'].split()
        if acc['created'] < date_7_days_ago and acc[
                'last_post'] < date_7_days_ago:
            s.delegate_vesting_shares(u['delegatee'], '0 VESTS', user)
            print(u['delegatee'], acc['created'], acc['last_post'])

        if float(amount) > float(vests):
            s.delegate_vesting_shares(u['delegatee'], '0 VESTS', user)
            print(u['delegatee'], float(amount))
Esempio n. 13
0
def post_top_trending_list(sorted_post_frame,
                           poster,
                           current_datetime,
                           trufflepicks_permalink,
                           overview_permalink,
                           sbd_amount,
                           steem_amount,
                           N=10):
    """ Post the no bot trending toplist to the blockchain"""
    df = sorted_post_frame.iloc[:N, :]

    logger.info('Creating top {} post'.format(N))
    first_image_urls = df.body.apply(lambda x: tftf.get_image_urls(x))

    steem_per_mvests = Converter(poster.steem).steem_per_mvests()
    truffle_link = 'https://steemit.com/steemit/@{}/{}'.format(
        poster.account, overview_permalink)
    trufflepicks_link = 'https://steemit.com/steemit/@{}/{}'.format(
        poster.account, trufflepicks_permalink)

    title, body = tfbp.top_trending_post(topN_authors=df.author,
                                         topN_permalinks=df.permalink,
                                         topN_titles=df.title,
                                         topN_filtered_bodies=df.filtered_body,
                                         topN_image_urls=first_image_urls,
                                         topN_rewards=df.reward,
                                         title_date=current_datetime,
                                         truffle_link=truffle_link,
                                         steem_per_mvests=steem_per_mvests,
                                         trufflepicks_link=trufflepicks_link,
                                         sbd_amount=sbd_amount,
                                         steem_amount=steem_amount)

    permalink = TRENDING_PERMALINK_TEMPLATE.format(
        date=current_datetime.strftime('%Y-%m-%d'))
    logger.info(
        'Posting top trending post with permalink: {}'.format(permalink))
    poster.post(body=body,
                permalink=permalink,
                title=title,
                tags=tfbp.TRENDING_TAGS,
                self_vote=False)

    return permalink
Esempio n. 14
0
def post_weakly_update(pipeline, post_frame, poster, current_datetime):
    steem_per_mvests = Converter(poster.steem).steem_per_mvests()
    stats = compute_weekly_statistics(post_frame, pipeline)

    delegator_list = tpaa.get_delegates_and_shares(poster.account,
                                                   poster.steem).keys()

    title, body = tpbp.weekly_update(steem_per_mvests=steem_per_mvests,
                                     current_datetime=current_datetime,
                                     delegator_list=delegator_list,
                                     **stats)
    permalink = PERMALINK_TEMPLATE.format(
        date=current_datetime.strftime('%Y-%V'))

    poster.post(body=body,
                title=title,
                permalink=permalink,
                self_vote=True,
                tags=TAGS)

    return permalink
Esempio n. 15
0
steemd_nodes = [
    'https://anyx.io',
    'https://api.steemit.com',
    #  'https://steemd.minnowsupportproject.org',
]

credfile = open("credentials.txt")
bot = credfile.readline().strip()
postkey = credfile.readline().strip()
key = credfile.readline().strip()

db = DB('curangel.sqlite3')
steem = Steem(keys=[key], nodes=steemd_nodes)
chain = Blockchain(steem)
converter = Converter(steem)
account = Account(bot, steem)


def getRewards():
    rewards = {}
    last_block = db.select('last_check', ['rewards_block'], '1=1',
                           'rewards_block', 1)[0]['rewards_block']
    steem_per_mvests = converter.steem_per_mvests()
    received = account.get_account_history(
        -1, 2500, filter_by=['curation_reward', 'delegate_vesting_shares'])
    i = 0
    for r in received:
        if i < 1:
            i = i + 1
            db.update('last_check', {'rewards_block': r['block']},
Esempio n. 16
0
#########################################
# Connections
#########################################

# steemd
#nodes = [
#    # 'http://192.168.1.50:8090',
#    os.environ['steem_node'] if 'steem_node' in os.environ else 'http://51.15.55.185:8090',
#]

nodes = config['steemd_nodes']

s = Steem(nodes)
d = Steemd(nodes)
b = Blockchain(steemd_instance=s, mode='head')
c = Converter(steemd_instance=s)

fullnodes = [
    'https://rpc.buildteam.io',
    'https://api.steemit.com',
]
fn = Steem(fullnodes)

# MongoDB
ns = os.environ['namespace'] if 'namespace' in os.environ else 'eostalk'
# mongo = MongoClient('mongodb://mongo')
mongo = MongoClient(config['mongo_url'])
db = mongo[ns]

# MongoDB Schema Enforcement
if not 'forum_requests' in db.collection_names():
Esempio n. 17
0
def get_sp(account):
    a = get_account_from_map(account)
    return round(Converter().vests_to_sp(int(
        a['vesting_shares'].split('.')[0])))
Esempio n. 18
0
class Account(object):
    def __init__(self, account_name, steem_instance=None):
        if not steem_instance:
            steem_instance = stm.Steem()
        self.steem = steem_instance

        self.name = account_name
        self.converter = Converter(self.steem)

        # caches
        self._blog = None
        self._props = None

    def get_props(self):
        if self._props is None:
            self._props = self.steem.rpc.get_account(self.name)
        return self._props

    def get_blog(self):
        if self._blog is None:
            self._blog = self.steem.get_blog(self.name)
        return self._blog

    @property
    def profile(self):
        with suppress(Exception):
            meta_str = self.get_props().get("json_metadata", "")
            return json.loads(meta_str).get('profile', dict())

    @property
    def sp(self):
        vests = Amount(self.get_props()['vesting_shares']).amount
        return self.converter.vests_to_sp(vests)

    @property
    def rep(self):
        return self.reputation()

    def get_balances(self):
        my_account_balances = self.steem.get_balances(self.name)
        return {
            "STEEM": my_account_balances["balance"].amount,
            "SBD": my_account_balances["sbd_balance"].amount,
            "VESTS": my_account_balances["vesting_shares"].amount,
        }

    def reputation(self):
        rep = int(self.get_props()['reputation'])
        if rep < 0:
            return -1
        if rep == 0:
            return 25

        score = (math.log10(abs(rep)) - 9) * 9 + 25
        return float("%.2f" % score)

    def voting_power(self):
        return self.get_props()['voting_power'] / 100

    def get_followers(self):
        return [
            x['follower'] for x in self._get_followers(direction="follower")
        ]

    def get_following(self):
        return [
            x['following'] for x in self._get_followers(direction="following")
        ]

    def _get_followers(self, direction="follower", last_user=""):
        if direction == "follower":
            followers = self.steem.rpc.get_followers(self.name,
                                                     last_user,
                                                     "blog",
                                                     100,
                                                     api="follow")
        elif direction == "following":
            followers = self.steem.rpc.get_following(self.name,
                                                     last_user,
                                                     "blog",
                                                     100,
                                                     api="follow")
        if len(followers) == 100:
            followers += self._get_followers(
                direction=direction, last_user=followers[-1][direction])[1:]
        return followers

    def check_if_already_voted(self, post):
        for vote in self.history2(filter_by="vote"):
            if vote['permlink'] == post['permlink']:
                return True

        return False

    def curation_stats(self):
        trailing_24hr_t = time.time() - datetime.timedelta(
            hours=24).total_seconds()
        trailing_7d_t = time.time() - datetime.timedelta(
            days=7).total_seconds()

        reward_24h = 0.0
        reward_7d = 0.0

        for reward in self.history2(filter_by="curation_reward", take=10000):

            timestamp = parse_time(reward['timestamp']).timestamp()
            if timestamp > trailing_7d_t:
                reward_7d += Amount(reward['reward']).amount

            if timestamp > trailing_24hr_t:
                reward_24h += Amount(reward['reward']).amount

        reward_7d = self.converter.vests_to_sp(reward_7d)
        reward_24h = self.converter.vests_to_sp(reward_24h)
        return {
            "24hr": reward_24h,
            "7d": reward_7d,
            "avg": reward_7d / 7,
        }

    def virtual_op_count(self):
        try:
            last_item = self.steem.rpc.get_account_history(self.name, -1,
                                                           0)[0][0]
        except IndexError:
            return 0
        else:
            return last_item

    def history(self, filter_by=None, start=0):
        """
        Take all elements from start to last from history, oldest first.
        """
        batch_size = 1000
        max_index = self.virtual_op_count()
        if not max_index:
            return

        start_index = start + batch_size
        i = start_index
        while True:
            if i == start_index:
                limit = batch_size
            else:
                limit = batch_size - 1
            history = self.steem.rpc.get_account_history(self.name, i, limit)
            for item in history:
                index = item[0]
                if index >= max_index:
                    return

                op_type = item[1]['op'][0]
                op = item[1]['op'][1]
                timestamp = item[1]['timestamp']
                trx_id = item[1]['trx_id']

                def construct_op(account_name):
                    return {
                        **op,
                        "index": index,
                        "account": account_name,
                        "trx_id": trx_id,
                        "timestamp": timestamp,
                        "type": op_type,
                    }

                if filter_by is None:
                    yield construct_op(self.name)
                else:
                    if type(filter_by) is list:
                        if op_type in filter_by:
                            yield construct_op(self.name)

                    if type(filter_by) is str:
                        if op_type == filter_by:
                            yield construct_op(self.name)
            i += batch_size

    def history2(self, filter_by=None, take=1000):
        """
        Take X elements from most recent history, oldest first.
        """
        max_index = self.virtual_op_count()
        start_index = max_index - take
        if start_index < 0:
            start_index = 0

        return self.history(filter_by, start=start_index)

    def get_account_votes(self):
        return self.steem.rpc.get_account_votes(self.name)

    def get_withdraw_routes(self):
        return self.steem.rpc.get_withdraw_routes(self.name, 'all')

    def get_conversion_requests(self):
        return self.steem.rpc.get_conversion_requests(self.name)

    @staticmethod
    def filter_by_date(items, start_time, end_time=None):
        start_time = parse_time(start_time).timestamp()
        if end_time:
            end_time = parse_time(end_time).timestamp()
        else:
            end_time = time.time()

        filtered_items = []
        for item in items:
            if 'time' in item:
                item_time = item['time']
            elif 'timestamp' in item:
                item_time = item['timestamp']
            timestamp = parse_time(item_time).timestamp()
            if end_time > timestamp > start_time:
                filtered_items.append(item)

        return filtered_items

    def export(self):
        """ This method returns a dictionary that is type-safe to store as JSON or in a database.
        """
        followers = self.get_followers()
        following = self.get_following()

        return {
            **self.get_props(),
            "profile": self.profile,
            "sp": self.sp,
            "rep": self.rep,
            "balances": walk_keys(str.upper, self.get_balances()),
            "followers": followers,
            "followers_count": len(followers),
            "following": following,
            "following_count": len(following),
            "curation_stats": self.curation_stats(),
            "withdrawal_routes": self.get_withdraw_routes(),
            "conversion_requests": self.get_conversion_requests(),
            "account_votes": self.get_account_votes(),
        }
Esempio n. 19
0
from flask import Flask, request, render_template
from flask_assistant import Assistant, ask, tell
from steem import Steem
from steem.converter import Converter
from steem.blog import Blog
from steem.account import Account
from steem.amount import Amount
from steemconnect.client import Client
from steemconnect.operations import Follow, Unfollow, Mute, ClaimRewardBalance, Comment, CommentOptions, Vote
import requests, json, os, random, string

St_username = ""
Tag = ''
s = Steem()
c = Converter()
app = Flask(__name__)
assist = Assistant(app, route='/api', project_id=os.environ.get('project_id'))
app.config['INTEGRATIONS'] = ['ACTIONS_ON_GOOGLE']  # To enable Rich Messages
posts = s.get_discussions_by_trending({"limit": "8"
                                       })  # To cache the top 8 trending posts
sc = Client(client_id=os.environ.get('client_id'),
            client_secret=os.environ.get('client_secret'))


class Steemian:
    def __init__(self, St_username):
        self.username = St_username
        self.data = Account(self.username)
        self.reputation = str(self.data.rep)
        self.upvoteworth = self.calculate_voteworth()
        self.steempower = self.calculate_steempower(True)
Esempio n. 20
0
    data['binance']['accounts'] = data['binance']['client'].get_account()
    data['binance']['balances'] = data['binance']['accounts']['balances']
except:
    data['binance'][
        'message'] = '[Binance] API Error: Cannot retrieve balances'
    pass

try:
    data['kucoin']['balances'] = data['kucoin']['client'].get_all_balances()
except:
    data['kucoin']['message'] = '[KuCoin] API Error: Cannot retrieve balances'
    pass

# Steemit
client = Steem()
converter = Converter()
try:
    account = client.get_account(cfg.get('Steemit', 'user_account'))
    balance = converter.vests_to_sp(
        np.float(account['vesting_shares'].split()[0]))
except:
    pass


# Portfolio
def normalize(datum):
    try:
        df = pd.DataFrame(datum['balances']).filter(datum['columns'])
        df.columns = ['currency', 'balance']
        df['currency'] = df['currency'].apply(np.str)
        df['balance'] = df['balance'].apply(np.float)
Esempio n. 21
0
async def on_message(message):
    command_run = 0
    #if message.content.upper().startswith("§REGISTER"): # code for the !register command
    #        userID = message.author.id
    #        if (len(message.content.strip()) > 9):
    #            args = message.content.split(" ")
    #            if "@" in args[1]:
    #                await client.send_message(message.channel, "Fehler -- Bitte Steem ID ohne @ eingeben!")
    #            else:
    #                command_run = 1
    #                if userID not in liste and args[1] not in liste :
    #                    liste[userID] = args[1] # append the userid and the steem handle to the dict
    #                    await client.send_message(message.channel, "Für die Discord ID <@%s> wurde die Steem ID %s registriert !" % (userID,liste[userID]) )
    #                    f = open(fname,"wb") #write the dict into a file
    #                    pickle.dump(liste,f)
    #                    f.close()
    #
    #                else:
    #                    await client.send_message(message.channel, "Die Discord ID <@%s> ist bereits mit der Steem ID %s verknüpft!" % (userID,liste[userID]) )
    #                    print (liste)

    if message.content.upper().startswith(
            "?STATUS"
    ):  # code for the status command, will list users and basic data about the bot
        account_name = "dach-support"
        acc_data = s.get_account(account_name)
        votingpower = float(acc_data["voting_power"])
        votingpower = votingpower / 100
        votetime = acc_data[
            "last_vote_time"]  # start of caluclation of actual voting power, need to go some strange ways
        votetime = votetime.replace("T", " ")
        votetime = datetime.datetime.strptime(votetime, "%Y-%m-%d %H:%M:%S")
        now = datetime.datetime.now()
        time_vp = now - votetime
        percentup = (int(((time_vp.total_seconds()) / 60) - 60) * 0.0139)
        if ((votingpower + percentup) >
                100):  # capping the vote percentage at 100
            resulting_vp = 100
        else:
            resulting_vp = (votingpower + percentup)
        embed = discord.Embed(title="D-A-CH Support Status",
                              description="Alive and kickin!",
                              color=0x00ff00)
        embed.add_field(name="Angemeldete User", value=liste, inline=False)
        embed.add_field(name="Votingpower",
                        value="%.2f Prozent" % resulting_vp,
                        inline=False)
        embed.set_thumbnail(
            url=
            "https://steemitimages.com/DQmSxg3TwiR7ZcTdH9WKH2To48eJsdQ7D1ejpYUmvLtuzUk/steemitdachfullress.png"
        )
        await client.send_message(message.channel, embed=embed)
        command_run = 1

    if message.content.upper().startswith("?HELP") or message.content.upper(
    ).startswith("§HILFE"):  # code for the help function
        await printhelp(message)
        command_run = 1

    if message.content.upper().startswith(
            "?INFO"
    ):  # code for the status command, will list users and basic data about the bot
        args = message.content.split(" ")
        try:
            account_name = str(args[1])
            try:
                today = datetime.datetime.today()
                sbd = s.get_account(account_name)
                pos1 = (str(sbd["json_metadata"]))
                posanf = pos1.find("profile_image")
                if posanf == -1:
                    picurl = "https://coinjournal.net/wp-content/uploads/2016/06/steemit-logo-blockchain-social-media-platform-696x364.png"
                else:
                    posanf = posanf + 16
                    posend = pos1.find("\"", posanf)
                    picurl = (pos1[posanf:posend])

                steemlink = "https://steemit.com/@" + account_name
                cachedlink = ("https://steemitimages.com/u/%s/avatar" %
                              account_name)
                #print (sbd)
                #print (cachedlink)
                #profilepic = "https://img.busy.org/@" + account_name
                votingpower = float(sbd["voting_power"])
                votingpower = votingpower / 100
                SPown = sbd["vesting_shares"].replace(
                    "VESTS", ""
                )  ## start of calculation of most recent Steempower value
                SPout = sbd["delegated_vesting_shares"].replace("VESTS", "")
                SPout = float(SPout)
                SPown = float(SPown)
                SPin = sbd["received_vesting_shares"].replace("VESTS", "")
                SPin = float(SPin)
                conv = Converter()
                steempower = conv.vests_to_sp(SPown)
                steempower_out = conv.vests_to_sp(SPout)
                steempower_in = conv.vests_to_sp(SPin)
                resulting_steempower = steempower - steempower_out + steempower_in
                #locales formating
                steempower = locale.format("%.2f",
                                           float(steempower),
                                           grouping=True)
                steempower_out = locale.format("%.2f",
                                               float(steempower_out),
                                               grouping=True)
                steempower_in = locale.format("%.2f",
                                              float(steempower_in),
                                              grouping=True)
                resulting_steempower = locale.format(
                    "%.2f", float(resulting_steempower), grouping=True)

                votetime = sbd[
                    "last_vote_time"]  # start of caluclation of actual voting power, need to go some strange ways
                votetime = votetime.replace("T", " ")
                votetime = datetime.datetime.strptime(votetime,
                                                      "%Y-%m-%d %H:%M:%S")
                created = sbd["created"]
                created = created.replace("T", " ")
                created = datetime.datetime.strptime(created,
                                                     "%Y-%m-%d %H:%M:%S")
                since = today - created
                rep = sbd[
                    "reputation"]  # startpoint of the rep calculation out of the raw reputation
                rep = float(rep)
                if rep == 0:  # special situation for the new accounts or the ones that never have received a single vote
                    rep = 25
                else:
                    neg = rep < 0
                    rep = abs(rep)
                    rep = math.log10(rep)
                    rep = max(rep - 9, 0)
                    rep = (-1 if neg else 1) * rep
                    rep = rep * 9 + 25
                    rep = round(rep, 2)
                    rep = locale.format("%.2f", rep,
                                        grouping=False)  #locale format

                now = datetime.datetime.now(
                )  # start of the calculation of the current voting power
                time_vp = now - votetime
                percentup = (int(((time_vp.total_seconds()) / 60) - 60) *
                             0.0139)
                if ((votingpower + percentup) >
                        100):  # capping the vote percentage at 100
                    resulting_vp = 100
                else:
                    resulting_vp = (votingpower + percentup)
                resulting_vp = locale.format("%.2f", resulting_vp)

                time_comment = sbd[
                    "last_post"]  # start of caluclation of last activity information
                time_comment = time_comment.replace("T", " ")
                time_comment = datetime.datetime.strptime(
                    time_comment, "%Y-%m-%d %H:%M:%S")
                time_post = sbd["last_root_post"]
                time_post = time_post.replace("T", " ")
                time_post = datetime.datetime.strptime(time_post,
                                                       "%Y-%m-%d %H:%M:%S")
                latestactivity = max((votetime, time_comment, time_post))
                latestactivity = latestactivity.replace(tzinfo=timezone('UTC'))
                latestactivity_cet = latestactivity.astimezone(
                    timezone('Europe/Berlin'))
                #building and localizing the amount of steem and savings
                amount_steem = (sbd["balance"].replace(" STEEM", ""))
                amount_steem = locale.format("%.2f",
                                             float(amount_steem),
                                             grouping=True)
                amount_steem_savings = (sbd["savings_balance"].replace(
                    " STEEM", ""))
                amount_steem_savings = locale.format(
                    "%.2f", float(amount_steem_savings), grouping=True)
                #building and localizing the amount of sbd and savings
                amount_sbd = (sbd["sbd_balance"].replace(" SBD", ""))
                amount_sbd = locale.format("%.2f",
                                           float(amount_sbd),
                                           grouping=True)
                amount_sbd_savings = (sbd["savings_sbd_balance"].replace(
                    " SBD", ""))
                amount_sbd_savings = locale.format("%.2f",
                                                   float(amount_sbd_savings),
                                                   grouping=True)

                # building the embed to broadcast via discor
                embed = discord.Embed(title="Account Information",
                                      description="[%s](%s)" %
                                      (account_name, steemlink),
                                      color=0x00ff00)
                embed.add_field(name="Steem Power",
                                value="%s SP" % resulting_steempower)
                embed.add_field(name="Eigene SP", value="%s SP" % steempower)
                embed.add_field(name="Delegierte SP",
                                value="%s SP" % steempower_out)
                embed.add_field(name="Erhaltene SP",
                                value="%s SP" % steempower_in)
                embed.add_field(name="Votingpower",
                                value="%s Prozent" % resulting_vp)
                embed.add_field(name="Kontostand Steem (Save)",
                                value="%s (%s) STEEM" %
                                (amount_steem, amount_steem_savings))
                embed.add_field(name="Kontostand SBD (Save)",
                                value="%s (%s) SBD" %
                                (amount_sbd, amount_sbd_savings))
                embed.add_field(name="Angemeldet seit",
                                value="%s, %s Tage" %
                                (datetime.datetime.strftime(
                                    created, "%d.%m.%Y"), since.days))
                embed.add_field(name="Reputation", value=rep)
                embed.add_field(name="Letzte Aktion auf Steem",
                                value=datetime.datetime.strftime(
                                    latestactivity_cet, "%d.%m.%Y %H:%M"))

                embed.set_thumbnail(url=picurl)
                embed.timestamp = datetime.datetime.utcnow()
                embed.set_footer(text="frisch von der Blockchain")
                await client.send_message(message.channel, embed=embed
                                          )  # send the built message
                command_run = 1
            except TypeError as err:
                await client.send_message(
                    message.channel,
                    "Fehler - kein SteemAccount mit dem Namen %s gefunden" %
                    account_name)
                print(err)
                command_run = 1
        except IndexError as err:
            await client.send_message(
                message.channel,
                "Fehler - bitte Steemnamen nach §info eingeben")
            print(err)
            command_run = 1


#    if message.content.upper().startswith("§UPVOTE"): # code for the upvote command, writes the article and the author into a file to be used by the vote bot
#        if (len(message.content.strip()) > 7) and message.content[7] == " ":
#            args = message.content.split(" ")
#            pos1 = args[1].find("@")
#            check = 0
#            if pos1 <= 0:
#                await client.send_message(message.channel, "Fehler - Bitte den kompletten Link hinter §upvote einfügen, beginnend mit http...")
#                check = check +1
#            else:
#                pos2 = args[1].find("/",pos1)
#                steem_name = (args[1][pos1+1:pos2])
#                length = len(args[1])
#                article = Post(args[1][pos1:length])
#                elapsed = Post.time_elapsed(article)
#                if elapsed >= datetime.timedelta(days=3):
#                    await client.send_message(message.channel, "Fehler - Leider ist der Post älter als 3 Tage")
#                    check = check +1
#                    command_run = 1
#                if article.is_main_post() is False:
#                    await client.send_message(message.channel, "Fehler - Kommentare können nicht vorgeschlagen werden")
#                    check = check +1
#                    command_run = 1
#                #await client.send_message(message.channel, "Alter des Posts : %s " % elapsed)
#
#                userID = message.author.id
#                if userID in liste:
#                    registered_name = liste[userID]
#                    if steem_name == registered_name:
#                        await client.send_message(message.channel, "Fehler - Das Vorschlagen eigener Posts ist untersagt!")
#                        check = check +1
#                else:
#                    await client.send_message(message.channel, "Fehler - Dein Steemname ist nicht registriert -- bitte zuerst §register benutzen")
#                    check = check +1
#                c.execute("SELECT permlink FROM articles WHERE permlink = (?)", (args[1][pos1:length],))
#                result = c.fetchone()
#                if result is not None: # Check if the article is already in the database
#                    await client.send_message(message.channel, "Fehler - Artikel wurde schon vorgeschlagen")
#                    check = 5
#                    command_run = 1
#
#                if check == 0:
#                    datarow =(registered_name,args[1][pos1:length],1)
#                    # Insert the data into the SQLITE Table
#                    c.execute("INSERT INTO articles VALUES(?,?,?)", datarow)
#                    #member  = discord.utils.get(message.server.members, name=steem_name)
#                    #await client.send_message(member, "Wow - Ein Post von dir wurde von %s beim D-A-CH Support eingereicht!" % registered_name )
#                    db.commit()
#                    command_run = 1
#                    await client.send_message(message.channel, "Erfolg - Du hast einen Post von %s beim D-A-CH Support eingereicht!" % steem_name )
#
#        else:
#            await client.send_message(message.channel, "Fehler - Bitte den kompletten Link hinter §upvote einfügen, beginnend mit http...")

#    if message.content.upper().startswith("§CHECK"):
#        c.execute("SELECT * FROM meetup")
#        print("fetchall:")
#        result = c.fetchall()
#        for r in result:
#            print(r)
#        await client.send_message(message.channel, "Folgend Artikel sind derzeit eingereicht: /n %s " % result )
#

    if message.content.upper().startswith("?ADDMEETUP"):
        executed = 0
        for role in message.author.roles:
            if role.name == "Admin":
                args = message.content.split(" ")
                Ort = str(args[1])
                Planer = str(args[2])
                Permlink = str(args[3])
                Datum = datetime.datetime.strptime(args[4], "%d.%m.%Y")
                #Datum = datetime.date(args[4])
                datarow = (Ort, Planer, Permlink, Datum)
                c.execute("INSERT INTO meetup VALUES(?,?,?,?)", datarow)
                db.commit()
                command_run = 1
                executed = 1
                await client.send_message(
                    message.channel, "Meetup von %s in %s wurde hinzugefügt" %
                    (str(args[2]), str(args[1])))
        if executed == 0:
            await client.send_message(
                message.channel,
                "Du hast nicht die benötigten Berechtigungen den Befehl auszuführen"
            )
            command_run = 1

    if message.content.upper().startswith("?NEXTMEETUP"):
        default = 4
        if (len(message.content.strip()) > 11) and message.content[11] == " ":
            args = message.content.split(" ")
            if args[1].isdigit():
                default = args[1]

        c.execute(
            "SELECT * FROM meetup ORDER BY date(\"datum\") ASC LIMIT (?)",
            (default, ))
        #print("fetchall:")
        result = c.fetchall()
        if len(result) == 0:
            await client.send_message(message.channel,
                                      "Derzeit sind keine Meetups geplant")
            command_run = 1
        else:
            today = datetime.datetime.today()
            for r in result:  # building the informations per meetup to fill the embed and post the message in a nice format
                pos1 = r[2].find("@")
                pos2 = r[2].find("/", pos1)
                steemname = (r[2][pos1 + 1:pos2])
                sbd = s.get_account(steemname)
                picdest = (str(sbd["json_metadata"]))
                posanf = picdest.find("profile_image")
                posanf = posanf + 16
                posend = picdest.find("\"", posanf)
                deltadays = r[3] - today
                daystomeetup = deltadays.days

                if deltadays.days >= -2:
                    if deltadays.days == 0:
                        daystomeetup = ("Morgen")
                    if deltadays.days == -1:
                        daystomeetup = ("Heute")

                    embed = discord.Embed(title="Nächstes Meetup in: %s" %
                                          r[0],
                                          description="",
                                          color=0x00ff00)
                    embed.add_field(
                        name="Planer",
                        value="[%s](%s)" %
                        (str(r[1]), "https://steemit.com/@" + str(r[1])))
                    embed.add_field(name="Link",
                                    value="[Link zum Steemit-Post](%s) " %
                                    str(r[2]),
                                    inline=True)
                    embed.add_field(
                        name="Datum",
                        value="%s" %
                        datetime.datetime.strftime(r[3], "%d.%m.%Y"),
                        inline=True)
                    embed.add_field(name="Tage bis zum Meetup",
                                    value="%s" % daystomeetup,
                                    inline=True)
                    embed.set_thumbnail(url=(picdest[posanf:posend]))
                    embed.timestamp = datetime.datetime.utcnow()
                    embed.set_footer(text="fresh from the DACH-BOT")
                    await client.send_message(message.channel, embed=embed)
                    command_run = 1
                else:
                    #await client.send_message(message.channel, "Derzeit sind keine Meetups geplant" )
                    command_run = 1

    if message.content.upper().startswith(
            "?KILLMEETUP"
    ):  # Function to empty the table, only admins can do that, handle with care
        executed = 0
        for role in message.author.roles:
            if role.name == "Admin":
                c.execute("DELETE FROM meetup")
                db.commit()
                executed = 1
        if executed == 0:
            await client.send_message(
                message.channel,
                "Du hast nicht die benötigten Berechtigungen den Befehl auszuführen"
            )

    else:
        if message.content.upper().startswith(
                "?") and command_run == 0 and len(message.content.strip()) > 2:
            await printhelp(message)
        command_run = 0
Esempio n. 22
0
from steem import Steem
from steem.account import Account
from steem.converter import Converter
import re

username = '******'  # 계정명 입력
s = Steem(nodes=["https://api.steemit.com"])
converter = Converter(steemd_instance=s)

a = Account(username)
histories = list(
    a.get_account_history(index=-1,
                          limit=5300,
                          filter_by='claim_reward_balance',
                          raw_output=True))

sum_steem = 0
sum_sbd = 0
sum_sp = 0

for history in histories:
    steem = history[1]['op'][1]['reward_steem']
    steem = float(re.findall("([0-9]+(?:\.[0-9]+)?)(?:\s)", steem)[0])

    sbd = history[1]['op'][1]['reward_sbd']
    sbd = float(re.findall("([0-9]+(?:\.[0-9]+)?)(?:\s)", sbd)[0])

    sp = history[1]['op'][1]['reward_vests']
    sp = float(re.findall("([0-9]+(?:\.[0-9]+)?)(?:\s)", sp)[0])
    sp = converter.vests_to_sp(sp)
Esempio n. 23
0
def main():

    parser = argparse.ArgumentParser(
        description='show multiple users balances',
        epilog='Report bugs to: https://github.com/bitfag/golos-scripts/issues'
    )
    parser.add_argument('-c',
                        '--config',
                        default='./common.yml',
                        help='specify custom path for config file')
    parser.add_argument('--no-header',
                        action='store_true',
                        help='supress header')
    parser.add_argument('--no-sum',
                        action='store_true',
                        help='supress summary output')
    parser.add_argument('-d',
                        '--debug',
                        action='store_true',
                        help='enable debug output'),

    args = parser.parse_args()

    # create logger
    if args.debug == True:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)
    handler = logging.StreamHandler()
    formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s")
    handler.setFormatter(formatter)
    log.addHandler(handler)

    # parse config
    with open(args.config, 'r') as ymlfile:
        conf = yaml.load(ymlfile)

    golos = Steem(nodes=conf['nodes_new'], no_broadcast=True)

    if not args.no_header:
        print('{:<20} {:>10} {:>11} {:>11}'.format('Account', 'GBG', 'GOLOS',
                                                   'GP'))
        print('--------------------')

    sum_gbg = float()
    sum_golos = float()
    sum_gp = float()
    for acc in conf['accs']:
        a = Account(acc, steemd_instance=golos)
        b = a.get_balances()
        vests = b['total']['GESTS']
        cv = Converter(golos)
        gp = cv.vests_to_sp(vests)
        print('{:<20} {:>10}  {:>10}  {:>10.0f}'.format(
            acc, b['total']['GBG'], b['total']['GOLOS'], gp))
        sum_gbg += b['total']['GBG']
        sum_golos += b['total']['GOLOS']
        sum_gp += gp

    if not args.no_sum:
        print('--------------------')
        print('{:<20} {:>10.3f}  {:>10.3f}  {:>10.0f}'.format(
            'Totals:', sum_gbg, sum_golos, sum_gp))
Esempio n. 24
0
class SteemHelper:
        
    s = Steem(nodes=[CONST.STEEMIT_API, 'http://steemd.pevo.science'])
    set_shared_steemd_instance(s)
    c = Converter()    

    def get_history(self, username):
        a = Account(username)
        history = a.history_reverse()
        count = 1

        for item in history:
            if count > 3:
                break
            print(item)
            count = count + 1



    def get_payout(self, username):
        b = Blog(username)
        posts = b.take(1)
        total_pending = 0
        total_payout = 0
        total_cur_payout = 0
        total_promoted = 0

        for post in posts:
            # Total pending value
            pending_val = post['pending_payout_value'].amount
            total_pending += pending_val            
            # Total payout value
            payout_val = post['total_payout_value'].amount
            total_payout += payout_val
            # Total curator payout value
            cur_payout = post['curator_payout_value'].amount
            total_cur_payout += cur_payout
            # Total max accepted payout value
            promoted = post['promoted'].amount
            total_promoted += promoted
        
        total_pending = round(total_pending, 2)
        total_payout = round(total_payout, 2)
        total_cur_payout = round(total_cur_payout, 2)
        total_promoted = round(total_promoted, 2)

        result = {
            'total_pending':"{} SBD".format(total_pending),
            'total_payout':"{} SBD".format(total_payout),
            'total_cur_payout':"{} SBD".format(total_cur_payout),
            'total_promoted':"{} SBD".format(total_promoted)
        }

        return result
        

    def get_account(self, username):
        try:
            a = self.s.get_account(username)
            a['json_metadata'] = json.loads(a['json_metadata'])
        except:
            return None
        return a

    def get_follow_count(self, username):
        return self.s.get_follow_count(username)

    def get_followers(self, username):
        return self.s.get_followers(username, 'blog', 'abit', 0)

    def get_reputation(self, reputation):
        reputation = float(reputation)
        return "({})".format(str(math.floor((math.log10(reputation)-9) * 9 + 25)))
    
    def get_steem_power(self, vests):
        vests = float(vests.replace('VESTS',''))
        return "{} SP".format(round(self.c.vests_to_sp(vests),2))

    def get_voting_power(self, vp):
        return "{}%".format(round(vp/100,2))