Exemplo n.º 1
0
def main():
    r = RabonaClient()
    for account in ACCOUNTS:
        # check if we can train, first.
        userinfo = r.userinfo(user=account["username"])
        if not userinfo.get("training_possible"):
            # training is not possible, wait.
            dt_delta = datetime.fromtimestamp(
                userinfo.get("training_busy_until")) - datetime.now()
            hours_left = int(dt_delta.total_seconds() / 3600)
            print("[%s] %d hours left for the training. Waiting." %
                  (account["username"], hours_left))
        else:
            players = r.team(user=account["username"]).get("players", [])
            print(f" > Found {len(players)} players.")

            # remove the players that can't play
            players = [
                p["uid"] for p in players
                if not (p["games_injured"] > 0 or p["games_blocked"] > 0
                        or p["frozen"] > 0)
            ]

            op = create_custom_json_op(account["username"],
                                       account["auto_train_type"], players)
            c = Client(keys=[account["posting_key"]])
            c.broadcast(op=op)
            print("[%s] [Training: %s] Done." %
                  (account["username"], account["auto_train_type"]))
Exemplo n.º 2
0
def inj_block_check(df, linedf, sl, btype="blocked"):
    if len(df) > 0:
        # List of suspended players
        for i in range(len(df)):
            print("Player %s is %s with uid=%s and position=%s" %
                  (df['name'][i], btype, df['uid'][i], types[df['type'][i]]))
            # List of alternatives
            alts = linedf[linedf['type'] == df['type'][i]].reset_index(
                drop=True)
            if (len(alts) > 0):
                alts = alts[alts['starting11'] >= 12].reset_index(
                    drop=True).sort_values(by=['overall_strength']).loc[0]
                print(
                    "The best alternative is %s with overall strength %s and uid %s"
                    % (alts['name'], alts['overall_strength'], alts['uid']))
                # Swap players
                sl["p" + str(df['starting11'][i])] = alts['uid']
                sl["p" + str(alts['starting11'])] = df['uid'][i]

                keys = natsort.natsorted(sl.keys())
                sl = dict(OrderedDict((k, sl[k]) for k in keys))
                for k, v in sl.items():
                    if v is None:
                        sl[k] = ""
                op = create_custom_json_op(account['username'],
                                           "save_formation", "451", sl)
                c = Client(keys=[account["posting_key"]])
                c.broadcast(op=op)
                print("[%s] OUT - [%s] IN" % (df['name'][i], alts['name']))
            else:
                "There are no subs that can be used in the squad."
    else:
        print("There are no %s player(s)." % (btype))
    linedf, sl = getStartingEleven(user=account['username'])
    return (linedf, sl)
Exemplo n.º 3
0
def scout(total, username, pkey):
    lighthive_client = Client(keys=[
        pkey,
    ])
    print('> Will scout %s players for %s.' % (total, username))
    for i in range(total):
        op = create_custom_json_op(username)
        trx_id = lighthive_client.broadcast_sync(op).get("id")
        time.sleep(3)
        signable_player = get_signable_player(trx_id)
        if signable_player.get("overall_strength") > 60:
            print("> Scouted: %s. Type: %s, OS: %s, TP: %s" % (
                signable_player.get("name"),
                PLAYER_TYPE_MAP.get(signable_player.get("type")),
                signable_player.get("overall_strength"),
                signable_player.get("teamplayer"),
            ))
Exemplo n.º 4
0
def main():
    import logging
    r = RabonaClient(loglevel=logging.ERROR)
    for account in ACCOUNTS:
        print(f" > Analyzing next match for @{account['username']}.")
        next_match = get_next_match(r, account["username"])
        print(f" > Next match is {next_match['club_1']} "
              f"vs {next_match['club_2']}.")

        opponent_user = next_match["team_user_2"]
        if next_match["team_user_2"] == account["username"]:
            opponent_user = next_match["team_user_1"]

        formation_of_opponent = get_formation(
            r, opponent_user, next_match["match_id"]) or "433 default"
        print(f" > Opponent is @{opponent_user}.")
        if formation_of_opponent:
            print(f" > Opponent will play {formation_of_opponent}.")
        formation_of_us = get_formation(r, account["username"],
                                        next_match["match_id"])
        if formation_of_us and str(formation_of_us) == account["formation"]:
            print(f" > Formation is already set for this match: "
                  f"{formation_of_us}.")
        else:
            # we need to set formation for that
            players = get_available_players(r, account["username"],
                                            account["formation"])
            formation = prepare_formation(account["formation"], players)

            op = create_custom_json_op(
                account["username"],
                next_match["match_id"],
                account["formation"],
                formation,
            )

            c = Client(keys=[account["posting_key"]],
                       nodes=["https://hived.emre.sh"])
            c.broadcast(op=op)
            print(f" >>> Formation: {account['formation']} is set"
                  f" for {account['username']}.")
        print(f" > All operations are completed for {account['username']}.")
        print("=" * 64)
