当前位置: 首页>>代码示例>>Python>>正文


Python api_wrapper.ApiWrapper类代码示例

本文整理汇总了Python中api_wrapper.ApiWrapper的典型用法代码示例。如果您正苦于以下问题:Python ApiWrapper类的具体用法?Python ApiWrapper怎么用?Python ApiWrapper使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ApiWrapper类的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self):
        self.api = ApiWrapper()
        self.processed_games = set()
        self.conn = sqlite3.connect(FILES.SQLLITE_FILE)
        self._setup_db()

        self._set_persistance()
开发者ID:Charleezy,项目名称:WinrateForFamiliarChamps,代码行数:7,代码来源:urf_by_summoner.py

示例2: _setup_api

    def _setup_api(self):
        # instantiate pgoapi
        self.api = ApiWrapper(config=self.config)

        # provide player position on the earth
        self._set_starting_position()

        self.login()
        # chain subrequests (methods) into one RPC call

        self.api.activate_signature(self.get_encryption_lib())
        self.logger.info('')
        # send empty map_cells and then our position
        self.update_web_location()
开发者ID:dhluong90,项目名称:PokemonGo-Bot,代码行数:14,代码来源:__init__.py

示例3: _setup_api

    def _setup_api(self):
        # instantiate pgoapi
        self.api = ApiWrapper()

        # provide player position on the earth
        self._set_starting_position()

        self.login()
        # chain subrequests (methods) into one RPC call

        self._print_character_info()

        self.logger.info('')
        self.update_inventory()
        # send empty map_cells and then our position
        self.update_web_location()
开发者ID:Keahibono,项目名称:PokemonGo-Bot,代码行数:16,代码来源:__init__.py

示例4: check_session

    def check_session(self, position):
        # Check session expiry
        if self.api._auth_provider and self.api._auth_provider._ticket_expire:

            # prevent crash if return not numeric value
            if not self.is_numeric(self.api._auth_provider._ticket_expire):
                self.logger.info("Ticket expired value is not numeric", 'yellow')
                return

            remaining_time = \
                self.api._auth_provider._ticket_expire / 1000 - time.time()

            if remaining_time < 60:
                self.logger.info("Session stale, re-logging in", 'yellow')
                position = self.position
                self.api = ApiWrapper()
                self.position = position
                self.login()
开发者ID:stylersnico,项目名称:PokemonGo-Bot,代码行数:18,代码来源:__init__.py

示例5: check_session

    def check_session(self, position):
        # Check session expiry
        if self.api._auth_provider and self.api._auth_provider._ticket_expire:

            # prevent crash if return not numeric value
            if not str(self.api._auth_provider._ticket_expire).isdigit():
                self.logger.info("Ticket expired value is not numeric", 'yellow')
            remaining_time = \
                self.api._auth_provider._ticket_expire / 1000 - time.time()

            if remaining_time < 60:
                self.event_manager.emit(
                    'api_error',
                    sender=self,
                    level='info',
                    formatted='Session stale, re-logging in.'
                )
                self.api = ApiWrapper(config=self.config)
                self.api.set_position(*position)
                self.login()
                self.api.activate_signature(self.get_encryption_lib())
开发者ID:JaapMoolenaar,项目名称:PokemonGo-Bot,代码行数:21,代码来源:__init__.py

示例6: PokemonGoBot


