本文整理汇总了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()
示例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()
示例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()
示例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()
示例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())
示例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."
示例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'
)
示例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."
示例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
#.........这里部分代码省略.........
示例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)
示例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()