Exemplo n.º 5
0
def auto_heal_and_unblock(team, pk):
    rbn_balance = r.userinfo(user=team).get("currency")
    logger.info("Checking \"%s\" for injured and blocked players.", team)
    players = r.team(user=team).get("players", [])
    # players[0]["games_blocked"] = 1

    injured_players = [p for p in players if int(p["games_injured"]) > 0]
    blocked_players = [p for p in players if int(p["games_blocked"]) > 0]

    if not injured_players and not blocked_players:
        logger.info(
            "\t\"%s\" doesnt have any injured or blocked players. Skipping.",
            team,
        )
        return
    else:
        logger.info("\tAvailable RBN: %s", round(rbn_balance))
        max_heal_games = round(rbn_balance) / 10000
        for p in injured_players:
            logger.info(
                "\t%s (%s) is injured for %s matches. Trying to heal." %
                (p["name"], p["uid"], p["games_injured"]))
            if p["games_injured"] <= max_heal_games:
                op = create_custom_json_op(team, p["uid"])
                c = Client(keys=[
                    pk,
                ])
                c.broadcast(op=op)
                logger.info("\t Transaction is broadcasted. Enjoy.")
                max_heal_games -= p["games_injured"] * 10000
            else:
                logger.info("\tNot enough RBN to heal %s (%s) for %s matches.",
                            p["name"], p["uid"], p["games_injured"])

        max_unblock_games = round(rbn_balance) / 10000
        for p in blocked_players:
            logger.info(
                "\t%s (%s) is blocked for %s matches. Trying to unblock." %
                (p["name"], p["uid"], p["games_blocked"]))

            if p["games_blocked"] <= max_unblock_games:
                op = create_custom_json_op(team, p["uid"], heal=False)
                c = Client(keys=[
                    pk,
                ])
                c.broadcast(op=op)
                logger.info("\t Transaction is broadcasted. Enjoy.")
                max_heal_games -= p["games_injured"] * 10000
            else:
                logger.info(
                    "\tNot enough RBN to unblock %s (%s) for %s matches.",
                    p["name"], p["uid"], p["games_blocked"])
Exemplo n.º 6
0
 def setUp(self):
     self.client = Client(nodes=TestClient.NODES)