#.........这里部分代码省略.........
            log_level = logging.ERROR
            logging.getLogger("requests").setLevel(logging.ERROR)
            logging.getLogger("websocket").setLevel(logging.ERROR)
            logging.getLogger("socketio").setLevel(logging.ERROR)
            logging.getLogger("engineio").setLevel(logging.ERROR)
            logging.getLogger("socketIO-client").setLevel(logging.ERROR)
            logging.getLogger("pgoapi").setLevel(logging.ERROR)
            logging.getLogger("rpc_api").setLevel(logging.ERROR)

        logging.basicConfig(
            level=log_level,
            format='%(asctime)s [%(name)10s] [%(levelname)s] %(message)s'
        )
    def check_session(self, position):
        # Check session expiry
        if self.api._auth_provider and self.api._auth_provider._ticket_expire:

            # prevent crash if return not numeric value
            if not self.is_numeric(self.api._auth_provider._ticket_expire):
                self.logger.info("Ticket expired value is not numeric", 'yellow')
                return

            remaining_time = \
                self.api._auth_provider._ticket_expire / 1000 - time.time()

            if remaining_time < 60:
                self.event_manager.emit(
                    'api_error',
                    sender=self,
                    level='info',
                    formatted='Session stale, re-logging in.'
                )
                position = self.position
                self.api = ApiWrapper()
                self.position = position
                self.login()
                self.api.activate_signature(self.get_encryption_lib())

    @staticmethod
    def is_numeric(s):
        try:
            float(s)
            return True
        except ValueError:
            return False

    def login(self):
        self.event_manager.emit(
            'login_started',
            sender=self,
            level='info',
            formatted="Login procedure started."
        )
        lat, lng = self.position[0:2]
        self.api.set_position(lat, lng, 0)

        while not self.api.login(
            self.config.auth_service,
            str(self.config.username),
            str(self.config.password)):

            self.event_manager.emit(
                'login_failed',
                sender=self,
                level='info',
                formatted="Login error, server busy. Waiting 10 seconds to try again."
开发者ID:lyriccoder,项目名称:PokemonGo-Bot,代码行数:67,代码来源:__init__.py

示例7: PokemonGoBot


#.........这里部分代码省略.........
            remaining_time = \
                self.api._auth_provider._ticket_expire / 1000 - time.time()

            if remaining_time < 60:
                logger.log("Session stale, re-logging in", 'yellow')
                self.login()

    @staticmethod
    def is_numeric(s):
        try:
            float(s)
            return True
        except ValueError:
            return False

    def login(self):
        logger.log('Attempting login to Pokemon Go.', 'white')
        self.api.reset_auth()
        lat, lng = self.position[0:2]
        self.api.set_position(lat, lng, 0)

        while not self.api.login(self.config.auth_service,
                                str(self.config.username),
                                str(self.config.password)):

            logger.log('[X] Login Error, server busy', 'red')
            logger.log('[X] Waiting 10 seconds to try again', 'red')
            time.sleep(10)

        logger.log('Login to Pokemon Go successful.', 'green')

    def _setup_api(self):
        # instantiate pgoapi
        self.api = ApiWrapper(PGoApi())

        # provide player position on the earth
        self._set_starting_position()

        self.login()

        # chain subrequests (methods) into one RPC call

        self._print_character_info()

        logger.log('')
        self.update_inventory()
        # send empty map_cells and then our position
        self.update_web_location()

    def _print_character_info(self):
        # get player profile call
        # ----------------------
        self.api.get_player()
        response_dict = self.api.call()
        # print('Response dictionary: \n\r{}'.format(json.dumps(response_dict, indent=2)))
        currency_1 = "0"
        currency_2 = "0"

        if response_dict:
            self._player = response_dict['responses']['GET_PLAYER']['player_data']
            player = self._player
        else:
            logger.log(
                "The API didn't return player info, servers are unstable - "
                "retrying.", 'red'
            )
开发者ID:digideskio,项目名称:PokemonGoBot-Manager,代码行数:67,代码来源:__init__.py

示例8: PokemonGoBot


#.........这里部分代码省略.........
            log_level = logging.ERROR
            logging.getLogger("requests").setLevel(logging.ERROR)
            logging.getLogger("websocket").setLevel(logging.ERROR)
            logging.getLogger("socketio").setLevel(logging.ERROR)
            logging.getLogger("engineio").setLevel(logging.ERROR)
            logging.getLogger("socketIO-client").setLevel(logging.ERROR)
            logging.getLogger("pgoapi").setLevel(logging.ERROR)
            logging.getLogger("rpc_api").setLevel(logging.ERROR)

        logging.basicConfig(
            level=log_level,
            format='%(asctime)s [%(name)10s] [%(levelname)s] %(message)s'
        )
    def check_session(self, position):

        # Check session expiry
        if self.api._auth_provider and self.api._auth_provider._ticket_expire:

            # prevent crash if return not numeric value
            if not self.is_numeric(self.api._auth_provider._ticket_expire):
                self.logger.info("Ticket expired value is not numeric", 'yellow')
                return

            remaining_time = \
                self.api._auth_provider._ticket_expire / 1000 - time.time()

            if remaining_time < 60:
                self.event_manager.emit(
                    'api_error',
                    sender=self,
                    level='info',
                    formatted='Session stale, re-logging in.'
                )
                self.api = ApiWrapper(config=self.config)
                self.api.set_position(*position)
                self.login()
                self.api.activate_signature(self.get_encryption_lib())

    @staticmethod
    def is_numeric(s):
        try:
            float(s)
            return True
        except ValueError:
            return False

    def login(self):
        self.event_manager.emit(
            'login_started',
            sender=self,
            level='info',
            formatted="Login procedure started."
        )
        lat, lng = self.position[0:2]
        self.api.set_position(lat, lng, self.alt) # or should the alt kept to zero?

        while not self.api.login(
            self.config.auth_service,
            str(self.config.username),
            str(self.config.password)):

            self.event_manager.emit(
                'login_failed',
                sender=self,
                level='info',
                formatted="Login error, server busy. Waiting 10 seconds to try again."
开发者ID:dhluong90,项目名称:PokemonGo-Bot,代码行数:67,代码来源:__init__.py

示例9: UrfSummonerCrawler

class UrfSummonerCrawler(object):

    def __init__(self):
        self.api = ApiWrapper()
        self.processed_games = set()
        self.conn = sqlite3.connect(FILES.SQLLITE_FILE)
        self._setup_db()

        self._set_persistance()

    def _setup_db(self):
        self.conn.cursor().execute('''CREATE TABLE IF NOT EXISTS test_data(
                                        summ_id integer,
                                        champ_id integer,
                                        result integer)
                                   ''')

    def _set_persistance(self):
        """ Sets summoner_list, processed_games_list and processed_summoners_list
        """
        for dat, fname, default in DATS_FILES_AND_DEFAULTS:
            if os.path.exists(fname):
                with open(fname, 'rb') as f:
                    setattr(self, dat, pickle.load(f))
            else:
                setattr(self, dat, default)

    def _save_persistance(self):
        for dat, fname, _ in DATS_FILES_AND_DEFAULTS:
            with open(fname, 'wb') as f:
                pickle.dump(getattr(self, dat), f)

    def _insert_row(self, summoner, summ_champion, win):
        self.cur.execute(''' INSERT INTO test_data
                        (summ_id, champ_id, result)
                        VALUES (?, ?, ?)
                    ''', (summoner, summ_champion, win))

    def _extract_summ(self, game):
        summ_team = game['teamId']
        win = game['stats']['win']
        summ_champion = game['championId']
        return (summ_team, win, summ_champion)

    def _extract_fellow(self, fellow):
        fsumm = fellow['summonerId']
        fchamp = fellow['championId']
        fteam = fellow['teamId']
        return (fsumm, fchamp, fteam)

    def crawl(self):
        self.cur = self.conn.cursor()
        print('''
                 Beginning crawl...
                 From previous session (if one existed):
                 Processed games: {}
                 Prcesssed Summoners: {}
                 Summoners left to process: {} (This will grow as execution continues)

              '''.format(len(self.processed_games),
                         len(self.processed_summs),
                         len(self.summoners)))

        while self.summoners and len(self.processed_games) <= MAX_GAMES_TO_PROCESS:
            summoner = self.summoners.popleft()
            if summoner in self.processed_summs:
                # skip if we've looked at summ's recent games already
                continue

            url = self.api.game_by_summoner(summoner)

            recent_games = self.api.api_call(url)['games']
            for game in recent_games:
                game_id = game['gameId']
                # only parse URF games we haven't seen before
                if game['subType'] == 'URF' and game_id not in self.processed_games:
                    summ_team, win, summ_champion = self._extract_summ(game)
                    self._insert_row(summoner, summ_champion, win)

                    # Go through each fellow player
                    # and calculate if they won or lost based on if they
                    # are on the current summoners team.
                    for fellow in game['fellowPlayers']:
                        fsumm, fchamp, fteam = self._extract_fellow(fellow)
                        # Winners are fellows on the summoners team
                        if fteam == summ_team:
                            fwin = win
                        else:
                            fwin = not win

                        self._insert_row(fsumm, fchamp, fwin)
                        # Add the summoner to the list of summoners to process later
                        # because they've probably played more urf games
                        if summoner not in self.processed_summs:
                            self.summoners.append(fsumm)

                    self.processed_games.add(game_id)

                    if len(self.processed_games) % 100 == 0:
                        # Every 100 games, write info to db
#.........这里部分代码省略.........
开发者ID:Charleezy,项目名称:WinrateForFamiliarChamps,代码行数:101,代码来源:urf_by_summoner.py

示例10: PokemonGoBot


#.........这里部分代码省略.........
            logging.getLogger("requests").setLevel(logging.ERROR)
            logging.getLogger("pgoapi").setLevel(logging.ERROR)
            logging.getLogger("rpc_api").setLevel(logging.ERROR)

    def check_session(self, position):
        # Check session expiry
        if self.api._auth_provider and self.api._auth_provider._ticket_expire:
            remaining_time = self.api._auth_provider._ticket_expire / 1000 - time.time()

            if remaining_time < 60:
                logger.log("Session stale, re-logging in", 'yellow')
                self.position = position
                self.login()

    def login(self):
        logger.log('[#] Attempting login to Pokemon Go.', 'white')
        self.api._auth_token = None
        self.api._auth_provider = None
        self.api._api_endpoint = None
        self.api.set_position(*self.position)

        while not self.api.login(self.config.auth_service,
                                 str(self.config.username),
                                 str(self.config.password)):

            logger.log('[X] Login Error, server busy', 'red')
            logger.log('[X] Waiting 10 seconds to try again', 'red')
            time.sleep(10)

        logger.log('[+] Login to Pokemon Go successful.', 'green')

    def _setup_api(self):
        # instantiate pgoapi
        self.api = ApiWrapper(PGoApi())

        # check if the release_config file exists
        try:
            with open('release_config.json') as file:
                pass
        except:
            # the file does not exist, warn the user and exit.
            logger.log(
                '[#] IMPORTANT: Rename and configure release_config.json.example for your Pokemon release logic first!', 'red')
            exit(0)

        # provide player position on the earth
        self._set_starting_position()

        self.login()

        # chain subrequests (methods) into one RPC call

        # get player profile call
        # ----------------------
        self.api.get_player()

        response_dict = self.api.call()
        # print('Response dictionary: \n\r{}'.format(json.dumps(response_dict, indent=2)))
        currency_1 = "0"
        currency_2 = "0"

        player = response_dict['responses']['GET_PLAYER']['player_data']

        # @@@ TODO: Convert this to d/m/Y H:M:S
        creation_date = datetime.datetime.fromtimestamp(
            player['creation_timestamp_ms'] / 1e3)
开发者ID:daaaarcy,项目名称:PokemonGo-Bot,代码行数:67,代码来源:__init__.py

示例11: _setup_api

    def _setup_api(self):
        # instantiate pgoapi
        self.api = ApiWrapper(PGoApi())

        # check if the release_config file exists
        try:
            with open('release_config.json') as file:
                pass
        except:
            # the file does not exist, warn the user and exit.
            logger.log(
                '[#] IMPORTANT: Rename and configure release_config.json.example for your Pokemon release logic first!', 'red')
            exit(0)

        # provide player position on the earth
        self._set_starting_position()

        self.login()

        # chain subrequests (methods) into one RPC call

        # get player profile call
        # ----------------------
        self.api.get_player()

        response_dict = self.api.call()
        # print('Response dictionary: \n\r{}'.format(json.dumps(response_dict, indent=2)))
        currency_1 = "0"
        currency_2 = "0"

        player = response_dict['responses']['GET_PLAYER']['player_data']

        # @@@ TODO: Convert this to d/m/Y H:M:S
        creation_date = datetime.datetime.fromtimestamp(
            player['creation_timestamp_ms'] / 1e3)

        pokecoins = '0'
        stardust = '0'
        balls_stock = self.pokeball_inventory()

        if 'amount' in player['currencies'][0]:
            pokecoins = player['currencies'][0]['amount']
        if 'amount' in player['currencies'][1]:
            stardust = player['currencies'][1]['amount']

        logger.log('[#] Username: {username}'.format(**player))
        logger.log('[#] Acccount Creation: {}'.format(creation_date))
        logger.log('[#] Bag Storage: {}/{}'.format(
            self.get_inventory_count('item'), player['max_item_storage']))
        logger.log('[#] Pokemon Storage: {}/{}'.format(
            self.get_inventory_count('pokemon'), player[
                'max_pokemon_storage']))
        logger.log('[#] Stardust: {}'.format(stardust))
        logger.log('[#] Pokecoins: {}'.format(pokecoins))
        logger.log('[#] PokeBalls: ' + str(balls_stock[1]))
        logger.log('[#] GreatBalls: ' + str(balls_stock[2]))
        logger.log('[#] UltraBalls: ' + str(balls_stock[3]))

        self.get_player_info()

        if self.config.email_status:
            emailer.periodic_email_status(self)

        if self.config.initial_transfer:
            worker = InitialTransferWorker(self)
            worker.work()

        logger.log('[#]')
        self.update_inventory()
开发者ID:daaaarcy,项目名称:PokemonGo-Bot,代码行数:69,代码来源:__init__.py


注:本文中的api_wrapper.ApiWrapper类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。