Exemplo n.º 7
0
class TestAccountHelper(unittest.TestCase):
    def setUp(self):
        self.client = Client(nodes=TestClient.NODES)

    def test_vp_with_hf20(self):
        last_vote_time = datetime.datetime.utcnow() - datetime.timedelta(
            hours=24)

        utc = pytz.timezone('UTC')
        last_vote_time = utc.localize(last_vote_time)

        result = {
            'voting_manabar': {
                'current_mana': 7900,
                'last_update_time': int(last_vote_time.timestamp())
            }
        }

        with requests_mock.mock() as m:
            m.post(TestClient.NODES[0], json={"result": [result]})
            account = self.client.account('emrebeyler')

        self.assertEqual(99, account.vp())

    def test_vp(self):
        last_vote_time = datetime.datetime.utcnow() - datetime.timedelta(
            hours=24)

        result = {
            "last_vote_time": last_vote_time.strftime("%Y-%m-%dT%H:%M:%S"),
            "voting_power": 7900,
        }
        with requests_mock.mock() as m:
            m.post(TestClient.NODES[0], json={"result": [result]})
            account = self.client.account('emrebeyler')

        self.assertEqual(99.0, account.vp())

    def test_rc(self):
        def match_get_accounts(request):
            method = json.loads(request.text)["method"]
            return method == "condenser_api.get_accounts"

        def match_find_rc_accounts(request):
            method = json.loads(request.text)["method"]
            return method == "rc_api.find_rc_accounts"

        last_update_time = datetime.datetime.utcnow() - datetime.timedelta(
            hours=24)
        last_update_timestamp = last_update_time.replace(
            tzinfo=datetime.timezone.utc).timestamp()

        result = {
            "rc_accounts": [{
                'account': 'emrebeyler',
                'rc_manabar': {
                    'current_mana': '750',
                    'last_update_time': last_update_timestamp
                },
                'max_rc_creation_adjustment': {
                    'amount': '1029141630',
                    'precision': 6,
                    'nai': '@@000000037'
                },
                'max_rc': '1000'
            }]
        }

        with requests_mock.mock() as m:
            m.post(TestClient.NODES[0],
                   json={"result": [{
                       "foo": "bar"
                   }]},
                   additional_matcher=match_get_accounts)
            m.post(TestClient.NODES[0],
                   json={"result": result},
                   additional_matcher=match_find_rc_accounts)

            self.assertEqual(float(95), self.client.account('emrebeyler').rc())

            self.assertEqual(
                float(75),
                self.client.account('emrebeyler').rc(
                    consider_regeneration=False))

    def test_reputation(self):
        reputation_sample = '74765490672156'  # 68.86
        with requests_mock.mock() as m:
            m.post(TestClient.NODES[0],
                   json={"result": [{
                       "reputation": reputation_sample
                   }]})
            account = self.client.account('emrebeyler')

        self.assertEqual(68.86, account.reputation())

    def test_account_history_simple(self):
        def match_max_index_request(request):
            params = json.loads(request.text)["params"]
            return params[1] == -1

        def match_non_max_index_request(request):
            params = json.loads(request.text)["params"]
            return params[1] != -1

        with requests_mock.mock() as m:
            m.post(TestClient.NODES[0],
                   json={"result": mock_history_max_index},
                   additional_matcher=match_max_index_request)
            m.post(TestClient.NODES[0],
                   json={"result": mock_history},
                   additional_matcher=match_non_max_index_request)

            account = Account(self.client)
            history = list(account.history(account="hellosteem"))
            self.assertEqual(3, len(history))

            # check filter
            history = list(
                account.history(account="hellosteem", filter=["transfer"]))

            self.assertEqual(2, len(history))

            # check exclude
            history = list(
                account.history(account="hellosteem", exclude=["transfer"]))

            self.assertEqual(1, len(history))

            # check only_operation_data

            history = list(
                account.history(account="hellosteem",
                                only_operation_data=False))

            self.assertEqual(3, history[0][0])
Exemplo n.º 8
0
class TestClient(unittest.TestCase):
    NODES = ["https://api.hivekings.com"]

    def setUp(self):
        self.client = Client(nodes=TestClient.NODES)

    def test_dynamic_api_selection(self):
        self.client('tags_api')
        self.assertEqual('tags_api', self.client.api_type)

    def test_default_api_selection(self):
        with requests_mock.mock() as m:
            m.post(TestClient.NODES[0], json={"result": {}})
            self.client.get_block(12323)
            self.assertEqual('condenser_api', self.client.api_type)

    def test_get_rpc_request_body_condenser_multiple_args(self):
        self.client('condenser_api')
        rpc_body = self.client.get_rpc_request_body(
            ('get_account_bandwidth', 'steemit', 'forum'), {
                'batch': True,
                'id': 1
            })

        self.assertEqual(
            "condenser_api.get_account_bandwidth",
            rpc_body["method"],
        )

        self.assertEqual(
            ('steemit', 'forum'),
            rpc_body["params"],
        )

    def test_get_rpc_request_body_condenser_single_arg(self):
        self.client('condenser_api')
        rpc_body = self.client.get_rpc_request_body(
            ('get_block', '123'),
            {},
        )

        self.assertEqual(
            ('123', ),
            rpc_body["params"],
        )

    def test_get_rpc_request_body_non_condenser_api_with_arg(self):
        self.client('database_api')
        rpc_body = self.client.get_rpc_request_body(
            ('list_vesting_delegations', {
                "start": [None],
                "limit": 20,
                "order": "by_delegation"
            }),
            {},
        )

        self.assertEqual(
            {
                'start': [None],
                'limit': 20,
                'order': 'by_delegation'
            }, rpc_body["params"])

    def test_get_rpc_request_body_non_condenser_api_no_arg(self):
        self.client('database_api')
        rpc_body = self.client.get_rpc_request_body(
            ('get_active_witnesses', ),
            {},
        )

        self.assertEqual({}, rpc_body["params"])

    def test_get_rpc_request_body_condenser_api_no_arg(self):
        rpc_body = self.client.get_rpc_request_body(
            ('get_active_witnesses', ),
            {},
        )

        self.assertEqual([], rpc_body["params"])

    def test_batch_rpc_calls(self):
        self.client.get_block(1, batch=True)
        self.client.get_block_header(2, batch=True)

        self.assertEqual(2, len(self.client.queue))
        self.assertEqual("condenser_api.get_block",
                         self.client.queue[0]["method"])
        self.assertEqual("condenser_api.get_block_header",
                         self.client.queue[1]["method"])

    def test_validate_response_rpc_error(self):
        resp = {
            'jsonrpc': '2.0',
            'error': {
                'code': -32000,
                'message': "Parse Error:Couldn't parse uint64_t",
                'data': ""
            },
            'id': 'f0acccf6-ebf6-4952-97da-89b248dfb0d0'
        }

        with self.assertRaises(lighthive.exceptions.RPCNodeException):
            self.client.validate_response(resp)

    def test_validate_repsonse_batch_call(self):
        resp = [{
            'previous': '017d08b4416e4ea77d5f582ddf4fc06bcf888eef',
            'timestamp': '2018-08-11T10:25:00',
            'witness': 'thecryptodrive',
            'transaction_merkle_root': '23676c4bdc0074489392892bcf'
            '1a5b779f280c8e',
            'extensions': []
        }, {
            'previous': '017d08b55aa2520bc3a777eaec77e872bb6b8943',
            'timestamp': '2018-08-11T10:25:03',
            'witness': 'drakos',
            'transaction_merkle_root': 'a4be1913157a1be7e4ab'
            'c36a22ffde1c110e683c',
            'extensions': []
        }]
        validated_resp = self.client.validate_response(resp)

        self.assertEqual(True, isinstance(validated_resp, list))
        self.assertEqual(2, len(validated_resp))

    def test_validate_repsonse_batch_call_one_error_one_fail(self):
        resp = [{
            'previous': '017d08b4416e4ea77d5f582ddf4fc06bcf888eef',
            'timestamp': '2018-08-11T10:25:00',
            'witness': 'thecryptodrive',
            'transaction_merkle_root': '23676c4bdc0074489392892bcf'
            '1a5b779f280c8e',
            'extensions': []
        }, {
            'jsonrpc': '2.0',
            'error': {
                'code': -32000,
                'message': "Parse Error:Couldn't parse uint64_t",
                'data': ""
            },
            'id': 'f0acccf6-ebf6-4952-97da-89b248dfb0d0'
        }]

        with self.assertRaises(lighthive.exceptions.RPCNodeException):
            self.client.validate_response(resp)

    def test_process_batch(self):
        with requests_mock.mock() as m:
            m.post(TestClient.NODES[0], json={"result": {}})
            self.client.get_block(12323, batch=True)
            self.client.get_block(1234, batch=True)

            self.assertEqual(2, len(self.client.queue))
            self.client.process_batch()
            self.assertEqual(0, len(self.client.queue))
Exemplo n.º 9
0
 def get_client_instance(self, keys=None):
     return Client(keys=keys)
Exemplo n.º 10
0
for i in range(len(subs)):
    sl["p" + str(i + 12)] = subs[i]

# Add empty subs
nplayers = []
for k, v in sl.items():
    nplayers.append(int(k[1:]))
for i in range(max(nplayers) + 1, 22):
    sl["p" + str(i)] = ""

# Update Squad
keys = natsort.natsorted(sl.keys())
sl = dict(OrderedDict((k, sl[k]) for k in keys))
op = create_custom_json_op(account['username'], "save_formation",
                           str(formation), sl)
c = Client(keys=[account["posting_key"]])
c.broadcast(op=op)

########################################
# Setup the Squad for Upcoming Matches #
########################################

matches = r.matches(user=account['username'], limit=30, order="DESC")
games = pd.DataFrame.from_dict(matches['matches'])
played = list(
    games[games.goals_team_1 >= 0]['match_id'].reset_index(drop=True))

for match in games['match_id']:
    if match not in played:
        op = create_custom_json_op(account['username'], "set_formation",
                                   str(formation), sl, str(match))