Esempio n. 1
0
def goto(**kwargs):
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']
    assets = kwargs['assets']

    target_x = strategy['parameters']['x']
    target_y = strategy['parameters']['y']
    target_cell = strategy['parameters']['cell'] if 'cell' in strategy[
        'parameters'] else None
    target_worldmap = strategy['parameters'][
        'worldmap'] if 'worldmap' in strategy['parameters'] and strategy[
            'parameters']['worldmap'] is not None else 1

    logger = log.get_logger(__file__, strategy['bot'])

    path_maker = PathMaker(
        strategy=strategy,
        listener=listener,
        orders_queue=orders_queue,
        logger=logger,
        assets=assets,
        target_coord=(target_x, target_y),
        target_cell=target_cell,
        worldmap=target_worldmap,
    )
    strategy['report'] = path_maker.make_path()

    log.close_logger(logger)
    return strategy
 def __init__(self, bot_profile, strategies_queue: queue.Queue,
              reports_queue: queue.Queue, assets):
     self.bot = bot_profile
     self.logger = logger.get_logger(__name__, self.bot['name'])
     self.strategies_queue = strategies_queue
     self.reports_queue = reports_queue
     self.assets = assets
     self.logger.info('Starting LL API')
     self.port = randint(10000, 20000)
     while not self.try_port(self.port):
         self.port = randint(10000, 20000)
     args = [
         'java', '-jar',
         os.path.join(os.path.dirname(__file__), '..',
                      'black-falcon-api-1.0-jar-with-dependencies.jar'),
         '-p',
         str(self.port)
     ]
     Popen(' '.join(args), shell=True)
     time.sleep(5)
     self.logger.info('Starting listener')
     self.listener_crashed = [False]
     self.listener = Listener(self.bot, self.assets)
     self.listener_thread = Thread(target=self.listener_bootstrapper)
     self.listener_thread.start()
     self.logger.info('Starting connector')
     self.orders_queue = queue.Queue()
     self.connection_crashed = [False]
     self.connection = Thread(target=self.connection_bootstrapper)
     self.connection.start()
     self.logger.info('New commander spawned for {}'.format(
         self.bot['name']))
     Thread(target=self.interrupts).start()
     self.run()
     self.logger.info('Commander shut down')
Esempio n. 3
0
def ping(**kwargs):
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']

    logger = log.get_logger(__name__, strategy['bot'])
    last_ping = listener.game_state['ping'] if 'ping' in listener.game_state.keys() else 0

    logger.info('Sending order to bot API: {}'.format('ping'))

    orders_queue.put(('ping',))
    start = time.time()
    waiting = True
    while waiting:
        if 'ping' in listener.game_state.keys():
            if last_ping != listener.game_state['ping']:
                waiting = False
        time.sleep(0.05)
    travel_time = time.time() - start
    logger.info('Received pong response in {}'.format(travel_time))
    strategy['report'] = {
        'success': True,
        'details': 'Response time : {}'.format(travel_time)
    }

    # Properly closing the logger so there are not as many as calls to this function.
    log.close_logger(logger)
    return strategy
def get_game_state(**kwargs):
    """
    A strategy to display a bot's game state.

    :param kwargs: strategy, listener, and orders_queue
    :return: the input strategy with a report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']
    assets = kwargs['assets']

    logger = log.get_logger(__name__, strategy['bot'])
    start = time.time()
    game_state = listener.game_state
    execution_time = time.time() - start
    logger.info('Fetched game state in {}s'.format(execution_time))

    pos = game_state['pos'] if 'pos' in game_state else [-100, -100]
    worldmap = game_state['worldmap'] if 'worldmap' in game_state else -100
    cell = game_state['cell'] if 'cell' in game_state else -100
    misc_stat = game_state['inventory'] if 'inventory' in game_state.keys(
    ) else None

    strategy['report'] = {
        'success': True,
        'details': {
            'Execution time': execution_time,
            'game_state': (pos, worldmap, cell, misc_stat)
        }
    }
    log.close_logger(logger)
    return strategy
def bank_close(**kwargs):
    """
    A strategy to close a bank

    :param kwargs: strategy, listener, and orders_queue
    :return: the input strategy with a report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']
    assets = kwargs['assets']

    logger = log.get_logger(__name__, strategy['bot'])

    global_start, start = time.time(), time.time()

    if not listener.game_state['storage_open']:
        logger.info('Closed bank in {}s'.format(0))
        strategy['report'] = {
            'success': True,
            'details': {'Execution time': 0}
        }
        log.close_logger(logger)
        return strategy

    # Open NPC
    order = {
        'command': 'close_npc',
        'parameters': {}
    }
    logger.info('Sending order to bot API: {}'.format(order))
    orders_queue.put((json.dumps(order),))

    start = time.time()
    timeout = 10 if 'timeout' not in strategy.keys() else strategy['timeout']
    waiting = True
    while waiting and time.time() - start < timeout:
        if not listener.game_state['storage_open']:
            waiting = False
        time.sleep(0.05)

    execution_time = time.time() - start
    if waiting:
        logger.warning('Failed to close bank {}s'.format(execution_time))
        strategy['report'] = {
            'success': False,
            'details': {'Execution time': execution_time, 'Reason': 'Failed to close bank {}s'.format(execution_time)}
        }
        log.close_logger(logger)
        return strategy

    execution_time = time.time() - global_start
    logger.info('Closed bank in {}s'.format(execution_time))
    strategy['report'] = {
        'success': True,
        'details': {'Execution time': execution_time}
    }
    log.close_logger(logger)
    return strategy
Esempio n. 6
0
    def __init__(self):
        self.logger = get_logger(__name__)
        if not os.path.exists(DB_PATH):
            self.logger.error("[{}] doesn't exists. \
Run create_proxy_list.py".format(DB_PATH))
            sys.exit(1)
        self.connect = sqlite3.connect(DB_PATH)
        self.cursor = self.connect.cursor()
Esempio n. 7
0
def disconnect(**kwargs):
    """
    A strategy to disconnect a bot.

    :param kwargs: strategy, listener, and orders_queue
    :return: the input strategy with a report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']

    logger = log.get_logger(__name__, strategy['bot'])

    if 'connected' in listener.game_state.keys():
        if not listener.game_state['connected']:
            logger.info('Bot disconnected in {}s'.format(0))
            strategy['report'] = {
                'success': True,
                'details': {'Execution time': 0}
            }
            log.close_logger(logger)
            return strategy

    order = {
        'command': 'disconnect',
        'parameters': {
            'name': strategy['bot']
        }
    }
    logger.info('Sending order to bot API: {}'.format(order))
    orders_queue.put((json.dumps(order),))

    start = time.time()
    timeout = 20 if 'timeout' not in strategy.keys() else strategy['timeout']
    waiting = True
    while waiting and time.time() - start < timeout:
        if 'connected' in listener.game_state.keys():
            if not listener.game_state['connected']:
                waiting = False
        time.sleep(0.05)
    execution_time = time.time() - start

    if waiting:
        logger.warn('Failed disconnecting in {}s'.format(execution_time))
        strategy['report'] = {
            'success': False,
            'details': {'Execution time': execution_time, 'Reason': 'Timeout'}
        }
        log.close_logger(logger)
        return strategy

    logger.info('Disconnected {} in {}s'.format(strategy['bot'], execution_time))
    strategy['report'] = {
        'success': True,
        'details': {'Execution time': execution_time}
    }
    log.close_logger(logger)
    return strategy
def auctionh_close(**kwargs):
    """
    A strategy to close the auction house.

    :param kwargs: strategy, listener, and orders_queue
    :return: the input strategy with a report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']
    assets = kwargs['assets']

    logger = log.get_logger(__name__, strategy['bot'])

    global_start, start = time.time(), time.time()

    if not listener.game_state['auction_house_info']:
        strategy['report'] = {
            'success': True,
            'details': {'Execution time': time.time() - global_start}
        }
        log.close_logger(logger)
        return strategy

    order = {
        "command": "close_npc"
    }
    logger.info('Sending order to bot API: {}'.format(order))
    orders_queue.put((json.dumps(order),))

    start = time.time()
    timeout = 10 if 'timeout' not in strategy.keys() else strategy['timeout']
    waiting = True
    while waiting and time.time() - start < timeout:
        if 'auction_house_info' in listener.game_state.keys():
            if not listener.game_state['auction_house_info']:
                waiting = False
        time.sleep(0.05)
    execution_time = time.time() - start

    if waiting:
        logger.warn('Failed closing the auction house in {}s'.format(execution_time))
        strategy['report'] = {
            'success': False,
            'details': {'Execution time': execution_time, 'Reason': 'Failed closing the auction house in {}s'.format(execution_time)}
        }
        log.close_logger(logger)
        return strategy

    logger.info('Closed the auction house in {}s'.format(execution_time))
    strategy['report'] = {
        'success': True,
        'details': {'Execution time': time.time() - global_start}
    }
    log.close_logger(logger)
    return strategy
Esempio n. 9
0
 def __init__(self, host, port, orders_queue, output_queue, bot=None):
     self.stop = [False]
     self.host = host
     self.port = port
     self.logger = logger.get_logger(__name__, 'Connection-{}-{}'.format(host, port) if bot is None else bot['name'])
     self.orders_queue = orders_queue
     self.output_queue = output_queue
     self.connection_string = 'ws://{}:{}'.format(host, port)
     self.logger.info('Connecting to websocket at: ' + self.connection_string)
     self.connection = websocket.WebSocketApp(self.connection_string, on_open=self.on_open, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close)
     self.connection.run_forever(ping_interval=15)
     if not self.stop[0]:
         raise Exception("Websocket at {} closed unexpectedly".format(self.connection_string))
 def __init__(self, host):
     self.logger = logger.get_logger(__name__, 'swarm_node')
     self.assets_paths = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'assets'))
     self.assets = {}
     self.load_assets()
     Thread(target=self.maintain_assets).start()
     self.host = host
     self.api_port = 8721
     self.api = WebsocketServer(self.api_port, host=self.host)
     self.api.set_fn_message_received(self.api_on_message)
     self.api_thread = Thread(target=self.api.run_forever)
     self.api_thread.start()
     self.logger.info('Swarm API server started, listening on {}:{}'.format(self.host, self.api_port))
     self.report_queue = queue.Queue()
     self.reports_thread = Thread(target=self.reports_listener)
     self.reports_thread.start()
     self.cartography = {
         'messages': {},
         'authorized_clients': []
     }
    def __init__(self, bot: dict, assets):
        """
        The listener receives the data stream coming from the game trough the API. It maintains the current game state and a read only copy that the commander may access.

        :param bot: the bot dict.
        """
        self.stop = False
        self.assets = assets
        self.logger = logger.get_logger(__name__, bot['name'])
        self.output_queue = Queue()
        self.default_game_state = {
            'name': bot['name'],
            'id': bot['id'],
            'username': bot['username'],
            'password': bot['password'],
            'server': bot['server'],
            'connected': False,
            'sub_end': 0,
            'api_outdated': False,
            'banned': False,
            'npc_dialog_open': False,
            'npc_current_question': None,
            'npc_possible_replies': None,
            'zaap_dialog_open': False,
            'zaap_destinations': None,
            'in_fight': False,
            'storage_open': False,
            'jobs': {},
            'harvest_done': False,
            'harvest_started': False,
            'map_players': [],
            'map_elements': [],
            'stated_elements': [],
            'file_request_message': {'timestamp': 0},
            'auction_house_info': [],
            'achievement_available': []
        }
        self._game_state = json.loads(json.dumps(self.default_game_state))
        self.game_state = json.loads(json.dumps(self._game_state))
        self.messages_queue = []
Esempio n. 12
0
def LauncherMain():
	#Comenzamos el inicio de las cosas
	#Cargamos la configuracion
	AC.Loadcfg()
	#Inicializamos el logger
	log = logger.get_logger("./logs/Launcher ",True,True)
	#Descubrimos servicios
	services = SD.discover(AC.servicePath)
    #Ejecutamos scripts de extensiones (si, codigo arbitrario)
	tools.runparts("./launcherinit.d/")
	#Obtenemos la lista de juegos
	lista = GL.GameList(AC.gameList)
	log.log("[INIT/init] "+str(lista)) #debug
	#Finalizamos con lanzar la interfaz
	#Primero inicializamos el backend
	fac = ABF.ArcadeBackendFacade(lista,services)
	#poner la GUI a andar
	gui = None
	if args.console:
		gui = ArcadeCLI.ArcadeCLI(fac)
	else:
		gui = Interfaz.ArcadeGUIEx(fac)
	gui.go()
Esempio n. 13
0
def LauncherMain():
	#Comenzamos el inicio de las cosas
	#Cargamos la configuracion
	AC.Loadcfg()
	#Inicializamos el logger
	log = logger.get_logger("./logs/Launcher ",True,True)
	#Descubrimos servicios
	services = SD.discover(AC.servicePath)
    #Ejecutamos scripts de extensiones (si, codigo arbitrario)
	tools.runparts("./launcherinit.d/")
	#Obtenemos la lista de juegos
	lista = GL.GameList(AC.gameList)
	log.log("[INIT/init] "+str(lista)) #debug
	#Finalizamos con lanzar la interfaz
	#Primero inicializamos el backend
	fac = ABF.ArcadeBackendFacade(lista,services)
	#poner la GUI a andar
	gui = None
	if args.console:
		gui = ArcadeCLI.ArcadeCLI(fac)
	else:
		gui = Interfaz.ArcadeGUI(fac)
	gui.go()
def bank_open(**kwargs):
    """
    A strategy to open a bank

    :param kwargs: strategy, listener, and orders_queue
    :return: the input strategy with a report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']
    assets = kwargs['assets']

    logger = log.get_logger(__name__, strategy['bot'])

    global_start, start = time.time(), time.time()

    if listener.game_state['storage_open']:
        logger.info('Opened bank in {}s'.format(0))
        strategy['report'] = {
            'success': True,
            'details': {
                'Execution time': 0
            }
        }
        log.close_logger(logger)
        return strategy

    # Open NPC
    order = {
        'command': 'open_npc',
        'parameters': {
            'map_id': listener.game_state['map_id'],
            'npc_id': -20001,
            'action_id': 3
        }
    }
    logger.info('Sending order to bot API: {}'.format(order))
    orders_queue.put((json.dumps(order), ))

    start = time.time()
    timeout = 10 if 'timeout' not in strategy.keys() else strategy['timeout']
    waiting = True
    while waiting and time.time() - start < timeout:
        if listener.game_state['npc_dialog_open']:
            waiting = False
        time.sleep(0.05)

    execution_time = time.time() - start
    if waiting:
        logger.warning(
            'Failed to open NPC dialog in {}s'.format(execution_time))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': execution_time,
                'Reason': 'Timeout'
            }
        }
        log.close_logger(logger)
        return strategy

    # Answer question
    order = {
        'command': 'answer_npc',
        'parameters': {
            'reply_id': listener.game_state['npc_possible_replies'][0]
        }
    }
    logger.info('Sending order to bot API: {}'.format(order))
    orders_queue.put((json.dumps(order), ))

    start = time.time()
    timeout = 10 if 'timeout' not in strategy.keys() else strategy['timeout']
    waiting = True
    while waiting and time.time() - start < timeout:
        if 'storage_open' in listener.game_state.keys():
            if listener.game_state['storage_open']:
                waiting = False
        time.sleep(0.05)

    if waiting:
        logger.warning('Failed to answer NPC to open storage in {}s'.format(
            execution_time))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time':
                execution_time,
                'Reason':
                'Failed to answer NPC to open storage in {}s'.format(
                    execution_time)
            }
        }
        log.close_logger(logger)
        return strategy

    execution_time = time.time() - global_start
    logger.info('Opened bank in {}s'.format(execution_time))
    strategy['report'] = {
        'success': True,
        'details': {
            'Execution time': execution_time
        }
    }
    log.close_logger(logger)
    return strategy
Esempio n. 15
0
def move(**kwargs):
    """
    A strategy move the bot within a map.

    :param kwargs: strategy, listener, and orders_queue
    :return: the input strategy with a report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']
    assets = kwargs['assets']

    logger = log.get_logger(__name__, strategy['bot'])
    global_start = time.time()

    # Close the auction house if it is open
    if len(listener.game_state['auction_house_info']):
        sub_strategy = auctionh_close.auctionh_close(listener=listener,
                                                     orders_queue=orders_queue,
                                                     assets=assets,
                                                     strategy={
                                                         "bot":
                                                         strategy['bot'],
                                                     })
        if not sub_strategy['report']['success']:
            strategy['report'] = {
                'success': False,
                'details': {
                    'Execution time': time.time() - global_start,
                    'Reason': sub_strategy['report']
                }
            }
            log.close_logger(logger)
            return strategy

    if 'cell' in listener.game_state.keys():
        if listener.game_state['cell'] == strategy['parameters']['cell']:
            logger.info('Completed move to cell {} in {}s'.format(
                strategy['parameters']['cell'], 0))
            strategy['report'] = {
                'success': True,
                'details': {
                    'Execution time': 0
                }
            }
            log.close_logger(logger)
            return strategy

    current_pos = '{};{}'.format(listener.game_state['pos'][0],
                                 listener.game_state['pos'][1])
    map_data = support_functions.fetch_map(assets['map_info'], current_pos,
                                           listener.game_state['worldmap'])
    deserialized_raw_cells = []
    for cell in map_data['rawCells']:
        deserialized_raw_cells.append(
            ast.literal_eval(assets['map_info_index'][cell]))
    order = {
        'command': 'move',
        'parameters': {
            "isUsingNewMovementSystem": map_data['isUsingNewMovementSystem'],
            "cells": deserialized_raw_cells,
            "target_cell": strategy['parameters']['cell']
        }
    }
    logger.info('Sending order to bot API: {}'.format(order))
    orders_queue.put((json.dumps(order), ))

    start = time.time()
    timeout = 20 if 'timeout' not in strategy.keys() else strategy['timeout']
    waiting = True
    while waiting and time.time() - start < timeout:
        if 'pos' in listener.game_state.keys(
        ) and 'worldmap' in listener.game_state.keys():
            if listener.game_state['cell'] == strategy['parameters']['cell']:
                waiting = False
        time.sleep(0.05)
    execution_time = time.time() - start

    if waiting:
        logger.warn('Failed moving to cell {} in {}s'.format(
            strategy['parameters']['cell'], execution_time))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': execution_time,
                'Reason': 'Timeout, no map movement for bot'
            }
        }
        log.close_logger(logger)
        return strategy

    start = time.time()
    timeout = 20 if 'timeout' not in strategy.keys() else strategy['timeout']
    waiting = True
    while waiting and time.time() - start < timeout:
        if 'pos' in listener.game_state.keys(
        ) and 'worldmap' in listener.game_state.keys():
            if not listener.game_state['currently_walking']:
                waiting = False
        time.sleep(0.05)
    execution_time = time.time() - start

    if waiting:
        logger.warn('Failed moving to cell {} in {}s'.format(
            strategy['parameters']['cell'], execution_time))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': execution_time,
                'Reason': 'Timeout, no movement confirmation'
            }
        }
        log.close_logger(logger)
        return strategy

    logger.info('Completed move to cell {} in {}s'.format(
        strategy['parameters']['cell'],
        time.time() - global_start))
    strategy['report'] = {
        'success': True,
        'details': {
            'Execution time': execution_time
        }
    }
    log.close_logger(logger)
    return strategy
Esempio n. 16
0
import os
import torch
from collections import OrderedDict
import torch.utils.model_zoo as model_zoo

from time import time

from tools.logger import get_logger

logger = get_logger()
model_urls = {
    'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
    'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
    'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
    'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
    'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}


def load_model(model, model_file, is_restore=False):
    t_start = time()
    if isinstance(model_file, str):
        state_dict = torch.load(model_file)
        if 'model' in state_dict.keys():
            state_dict = state_dict['model']
    else:
        state_dict = model_file
    t_ioend = time()

    if is_restore:
        new_state_dict = OrderedDict()
def go_drop_bank(**kwargs):
    """
    Go to the bank to drop what it holds

    :param kwargs:
    :return: report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']
    assets = kwargs['assets']

    logger = log.get_logger(__name__, strategy['bot'])
    start, global_start = time.time(), time.time()

    if 'parameters' in strategy.keys() and 'return' in strategy['parameters'].keys() and strategy['parameters']['return'] == 'current':
        strategy['parameters']['return'] = {'pos': listener.game_state['pos'], 'cell': listener.game_state['cell'], 'worldmap': listener.game_state['worldmap']}

    sub_strategy = strategies.goto.goto(
        orders_queue=orders_queue,
        assets=assets,
        listener=listener,
        strategy={
            'bot': strategy['bot'],
            'parameters': {
                'x': 4,
                'y': -18,
                'worldmap': 1
            }
        }
    )
    if not sub_strategy['report']['success']:
        strategy['report'] = {
            'success': False,
            'details': {'Execution time': time.time() - start, 'Reason': sub_strategy['report']}
        }
        log.close_logger(logger)
        return strategy

    sub_strategy = strategies.bank_enter.bank_enter(
        orders_queue=orders_queue,
        assets=assets,
        listener=listener,
        strategy={
            'bot': strategy['bot'],
        }
    )
    if not sub_strategy['report']['success']:
        strategy['report'] = {
            'success': False,
            'details': {'Execution time': time.time() - start, 'Reason': sub_strategy['report']}
        }
        log.close_logger(logger)
        return strategy

    sub_strategy = strategies.bank_open.bank_open(
        orders_queue=orders_queue,
        assets=assets,
        listener=listener,
        strategy={
            'bot': strategy['bot'],
        }
    )
    if not sub_strategy['report']['success']:
        strategy['report'] = {
            'success': False,
            'details': {'Execution time': time.time() - start, 'Reason': sub_strategy['report']}
        }
        log.close_logger(logger)
        return strategy

    sub_strategy = strategies.bank_put_items.bank_put_items(
        orders_queue=orders_queue,
        assets=assets,
        listener=listener,
        strategy={
            'bot': strategy['bot'],
            'parameters': {
                'items': 'all'
            }
        }
    )
    if not sub_strategy['report']['success']:
        strategy['report'] = {
            'success': False,
            'details': {'Execution time': time.time() - start, 'Reason': sub_strategy['report']}
        }
        log.close_logger(logger)
        return strategy

    sub_strategy = strategies.bank_get_kamas.bank_get_kamas(
        orders_queue=orders_queue,
        assets=assets,
        listener=listener,
        strategy={
            'bot': strategy['bot'],
        }
    )
    if not sub_strategy['report']['success']:
        strategy['report'] = {
            'success': False,
            'details': {'Execution time': time.time() - start, 'Reason': sub_strategy['report']}
        }
        log.close_logger(logger)
        return strategy

    sub_strategy = strategies.bank_close.bank_close(
        orders_queue=orders_queue,
        assets=assets,
        listener=listener,
        strategy={
            'bot': strategy['bot'],
        }
    )
    if not sub_strategy['report']['success']:
        strategy['report'] = {
            'success': False,
            'details': {'Execution time': time.time() - start, 'Reason': sub_strategy['report']}
        }
        log.close_logger(logger)
        return strategy

    sub_strategy = strategies.bank_exit.bank_exit(
        orders_queue=orders_queue,
        assets=assets,
        listener=listener,
        strategy={
            'bot': strategy['bot'],
        }
    )
    if not sub_strategy['report']['success']:
        strategy['report'] = {
            'success': False,
            'details': {'Execution time': time.time() - start, 'Reason': sub_strategy['report']}
        }
        log.close_logger(logger)
        return strategy

    if 'parameters' in strategy.keys() and 'return' in strategy['parameters'].keys() and strategy['parameters']['return'] is not None:
        sub_strategy = strategies.goto.goto(
            orders_queue=orders_queue,
            assets=assets,
            listener=listener,
            strategy={
                'bot': strategy['bot'],
                'parameters': {
                    'x': strategy['parameters']['return']['pos'][0],
                    'y': strategy['parameters']['return']['pos'][1],
                    'cell': strategy['parameters']['return']['cell'] if 'cell' in strategy['parameters']['return'].keys() else None,
                    'worldmap': strategy['parameters']['return']['worldmap'] if 'worldmap' in strategy['parameters']['return'].keys() else 1
                }
            }
        )
        if not sub_strategy['report']['success']:
            strategy['report'] = {
                'success': False,
                'details': {'Execution time': time.time() - start, 'Reason': sub_strategy['report']}
            }
            log.close_logger(logger)
            return strategy

    logger.info('Dropped to bank in {}s'.format(time.time() - global_start))
    strategy['report'] = {
        'success': True,
        'details': {'Execution time': time.time() - global_start}
    }
    log.close_logger(logger)
    return strategy
Esempio n. 18
0
import atexit
import os
import signal
import sys
import time

from rpc import SimpleJSONRPCServer
from tools import logger as logging
from qt4i.driver.util._process import Process

DEFAULT_IP = '0.0.0.0'
DEFAULT_PORT = 12306
DEFAULT_AGENT_PORT = 8100
DEFAULT_PID_FILE = '/tmp/driverserver.pid'

logger = logging.get_logger()


class ArgumentParser(argparse.ArgumentParser):
    '''Argument parser, automatically display help while error
    '''
    def error(self, message):
        sys.stderr.write('error: %s\n' % message)
        self.print_help()
        sys.exit(2)


CMD_HELP = {
    "start": "start driver server daemon",
    "stop": "stop driver server daemon",
    "restart": "stop driver server daemon and start it again",
Esempio n. 19
0
"""
Provides the main entry point for the discord bot.
"""

import logging
import os
import discord

# Import from local modules.
import commands
from tools.logger import get_logger
from tools.wrapper import Response
from registry import COMMAND_DICT, safe_call, CommandNotFoundError

CLIENT = discord.Client()
LOGGER = get_logger("bot")
PREFIX = os.environ.get("COMMAND_PREFIX", "!")

DB_ENGINE = None
DB_SESSION = None


@CLIENT.event
async def on_ready():
    """ Log login information. """

    print(f"Logged in as bot: {CLIENT.user.name} ({CLIENT.user.id}).")
    LOGGER.info("Logged in as bot: %s (%s).", CLIENT.user.name, CLIENT.user.id)

    print("Connected to the following servers:")
    server_list = await CLIENT.fetch_guilds().flatten()
Esempio n. 20
0
def connect(**kwargs):
    """
    A strategy to connect a bot.

    :param kwargs: strategy, listener, and orders_queue
    :return: the input strategy with a report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']
    assets = kwargs['assets']

    logger = log.get_logger(__name__, strategy['bot'])

    if support_functions.get_profile(strategy['bot'])['banned']:
        logger.warning('{} has been banned'.format(strategy['bot']))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': 0,
                'Reason': '{} has been banned'.format(strategy['bot'])
            }
        }
        log.close_logger(logger)
        return strategy

    if 'connected' in listener.game_state.keys():
        if listener.game_state['connected']:
            logger.info('Bot connected in {}s'.format(0))
            strategy['report'] = {
                'success': True,
                'details': {
                    'Execution time': 0
                }
            }
            log.close_logger(logger)
            return strategy

    bot_profile = strategies.support_functions.get_profile(strategy['bot'])
    order = {
        'command': 'connect',
        'parameters': {
            'name': bot_profile['name'],
            'username': bot_profile['username'],
            'password': bot_profile['password'],
            'serverId': assets['server_2_id'][bot_profile['server']],
        }
    }
    logger.info('Sending order to bot API: {}'.format(order))
    orders_queue.put((json.dumps(order), ))

    start = time.time()
    timeout = 40 if 'timeout' not in strategy.keys() else strategy['timeout']
    waiting = True
    while waiting and time.time() - start < timeout:
        if 'connected' in listener.game_state.keys(
        ) and 'api_outdated' in listener.game_state.keys():
            if 'pos' in listener.game_state.keys() or listener.game_state[
                    'api_outdated'] or listener.game_state['banned']:
                # Actually wait for the map to load and not just a connection confirmation
                waiting = False
        time.sleep(0.05)
    execution_time = time.time() - start

    if waiting:
        logger.warn('Failed connecting in {}s'.format(execution_time))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': execution_time,
                'Reason': 'Timeout'
            }
        }
        log.close_logger(logger)
        return strategy

    if listener.game_state['api_outdated']:
        logger.warn(
            'Your BlackFalconAPI is outdated. Try to get the latest one or contact the BlackFalcon team if you already have the latest version'
        )
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time':
                execution_time,
                'Reason':
                'Your BlackFalconAPI is outdated. Try to get the latest one or contact the BlackFalcon team if you already have the latest version'
            }
        }
        log.close_logger(logger)
        return strategy

    if listener.game_state['banned']:
        logger.warn('{} has been banned'.format(strategy['bot']))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': execution_time,
                'Reason': '{} has been banned'.format(strategy['bot'])
            }
        }
        log.close_logger(logger)
        return strategy

    logger.info('Connected {} in {}s'.format(strategy['bot'], execution_time))
    strategy['report'] = {
        'success': True,
        'details': {
            'Execution time': execution_time
        }
    }
    log.close_logger(logger)
    return strategy
def enter_dd_territory(**kwargs):
    """
    A strategy to enter the DD territory using the stairs in the east.

    :param kwargs: strategy, listener, and orders_queue
    :return: the input strategy with a report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']
    assets = kwargs['assets']

    logger = log.get_logger(__name__, strategy['bot'])

    global_start, start = time.time(), time.time()

    # Get the IDs for activating the steps
    element_id, skill_uid = None, None
    current_map = listener.game_state['pos']
    for element in listener.game_state['map_elements']:
        if 'enabledSkills' in element.keys():
            for skill in element['enabledSkills']:
                if 'skillId' in skill.keys() and skill['skillId'] == 184:
                    element_id = element['elementId']
                    skill_uid = skill['skillInstanceUid']

    if element_id is None or skill_uid is None:
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time':
                time.time() - start,
                'Reason':
                'Could not find the stairs door at {}, map id : {}'.format(
                    current_map, listener.game_state['map_id'])
            }
        }
        log.close_logger(logger)
        return strategy
    report = strategies.move.move(strategy={
        'bot': strategy['bot'],
        'command': 'move',
        'parameters': {
            'cell': 387
        }
    },
                                  listener=listener,
                                  assets=assets,
                                  orders_queue=orders_queue)['report']

    if not report['success']:
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': time.time() - start,
                'reason': 'Move failed'
            }
        }
        log.close_logger(logger)
        return strategy

    order = {
        'command': 'use_interactive',
        'parameters': {
            'element_id': element_id,
            'skill_uid': skill_uid
        }
    }
    logger.info('Sending order to bot API: {}'.format(order))
    orders_queue.put((json.dumps(order), ))

    start = time.time()
    timeout = 10 if 'timeout' not in strategy.keys() else strategy['timeout']
    waiting = True
    while waiting and time.time() - start < timeout:
        if 'pos' in listener.game_state.keys():
            if listener.game_state['pos'] == [-22, -1]:
                waiting = False
        time.sleep(0.05)
    execution_time = time.time() - start

    if waiting:
        logger.warn(
            'Failed entering DD territory using the stairs in {}s'.format(
                execution_time))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': execution_time,
                'Reason': 'Timeout'
            }
        }
        log.close_logger(logger)
        return strategy

    logger.info(
        'Entered DD territory using the stairs in {}s'.format(execution_time))
    strategy['report'] = {
        'success': True,
        'details': {
            'Execution time': execution_time
        }
    }
    log.close_logger(logger)
    return strategy
def harvest(**kwargs):
    """
    Harvests a cell's resources after checking that it can.

    :param kwargs:
    :return: report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']
    assets = kwargs['assets']

    resource_cell = strategy['parameters']['cell']

    logger = log.get_logger(__name__, strategy['bot'])
    start, global_start = time.time(), time.time()

    # Manage whitelist/blacklist
    if 'whitelist' in strategy['parameters'].keys() and \
            strategy['parameters']['whitelist'] is not None and \
            'blacklist' in strategy['parameters'].keys() and \
            strategy['parameters']['blacklist'] is not None:
        logger.warn(
            'You can not have a whitelist and a blacklist at the same time')
        strategy['report'] = {
            'success': False,
            'details': {
                'Reason':
                'You can not have a whitelist and a blacklist at the same time'
            }
        }
        log.close_logger(logger)
        return strategy

    if 'whitelist' in strategy['parameters'].keys(
    ) and strategy['parameters']['whitelist'] is not None:
        whitelist = strategy['parameters']['whitelist']
    elif 'blacklist' in strategy['parameters'].keys(
    ) and strategy['parameters']['blacklist'] is not None:
        whitelist = [
            int(key) for key in assets['id_2_names'].keys()
            if key not in strategy['parameters']['blacklist']
        ]
    else:
        whitelist = [int(key) for key in assets['id_2_names'].keys()]

    # Check if the cell has an available resource
    element_id = None
    for element in listener.game_state['stated_elements']:
        if element['elementCellId'] == resource_cell:
            element_id = element['elementId']
    if element_id is None:
        logger.warn('Did not find a resource at cell {} in {}s'.format(
            resource_cell, 0))
        strategy['report'] = {
            'success': False,
            'details': {
                'Reason':
                'Did not find a resource at cell {} in {}s'.format(
                    resource_cell, 0)
            }
        }
        log.close_logger(logger)
        return strategy

    skill_id, skill_uid = None, None
    for element in listener.game_state['map_elements']:
        if element_id == element['elementId']:
            if 'enabledSkills' in element.keys():
                for skill in element['enabledSkills']:
                    if 'skillId' in skill.keys():
                        skill_id = skill['skillId']
                        skill_uid = skill['skillInstanceUid']
    if skill_id is None:
        logger.warn(
            'Resource at cell {} is not harvestable'.format(resource_cell))
        strategy['report'] = {
            'success': False,
            'details': {
                'Reason':
                'Resource at cell {} is not harvestable'.format(resource_cell)
            }
        }
        log.close_logger(logger)
        return strategy

    # Check if the resource is whitelisted
    for skill in assets['Skills']:
        if skill['id'] == skill_id and skill[
                'gatheredRessourceItem'] not in whitelist:
            logger.warn(
                'Resource ({}/{}) at cell {} is not whitelisted'.format(
                    skill['gatheredRessourceItem'],
                    assets['id_2_names'][str(skill['gatheredRessourceItem'])],
                    resource_cell))
            strategy['report'] = {
                'success': False,
                'details': {
                    'Reason':
                    'Resource ({}/{}) at cell {} is not whitelisted'.format(
                        skill['gatheredRessourceItem'],
                        assets['id_2_names'][str(
                            skill['gatheredRessourceItem'])], resource_cell)
                }
            }
            log.close_logger(logger)
            return strategy

    # Check if the player has the skill level to harvest it
    required_skill_level, range = None, None
    for skill in assets['Skills']:
        if skill['id'] == skill_id:
            required_skill_level = skill['levelMin']
            range = skill['range']
    if required_skill_level is None:
        logger.warn('Skill id not found')
        strategy['report'] = {
            'success': False,
            'details': {
                'Reason': 'Skill id not found'
            }
        }
        log.close_logger(logger)
        return strategy

    bot_skill_level = None
    for job_id, job in listener.game_state['jobs'].items():
        for skill in job['skills']:
            if skill['skillId'] == skill_id:
                bot_skill_level = job['jobLevel']
    if bot_skill_level is None:
        logger.warn('Could not determine bot skill level')
        strategy['report'] = {
            'success': False,
            'details': {
                'Reason': 'Could not determine bot skill level'
            }
        }
        log.close_logger(logger)
        return strategy

    if bot_skill_level < required_skill_level:
        logger.warn('Bot skill level insufficient')
        strategy['report'] = {
            'success': False,
            'details': {
                'Reason': 'Bot skill level insufficient'
            }
        }
        log.close_logger(logger)
        return strategy

    # TODO: remove this after fight is implemented
    if bot_skill_level > 19:
        logger.warn('Bot skill level too high')
        strategy['report'] = {
            'success': False,
            'details': {
                'Reason': 'Bot skill level too high'
            }
        }
        log.close_logger(logger)
        return strategy

    # Check if the player can reach the resource i.e. skill range >= manhattan distance between closest reachable cell and resource cell
    closest_reachable_cell = support_functions.get_closest_reachable_cell(
        assets['map_info'], resource_cell, listener.game_state['cell'],
        listener.game_state['pos'], listener.game_state['worldmap'])
    dist = sum([
        abs(a - b)
        for a, b in zip(support_functions.cell_2_coord(closest_reachable_cell),
                        support_functions.cell_2_coord(resource_cell))
    ])
    if dist > range:
        logger.warn('Resource out of range')
        strategy['report'] = {
            'success': False,
            'details': {
                'Reason': 'Resource out of range'
            }
        }
        log.close_logger(logger)
        return strategy

    # Move the bot the appropriate cell to use the resource
    sub_strategy = strategies.move.move(listener=listener,
                                        strategy={
                                            'bot': strategy['bot'],
                                            'parameters': {
                                                'cell': closest_reachable_cell
                                            }
                                        },
                                        orders_queue=orders_queue,
                                        assets=assets)
    if not sub_strategy['report']['success']:
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': time.time() - start,
                'Reason': 'Move to get to resource harvest spot failed'
            }
        }
        log.close_logger(logger)
        return strategy

    # Check if the resource is still available
    element_id = None
    for element in listener.game_state['stated_elements']:
        if element['elementCellId'] == resource_cell:
            element_id = element['elementId']
    if element_id is None:
        logger.warn('Did not find a resource at cell {} in {}s'.format(
            resource_cell, 0))
        strategy['report'] = {
            'success': False,
            'details': {
                'Reason':
                'Did not find a resource at cell {} in {}s'.format(
                    resource_cell, 0)
            }
        }
        log.close_logger(logger)
        return strategy

    skill_id, skill_uid = None, None
    for element in listener.game_state['map_elements']:
        if element_id == element['elementId']:
            if 'enabledSkills' in element.keys():
                for skill in element['enabledSkills']:
                    if 'skillId' in skill.keys():
                        skill_id = skill['skillId']
                        skill_uid = skill['skillInstanceUid']
    if skill_id is None:
        logger.warn(
            'Resource at cell {} is not harvestable'.format(resource_cell))
        strategy['report'] = {
            'success': False,
            'details': {
                'Reason':
                'Resource at cell {} is not harvestable'.format(resource_cell)
            }
        }
        log.close_logger(logger)
        return strategy

    # # ---------------------------------------
    # # TODO: temporary blocking of harvest operation to check if that's the source of bans
    # strategy['report'] = {
    #     'success': True,
    #     'details': {
    #         'Execution time': time.time() - global_start,
    #         'Collected': {}
    #     }
    # }
    #
    # log.close_logger(logger)
    # return strategy
    # # ---------------------------------------

    # harvest
    inventory_before_harvest = json.loads(
        json.dumps(listener.game_state['inventory']))
    order = {
        'command': 'use_interactive',
        'parameters': {
            'element_id': element_id,
            'skill_uid': skill_uid
        }
    }
    logger.info('Sending order to bot API: {}'.format(order))
    orders_queue.put((json.dumps(order), ))

    start = time.time()
    timeout = 10 if 'timeout' not in strategy.keys() else strategy['timeout']
    waiting = True
    while waiting and time.time() - start < timeout:
        if listener.game_state['harvest_started']:
            waiting = False
        time.sleep(0.05)
    execution_time = time.time() - start

    if waiting:
        logger.warn('Failed to start harvest in {}s'.format(execution_time))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': execution_time,
                'Reason':
                'Failed to start harvest in {}s'.format(execution_time)
            }
        }
        log.close_logger(logger)
        return strategy

    start = time.time()
    timeout = 10 if 'timeout' not in strategy.keys() else strategy['timeout']
    waiting = True
    while waiting and time.time() - start < timeout:
        if listener.game_state['harvest_done']:
            waiting = False
        time.sleep(0.05)
    execution_time = time.time() - start

    if waiting:
        logger.warn(
            'Harvest started but did not end ? in {}s'.format(execution_time))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time':
                execution_time,
                'Reason':
                'Harvest started but did not end ? in {}s'.format(
                    execution_time)
            }
        }
        log.close_logger(logger)
        return strategy

    collected = {}
    inventory_after_harvest = json.loads(
        json.dumps(listener.game_state['inventory']))
    for item in inventory_after_harvest:
        was_in_inventory = False
        for item_before in inventory_before_harvest:
            if item['objectUID'] == item_before['objectUID']:
                was_in_inventory = True
                if item['quantity'] != item_before['quantity']:
                    if assets['id_2_names'][str(
                            item['objectGID'])] in collected.keys():
                        collected[assets['id_2_names'][str(
                            item['objectGID']
                        )]] += item['quantity'] - item_before['quantity']
                    else:
                        collected[assets['id_2_names'][str(
                            item['objectGID']
                        )]] = item['quantity'] - item_before['quantity']

        if not was_in_inventory:
            collected[assets['id_2_names'][str(
                item['objectGID'])]] = item['quantity']

    logger.info('Harvested {} in {}s'.format(collected, execution_time))

    strategy['report'] = {
        'success': True,
        'details': {
            'Execution time': execution_time,
            'Collected': collected
        }
    }

    log.close_logger(logger)
    return strategy
Esempio n. 23
0
#modulo encargado de la instalacion de balls, delegando si es necesario

import zipfile
import tools.logger
import ball_info

global log_
log_ = logger.get_logger()

def install_ball(path):
	"""Funcion que permite instalar un ball, dado el path a este.
	"""

	#El primer paso es abrir el archivo
	log_.log("[BallInstall/install_ball] Opening "+path)
	with zipfile.ZipFile(path,"r") as b:
		b_file = b.open("BallInfo.xml")
		#Ahora se verifican que existan las dependencias
		b_info = ball_info.BallInfo(b_file)
		if not check_dependencies(b_info):
			#Faltan requisitos
			log_.log("[BallInstall/install_ball] Missing requisites for ball "+path)
			#Informamos que no se realizo instalacion
			return False
		#Si pasa el check de dependencias, procedemos
		log_.log("[BallInstall/install_ball] Dependencies OK")
		#TODO: Llamar a instalador del tipo
		return_val = False
		try:
			imstr = "install."+str(b_info.get_balltype)
			eval("import "+imstr)
def enter_havenbag(**kwargs):
    """
    A strategy to enter the haven bag.
    Checks if the player is level > 10 and if it's already inside.

    :param kwargs: strategy, listener, and orders_queue
    :return: the input strategy with a report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']

    logger = log.get_logger(__name__, strategy['bot'])

    if listener.game_state['level'] < 10:
        logger.warn('Bot level too low')
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': 0,
                'Reason': 'Bot level too low'
            }
        }
        log.close_logger(logger)
        return strategy

    if listener.game_state['sub_end'] < time.time():
        logger.warn('Bot not subscribed')
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': 0,
                'Reason': 'Bot not subscribed'
            }
        }
        log.close_logger(logger)
        return strategy

    if 'in_haven_bag' in listener.game_state.keys():
        if listener.game_state['in_haven_bag']:
            logger.info('Entered havenbag in {}s'.format(0))
            strategy['report'] = {
                'success': True,
                'details': {
                    'Execution time': 0
                }
            }
            log.close_logger(logger)
            return strategy

    order = {'command': 'enter_havenbag'}
    logger.info('Sending order to bot API: {}'.format(order))
    orders_queue.put((json.dumps(order), ))

    start = time.time()
    timeout = 10 if 'timeout' not in strategy.keys() else strategy['timeout']
    waiting = True
    while waiting and time.time() - start < timeout:
        if 'in_haven_bag' in listener.game_state.keys():
            if listener.game_state['in_haven_bag']:
                waiting = False
        time.sleep(0.05)
    execution_time = time.time() - start

    if waiting:
        logger.warn('Failed entering havenbag in {}s'.format(execution_time))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': execution_time,
                'Reason': 'Timeout'
            }
        }
        log.close_logger(logger)
        return strategy

    logger.info('Entered havenbag in {}s'.format(execution_time))
    strategy['report'] = {
        'success': True,
        'details': {
            'Execution time': execution_time
        }
    }
    log.close_logger(logger)
    return strategy
def bank_get_items(**kwargs):
    """
    A strategy to get items from the bank

    :param kwargs: strategy, listener, and orders_queue
    :return: the input strategy with a report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']
    assets = kwargs['assets']

    logger = log.get_logger(__name__, strategy['bot'])

    global_start, start = time.time(), time.time()

    items_to_transfer = {}
    if 'parameters' in strategy.keys(
    ) and 'items' in strategy['parameters'].keys():
        if strategy['parameters']['items'] != 'all' and strategy['parameters'][
                'items'] is not None:
            for item in strategy['parameters']['items']:
                items_to_transfer[item['general_id']] = item[
                    'quantity'] if 'quantity' in item.keys() else 'all'
        else:
            items_to_transfer = 'all'
    else:
        items_to_transfer = 'all'

    if not listener.game_state['storage_open']:
        logger.warning('Bank is not open')
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': 0,
                'Reason': 'Bank is not open'
            }
        }
        log.close_logger(logger)
        return strategy

    # Check that all requested items with a specified quantity are in the storage
    if type(items_to_transfer) is dict:
        for key in items_to_transfer.keys():
            found = False
            for item in listener.game_state['storage_content']['objects']:
                if item['objectGID'] == key:
                    found = True
            if not found:
                logger.warning(
                    'Object {}/{} with requested quantity {} is not in the storage'
                    .format(key, assets['id_2_names'][str(key)],
                            items_to_transfer[key]))
                strategy['report'] = {
                    'success': False,
                    'details': {
                        'Execution time':
                        0,
                        'Reason':
                        'Object {}/{} with requested quantity {} is not in the storage'
                        .format(key, assets['id_2_names'][str(key)],
                                items_to_transfer[key])
                    }
                }
                log.close_logger(logger)
                return strategy

    uids_to_transfer_all = []
    uids_to_transfer_specified = []
    transfer_recap = []
    for item in listener.game_state['storage_content']['objects']:
        if items_to_transfer == 'all':
            transfer_recap.append({
                'GID':
                item['objectGID'],
                'name':
                assets['id_2_names'][str(item['objectGID'])],
                'quantity':
                item['quantity'],
                'weight_one':
                assets['id_2_weight'][str(item['objectGID'])]
            })

            uids_to_transfer_all.append(item['objectUID'])
        elif item['objectGID'] in items_to_transfer.keys():
            transfer_recap.append({
                'GID':
                item['objectGID'],
                'quantity':
                item['quantity'],
                'weight_one':
                assets['id_2_weight'][str(item['objectGID'])]
            })

            if items_to_transfer[item['objectGID']] == 'all':
                uids_to_transfer_all.append(item['objectUID'])
            elif items_to_transfer[item['objectGID']] > 0:
                if item['quantity'] < items_to_transfer[item['objectGID']]:
                    logger.warning(
                        'Requested quantity of {} {}:{} is not available in storage ({} available )'
                        .format(items_to_transfer[item['objectGID']],
                                item['objectGID'],
                                assets['id_2_names'][str(item['objectGID'])],
                                item['quantity']))
                    strategy['report'] = {
                        'success': False,
                        'details': {
                            'Execution time':
                            0,
                            'Reason':
                            'Requested quantity of {} {}/{} is not available in storage ({} available )'
                            .format(
                                items_to_transfer[item['objectGID']],
                                item['objectGID'],
                                assets['id_2_names'][str(item['objectGID'])],
                                item['quantity'])
                        }
                    }
                    log.close_logger(logger)
                    return strategy

                uids_to_transfer_specified.append({
                    'unique_id':
                    item['objectUID'],
                    'quantity':
                    items_to_transfer[item['objectGID']]
                })
                transfer_recap[-1]['quantity'] = items_to_transfer[
                    item['objectGID']]

    # Check weight
    available_weight = listener.game_state['max_weight'] - listener.game_state[
        'weight']
    transfer_weight = sum(
        [item['quantity'] * item['weight_one'] for item in transfer_recap])
    if transfer_weight > available_weight:
        logger.warning(
            'Requested transfer ({} pods) would exceed carry capacity ({} pods)'
            .format(transfer_weight, available_weight))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time':
                0,
                'Reason':
                'Requested transfer ({} pods) would exceed carry capacity ({} pods)'
                .format(transfer_weight, available_weight)
            }
        }
        log.close_logger(logger)
        return strategy

    # Transfer pack (quantity unspecified)
    if len(uids_to_transfer_all):
        inventory_before = json.loads(
            json.dumps(listener.game_state['inventory']))
        order = {
            "command": "storage_to_inv_list",
            "parameters": {
                "items_uids": uids_to_transfer_all
            }
        }
        logger.info('Sending order to bot API: {}'.format(order))
        orders_queue.put((json.dumps(order), ))

        start = time.time()
        timeout = 10 if 'timeout' not in strategy.keys(
        ) else strategy['timeout']
        waiting = True
        while waiting and time.time() - start < timeout:
            if listener.game_state['inventory'] != inventory_before:
                waiting = False
            time.sleep(0.05)

        execution_time = time.time() - global_start
        if waiting:
            logger.warning(
                'Failed to get pack of items {} from bank in {}s'.format(
                    uids_to_transfer_all, execution_time))
            strategy['report'] = {
                'success': False,
                'details': {
                    'Execution time':
                    execution_time,
                    'Reason':
                    'Failed to get pack of items {} from bank in {}s'.format(
                        uids_to_transfer_all, execution_time)
                }
            }
            log.close_logger(logger)
            return strategy

    # Transfer specified
    for item in uids_to_transfer_specified:
        inventory_before = json.loads(
            json.dumps(listener.game_state['inventory']))
        order = {
            "command": "storage_to_inv",
            "parameters": {
                "item_uid": item['unique_id'],
                "quantity": item['quantity']
            }
        }
        logger.info('Sending order to bot API: {}'.format(order))
        orders_queue.put((json.dumps(order), ))

        start = time.time()
        timeout = 10 if 'timeout' not in strategy.keys(
        ) else strategy['timeout']
        waiting = True
        while waiting and time.time() - start < timeout:
            if listener.game_state['inventory'] != inventory_before:
                waiting = False
            time.sleep(0.05)

        execution_time = time.time() - global_start
        if waiting:
            logger.warning('Failed to get {} item {} from bank in {}s'.format(
                item['quantity'], item['unique_id'], execution_time))
            strategy['report'] = {
                'success': False,
                'details': {
                    'Execution time':
                    execution_time,
                    'Reason':
                    'Failed to get {} item {} from bank in {}s'.format(
                        item['quantity'], item['unique_id'], execution_time)
                }
            }
            log.close_logger(logger)
            return strategy

    logger.info(
        'Transferred from storage to inventory: {}'.format(transfer_recap))
    strategy['report'] = {
        'success': True,
        'details': {
            'Execution time': time.time() - global_start,
            'Transfer': transfer_recap
        }
    }
    log.close_logger(logger)
    return strategy
Esempio n. 26
0
def bank_enter(**kwargs):
    """
    A strategy to enter a bank

    :param kwargs: strategy, listener, and orders_queue
    :return: the input strategy with a report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']
    assets = kwargs['assets']

    logger = log.get_logger(__name__, strategy['bot'])

    global_start, start = time.time(), time.time()

    if listener.game_state['worldmap'] == -1:
        logger.info('Already inside bank (or at least underground) in {}s'.format(0))
        strategy['report'] = {
            'success': True,
            'details': {'Execution time': 0}
        }
        log.close_logger(logger)
        return strategy

    # Move the bot the appropriate cell to activate the zaap
    door_cell, element_id, skill_uid = None, None, None
    current_cell = listener.game_state['cell']
    current_map = listener.game_state['pos']
    for element in listener.game_state['map_elements']:
        if 'enabledSkills' in element.keys():
            for skill in element['enabledSkills']:
                if 'skillId' in skill.keys() and skill['skillId'] == 184:
                    element_id = element['elementId']
                    door_cell = assets['elements_info'][str(listener.game_state['map_id'])][str(element_id)]['cell']
                    skill_uid = skill['skillInstanceUid']

    if door_cell is None or element_id is None or skill_uid is None:
        strategy['report'] = {
            'success': False,
            'details': {'Execution time': time.time() - start,
                        'Reason': 'Could not find a Zaap at {}, map id : {}'.format(current_map, listener.game_state['map_id'])}
        }
        log.close_logger(logger)
        return strategy

    door_use_cell = strategies.support_functions.get_closest_walkable_neighbour_cell(assets['map_info'], door_cell, current_cell, current_map, listener.game_state['worldmap'])
    sub_strategy = strategies.move.move(
        listener=listener,
        strategy={'bot': strategy['bot'], 'parameters': {'cell': door_use_cell}},
        orders_queue=orders_queue,
        assets=assets
    )
    if not sub_strategy['report']['success']:
        strategy['report'] = {
            'success': False,
            'details': {'Execution time': time.time() - start, 'Reason': 'Move to get to door failed'}
        }
        log.close_logger(logger)
        return strategy

    order = {
        'command': 'use_interactive',
        'parameters': {
            'element_id': element_id,
            'skill_uid': skill_uid
        }
    }
    logger.info('Sending order to bot API: {}'.format(order))
    orders_queue.put((json.dumps(order),))

    start = time.time()
    timeout = 10 if 'timeout' not in strategy.keys() else strategy['timeout']
    waiting = True
    while waiting and time.time() - start < timeout:
        if listener.game_state['worldmap'] == -1:
            waiting = False
        time.sleep(0.05)
    execution_time = time.time() - start

    if waiting:
        logger.warn('Failed to open bank door in {}s'.format(execution_time))
        strategy['report'] = {
            'success': False,
            'details': {'Execution time': execution_time, 'Reason': 'Failed to open bank door in {}s'.format(execution_time)}
        }
        log.close_logger(logger)
        return strategy

    logger.info('Entered bank in {}s'.format(execution_time))

    execution_time = time.time() - global_start
    strategy['report'] = {
        'success': True,
        'details': {'Execution time': execution_time}
    }
    log.close_logger(logger)
    return strategy
def change_map(**kwargs):
    """
    A strategy make the bot move to an adjacent map.

    :param kwargs: strategy, listener, and orders_queue
    :return: the input strategy with a report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']
    assets = kwargs['assets']

    logger = log.get_logger(__name__, strategy['bot'])

    cell = strategy['parameters']['cell']
    direction = strategy['parameters']['direction']  # 'n', 's', 'w', 'e'

    global_start, start = time.time(), time.time()
    report = strategies.move.move(
        strategy={
            'bot': strategy['bot'],
            'command': 'move',
            'parameters': {
                'cell': cell
            }
        },
        listener=listener,
        assets=assets,
        orders_queue=orders_queue
    )['report']

    if not report['success']:
        strategy['report'] = {
            'success': False,
            'details': {'Execution time': time.time() - start, 'reason': 'Move failed'}
        }
        log.close_logger(logger)
        return strategy

    current_map_id = listener.game_state['map_id']
    current_pos = '{};{}'.format(listener.game_state['pos'][0], listener.game_state['pos'][1])
    map_data = strategies.support_functions.fetch_map(assets['map_info'], current_pos, listener.game_state['worldmap'])
    target_map_id = map_data['neighbours'][direction]
    order = {
        'command': 'change_map',
        'parameters': {
            'direction': strategy['parameters']['direction'],
            'target_map_id': target_map_id
        }
    }
    logger.info('Sending order to bot API: {}'.format(order))
    orders_queue.put((json.dumps(order),))

    start = time.time()
    timeout = 10 if 'timeout' not in strategy.keys() else strategy['timeout']
    waiting = True
    while waiting and time.time() - start < timeout:
        if 'pos' in listener.game_state.keys():
            if listener.game_state['map_id'] != current_map_id:
                waiting = False
        time.sleep(0.05)
    execution_time = time.time() - start

    if waiting:
        logger.warn('Failed changing map from {} through cell {} in {}s'.format(current_pos, cell, execution_time))
        strategy['report'] = {
            'success': False,
            'details': {'Execution time': execution_time, 'Reason': 'Timeout'}
        }
        log.close_logger(logger)
        return strategy

    logger.info('Changed map from {} through cell {} in {}s'.format(current_pos, cell, execution_time))
    strategy['report'] = {
        'success': True,
        'details': {'Execution time': execution_time}
    }
    log.close_logger(logger)
    time.sleep(0.5)
    return strategy
def path_ten(**kwargs):
    """
    Walks around to get to level ten by earning successes

    :param kwargs:
    :return: report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']
    assets = kwargs['assets']

    logger = log.get_logger(__name__, strategy['bot'])
    start, global_start = time.time(), time.time()
    if listener.game_state['level'] >= 10:
        logger.info('Bot is already at least level 10')
        strategy['report'] = {
            'success': True,
            'details': {
                'Execution time': time.time() - global_start
            }
        }
        log.close_logger(logger)
        return strategy

    path = [
        {
            'pos': [-2, -4],
            'worldmap': 2
        },
        {
            'pos': [-2, -2],
            'worldmap': 2
        },
        {
            'pos': [1, -2],
            'worldmap': 2
        },
        {
            'pos': [1, -4],
            'worldmap': 2
        },
        {
            'pos': [2, -14]
        },
        {
            'pos': [3, -14]
        },
        {
            'pos': [8, -15]
        },
        {
            'pos': [9, -25]
        },
        {
            'pos': [3, -32]
        },
        {
            'pos': [2, -27]
        },
        {
            'pos': [-3, -28]
        },
        {
            'pos': [-6, -29]
        },
        {
            'pos': [-5, -36]
        },
        {
            'pos': [-5, -47]
        },
        {
            'pos': [-8, -54]
        },
        {
            'pos': [-9, -54]
        },
        {
            'pos': [-15, -54]
        },
        {
            'pos': [-19, -56]
        },
        {
            'pos': [-19, -57]
        },
        {
            'pos': [-24, -62]
        },
        {
            'pos': [-28, -63]
        },
        {
            'pos': [-29, -60]
        },
        {
            'pos': [-27, -59]
        },
        {
            'pos': [-27, -55]
        },
        {
            'pos': [-27, -51]
        },
        {
            'pos': [-29, -53]
        },
        {
            'pos': [-30, -58]
        },
        {
            'pos': [-34, -53]
        },
        {
            'pos': [-34, -52]
        },
        {
            'pos': [-35, -52]
        },
        {
            'pos': [-35, -54]
        },
        {
            'pos': [-34, -59]
        },
        {
            'pos': [-29, -47]
        },
        {
            'pos': [-27, -34]
        },
        {
            'pos': [-25, -11]
        },
        {
            'pos': [-16, -3]
        },
        {
            'pos': [-18, -1]
        },
        {
            'pos': [-22, -1]
        },
        {
            'pos': [-24, 14]
        },
        {
            'pos': [-19, 23]
        },
        {
            'pos': [-22, 28]
        },
        {
            'pos': [-22, 29]
        },
        {
            'pos': [-27, 41]
        },
        {
            'pos': [-26, 40]
        },
        {
            'pos': [-24, 40]
        },
        {
            'pos': [-22, 40]
        },
        {
            'pos': [-20, 40]
        },
        {
            'pos': [-22, 37]
        },
        {
            'pos': [-24, 37]
        },
        {
            'pos': [-28, 37]
        },
        {
            'pos': [-29, 37]
        },
        {
            'pos': [-29, 34]
        },
        {
            'pos': [-27, 33]
        },
        {
            'pos': [-26, 33]
        },
    ]
    for pos in path:
        sub_strategy = strategies.goto.goto(
            assets=assets,
            orders_queue=orders_queue,
            listener=listener,
            strategy={
                'bot': strategy['bot'],
                'parameters': {
                    'x': pos['pos'][0],
                    'y': pos['pos'][1],
                    'worldmap':
                    pos['worldmap'] if 'worldmap' in pos.keys() else 1
                }
            })
        if not sub_strategy['report']['success']:
            strategy['report'] = {
                'success': False,
                'details': {
                    'Execution time': time.time() - start,
                    'Reason': sub_strategy['report']
                }
            }
            log.close_logger(logger)
            return strategy

        sub_strategy = strategies.achievement_reward.achievement_reward(
            assets=assets,
            orders_queue=orders_queue,
            listener=listener,
            strategy={'bot': strategy['bot']})
        if not sub_strategy['report']['success']:
            strategy['report'] = {
                'success': False,
                'details': {
                    'Execution time': time.time() - start,
                    'Reason': sub_strategy['report']
                }
            }
            log.close_logger(logger)
            return strategy
    time.sleep(2)
    sub_strategy = strategies.achievement_reward.achievement_reward(
        assets=assets,
        orders_queue=orders_queue,
        listener=listener,
        strategy={'bot': strategy['bot']})
    if not sub_strategy['report']['success']:
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': time.time() - start,
                'Reason': sub_strategy['report']
            }
        }
        log.close_logger(logger)
        return strategy

    logger.info('Finished walking path 10 in {}s'.format(time.time() -
                                                         global_start))
    strategy['report'] = {
        'success': True,
        'details': {
            'Execution time': time.time() - global_start
        }
    }
    log.close_logger(logger)
    return strategy
Esempio n. 29
0
def bank_get_kamas(**kwargs):
    """
    A strategy to get kamas from the bank

    :param kwargs: strategy, listener, and orders_queue
    :return: the input strategy with a report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']
    assets = kwargs['assets']

    logger = log.get_logger(__name__, strategy['bot'])

    global_start, start = time.time(), time.time()

    kamas_to_transfer = 'all'
    if 'parameters' in strategy.keys() and 'quantity' in strategy['parameters'].keys() and strategy['parameters']['quantity'] is not None:
        kamas_to_transfer = strategy['parameters']['quantity']

    if not listener.game_state['storage_open']:
        logger.warning('Bank is not open')
        strategy['report'] = {
            'success': False,
            'details': {'Execution time': 0, 'Reason': 'Bank is not open'}
        }
        log.close_logger(logger)
        return strategy

    kamas_in_storage = listener.game_state['storage_content']['kamas']
    kamas_to_transfer = kamas_in_storage if kamas_to_transfer == 'all' else kamas_to_transfer

    if kamas_to_transfer > kamas_in_storage:
        logger.warning('Cannot get {} kamas from bank, only {} are available'.format(kamas_to_transfer, kamas_in_storage))
        strategy['report'] = {
            'success': False,
            'details': {'Execution time': time.time() - global_start, 'Reason': 'Cannot get {} kamas from bank, only {} are available'.format(kamas_to_transfer, kamas_in_storage)}
        }
        log.close_logger(logger)
        return strategy

    if kamas_to_transfer == 0:
        logger.info('No kamas to transfer')
        strategy['report'] = {
            'success': True,
            'details': {'Execution time': time.time() - global_start}
        }
        log.close_logger(logger)
        return strategy

    kamas_before = listener.game_state['kamas']

    order = {
        "command": "move_kamas",
        "parameters": {
            "quantity": -kamas_to_transfer
        }
    }
    logger.info('Sending order to bot API: {}'.format(order))
    orders_queue.put((json.dumps(order),))

    start = time.time()
    timeout = 10 if 'timeout' not in strategy.keys() else strategy['timeout']
    waiting = True
    while waiting and time.time() - start < timeout:
        if 'kamas' in listener.game_state.keys():
            if listener.game_state['kamas'] != kamas_before:
                waiting = False
        time.sleep(0.05)

    execution_time = time.time() - global_start
    if waiting:
        logger.warning('Failed to get {} kamas from bank in {}s'.format(kamas_to_transfer, execution_time))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': execution_time,
                'Reason': 'Failed to get {} from bank in {}s'.format(kamas_to_transfer, execution_time)
            }
        }
        log.close_logger(logger)
        return strategy

    logger.info('{} kamas transferred from bank to inventory'.format(kamas_to_transfer))
    strategy['report'] = {
        'success': True,
        'details': {'Execution time': time.time() - global_start}
    }
    log.close_logger(logger)
    return strategy
def auctionh_sell(**kwargs):
    """
    Sells items at this map's auction house

    :param kwargs:
    :return: report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']
    assets = kwargs['assets']

    logger = log.get_logger(__name__, strategy['bot'])
    start, global_start = time.time(), time.time()

    # Establish the list of stuff to sell
    stuff_to_sell = {}
    for item in strategy['parameters']['items']:

        # If both a general and unique id are given
        if 'general_id' in item.keys() and item['general_id'] is not None and \
                'unique_id' in item.keys() and item['unique_id'] is not None:
            strategy['report'] = {
                'success': False,
                'details': {
                    'Execution time':
                    time.time() - start,
                    'Reason':
                    'General id and unique id can not both be specified for an item'
                }
            }
            log.close_logger(logger)
            return strategy

        # If a general id is given
        if 'general_id' in item.keys() and item['general_id'] is not None:
            for inventory_item in listener.game_state['inventory']:
                if inventory_item['objectGID'] == item[
                        'general_id'] and inventory_item['position'] == 63:
                    item['name'] = assets['id_2_names'][str(
                        inventory_item['objectGID'])]
                    item['type'] = assets['id_2_type'][str(
                        inventory_item['objectGID'])]
                    item['level'] = assets['id_2_level'][str(
                        inventory_item['objectGID'])]
                    stuff_to_sell[inventory_item['objectUID']] = item

        # If a unique is is given
        if 'unique_id' in item.keys() and item['unique_id'] is not None:
            found = False
            for inventory_item in listener.game_state['inventory']:
                if inventory_item['objectUID'] == item['unique_id']:
                    if inventory_item['position'] != 63:
                        logger.warning(
                            'Item is currently worn and cannot be sold')
                        strategy['report'] = {
                            'success': False,
                            'details': {
                                'Execution time':
                                time.time() - start,
                                'Reason':
                                'Item is currently worn and cannot be sold'
                            }
                        }
                        log.close_logger(logger)
                        return strategy

                    found = True
                    item['name'] = assets['id_2_names'][str(
                        inventory_item['objectGID'])]
                    item['type'] = assets['id_2_type'][str(
                        inventory_item['objectGID'])]
                    item['level'] = assets['id_2_level'][str(
                        inventory_item['objectGID'])]
                    item['general_id'] = inventory_item['objectGID']
                    stuff_to_sell[inventory_item['objectUID']] = item

            if not found:
                logger.warning(
                    'Item specified by unique id could not be found in inventory'
                )
                strategy['report'] = {
                    'success': False,
                    'details': {
                        'Execution time':
                        time.time() - start,
                        'Reason':
                        'Item specified by unique id could not be found in inventory'
                    }
                }
                log.close_logger(logger)
                return strategy

    # Check quantities
    for uid, item in stuff_to_sell.items():
        if 'quantity' not in item.keys() or item['quantity'] is None:
            item['quantity'] = 'all'

        available_in_inv = 0
        for inventory_item in listener.game_state['inventory']:
            if inventory_item['objectUID'] == uid:
                available_in_inv = inventory_item['quantity']
                break

        if item['quantity'] == 'all':
            item['quantity'] = available_in_inv // item['pack_size']
        elif item['quantity'] * item['pack_size'] > available_in_inv:
            logger.warning(
                'Not enough {}/{}. Requested {}, available {}'.format(
                    uid, item['name'], item['quantity'] * item['pack_size'],
                    available_in_inv))
            strategy['report'] = {
                'success': False,
                'details': {
                    'Execution time':
                    time.time() - start,
                    'Reason':
                    'Not enough {}/{}. Requested {}, available {}'.format(
                        uid, item['name'],
                        item['quantity'] * item['pack_size'], available_in_inv)
                }
            }
            log.close_logger(logger)
            return strategy

    # Fill prices
    prices_to_check = []
    for uid, item in stuff_to_sell.items():
        if 'price' not in item.keys() or item['quantity'] is None:
            prices_to_check.append(item['general_id'])

    if len(prices_to_check):
        sub_strategy = strategies.auctionh_get_prices.auctionh_get_prices(
            assets=assets,
            orders_queue=orders_queue,
            listener=listener,
            strategy={
                'bot': strategy['bot'],
                'parameters': {
                    'general_ids_list': prices_to_check
                }
            })
        if not sub_strategy['report']['success']:
            strategy['report'] = {
                'success': False,
                'details': {
                    'Execution time': time.time() - start,
                    'Reason': sub_strategy['report']
                }
            }
            log.close_logger(logger)
            return strategy

        for gid, item in sub_strategy['report']['details']['Results'].items():
            gid = int(gid)
            for uid, item_to_sell in stuff_to_sell.items():
                if gid == item_to_sell[
                        'general_id'] and 'price' not in item_to_sell.keys():
                    item_to_sell['price'] = item['items_stats'][0]['prices'][[
                        1, 10, 100
                    ].index(item_to_sell['pack_size'])] - 1

    # Check that the bot has enough money to sell
    total_fee = 0
    for uid, item in stuff_to_sell.items():
        total_fee += math.ceil(item['price'] * item['quantity'] * 0.02)
    if total_fee > listener.game_state['kamas']:
        logger.warning(
            'Not enough money to sell items. Needed: {}, available: {}. Items to sell: {}'
            .format(total_fee, listener.game_state['kamas'], stuff_to_sell))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time':
                time.time() - start,
                'Reason':
                'Item specified by unique id could not be found in inventory'
            }
        }
        log.close_logger(logger)
        return strategy

    # Open the auction house if it is closed.
    if not listener.game_state[
            'auction_house_info'] or 'sellerDescriptor' not in listener.game_state[
                'auction_house_info'].keys():
        sub_strategy = strategies.auctionh_open.auctionh_open(
            listener=listener,
            orders_queue=orders_queue,
            assets=assets,
            strategy={
                "bot": strategy['bot'],
                "parameters": {
                    "mode": "sell"
                }
            })
        if not sub_strategy['report']['success']:
            strategy['report'] = {
                'success': False,
                'details': {
                    'Execution time': time.time() - start,
                    'Reason': sub_strategy['report']
                }
            }
            log.close_logger(logger)
            return strategy

    # Check that the hdv has the level to sell these items
    for uid, item in stuff_to_sell.items():
        if item['level'] > listener.game_state['auction_house_info'][
                'sellerDescriptor']['maxItemLevel']:
            logger.warning(
                'Item {}/() is too high level for the {} auction house. Item level: {}, auction house max: {}'
                .format(
                    item['general_id'], item['name'],
                    listener.game_state['pos'], item['level'],
                    listener.game_state['auction_house_info']
                    ['sellerDescriptor']['maxItemLevel']))
            strategy['report'] = {
                'success': False,
                'details': {
                    'Execution time':
                    time.time() - start,
                    'Reason':
                    'Item {}/() is too high level for the {} auction house. Item level: {}, auction house max: {}'
                    .format(
                        item['general_id'], item['name'],
                        listener.game_state['pos'], item['level'],
                        listener.game_state['auction_house_info']
                        ['sellerDescriptor']['maxItemLevel'])
                }
            }
            log.close_logger(logger)
            return strategy

    # Check that the hdv can sell these items
    # TODO: test
    for uid, item in stuff_to_sell.items():
        if item['type'] not in listener.game_state['auction_house_info'][
                'sellerDescriptor']['types']:
            logger.warning(
                'Type {} can not be sold at the {} auction house'.format(
                    item['type'], listener.game_state['pos']))
            strategy['report'] = {
                'success': False,
                'details': {
                    'Execution time':
                    time.time() - start,
                    'Reason':
                    'Type {} can not be sold at the {} auction house'.format(
                        item['type'], listener.game_state['pos'])
                }
            }
            log.close_logger(logger)
            return strategy

    # Check that the bot has enough slots available
    # TODO: test
    total_slots_needed = 0
    for uid, item in stuff_to_sell.items():
        total_slots_needed += item['quantity']

    available_slots = listener.game_state['auction_house_info'][
        'sellerDescriptor']['maxItemPerAccount'] - len(
            listener.game_state['auction_house_info']['objectsInfos'])
    if total_slots_needed > available_slots:
        logger.warning(
            'Not enough slots available to sell items. Needed: {}, available: {}. Items to sell: {}'
            .format(total_slots_needed, available_slots, stuff_to_sell))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time':
                time.time() - start,
                'Reason':
                'Not enough slots available to sell items. Needed: {}, available: {}. Items to sell: {}'
                .format(total_slots_needed, available_slots, stuff_to_sell)
            }
        }
        log.close_logger(logger)
        return strategy

    # Sell stuff
    stuff_sold = {}
    for uid, item in stuff_to_sell.items():
        for _ in range(item['quantity']):
            previous_item_quantity = None
            for inv_item in listener.game_state['inventory']:
                if inv_item['objectGID'] == item['general_id']:
                    previous_item_quantity = inv_item['quantity']
            order = {
                'command': 'auctionh_sell_item',
                'parameters': {
                    'unique_id': uid,
                    'quantity': item['pack_size'],
                    'price': item['price']
                }
            }
            logger.info('Sending order to bot API: {}'.format(order))
            orders_queue.put((json.dumps(order), ))

            start = time.time()
            timeout = 10 if 'timeout' not in strategy.keys(
            ) else strategy['timeout']
            waiting = True
            while waiting and time.time() - start < timeout:
                item_quantity = None
                for inv_item in listener.game_state['inventory']:
                    if inv_item['objectGID'] == item['general_id']:
                        item_quantity = inv_item['quantity']
                if item_quantity != previous_item_quantity:
                    waiting = False
                time.sleep(0.05)
            execution_time = time.time() - start

            if waiting:
                logger.warning(
                    'Failed to sell {}/{}, quantity: {}, price: {}'.format(
                        item['general_id'], item['name'], item['pack_size'],
                        item['price']))
                strategy['report'] = {
                    'success': False,
                    'details': {
                        'Execution time':
                        execution_time,
                        'Reason':
                        'Failed to sell {}:/}, quantity: {}, price: {}'.format(
                            item['general_id'], item['name'],
                            item['pack_size'], item['price'])
                    }
                }
                log.close_logger(logger)
                return strategy
            logger.info('Sold {}/{}, quantity: {}, price: {}'.format(
                item['general_id'], item['name'], item['pack_size'],
                item['price']))
            if uid in stuff_sold.keys():
                stuff_sold[uid]['quantity'] += item['pack_size']
                stuff_sold[uid]['total_price'] += item['price']
            else:
                stuff_sold[uid] = {
                    'name': item['name'],
                    'general_id': item['general_id'],
                    'quantity': item['pack_size'],
                    'total_price': item['price']
                }

    # Close auction house
    sub_strategy = strategies.auctionh_close.auctionh_close(
        listener=listener,
        orders_queue=orders_queue,
        assets=assets,
        strategy={
            "bot": strategy['bot'],
        })
    if not sub_strategy['report']['success']:
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': time.time() - start,
                'Reason': sub_strategy['report']
            }
        }
        log.close_logger(logger)
        return strategy

    strategy['report'] = {
        'success': True,
        'details': {
            'Execution time': time.time() - global_start,
            'sold': stuff_sold
        }
    }

    log.close_logger(logger)
    return strategy
Esempio n. 31
0
def use_zaap(**kwargs):
    """
    Uses a zaap to get to a specified destination
    The bot must be on a map with a zaap
    This strategy will move the bot to an appropriate cell to use the zaap

    :param kwargs:
    :return: report
    """
    strategy = kwargs['strategy']
    listener = kwargs['listener']
    orders_queue = kwargs['orders_queue']
    assets = kwargs['assets']

    logger = log.get_logger(__name__, strategy['bot'])
    start, global_start = time.time(), time.time()

    # Move the bot the appropriate cell to activate the zaap
    zaap_cell, element_id, skill_uid = None, None, None
    current_cell = listener.game_state['cell']
    current_map = listener.game_state['pos']
    for element in listener.game_state['map_elements']:
        if 'enabledSkills' in element.keys():
            for skill in element['enabledSkills']:
                if 'skillId' in skill.keys() and skill['skillId'] == 114:
                    element_id = element['elementId']
                    zaap_cell = assets['elements_info'][str(
                        listener.game_state['map_id'])][str(
                            element_id)]['cell']
                    skill_uid = skill['skillInstanceUid']

    if zaap_cell is None or element_id is None or skill_uid is None:
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time':
                time.time() - start,
                'Reason':
                'Could not find a Zaap at {}, map id : {}'.format(
                    current_map, listener.game_state['map_id'])
            }
        }
        log.close_logger(logger)
        return strategy

    if not listener.game_state['in_haven_bag']:
        zaap_use_cell = strategies.support_functions.get_closest_walkable_neighbour_cell(
            assets['map_info'], zaap_cell, current_cell, current_map,
            listener.game_state['worldmap'])
        sub_strategy = strategies.move.move(listener=listener,
                                            strategy={
                                                'bot': strategy['bot'],
                                                'parameters': {
                                                    'cell': zaap_use_cell
                                                }
                                            },
                                            orders_queue=orders_queue,
                                            assets=assets)
        if not sub_strategy['report']['success']:
            strategy['report'] = {
                'success': False,
                'details': {
                    'Execution time': time.time() - start,
                    'Reason': 'Move to get to zaap failed'
                }
            }
            log.close_logger(logger)
            return strategy

    order = {
        'command': 'use_interactive',
        'parameters': {
            'element_id': element_id,
            'skill_uid': skill_uid
        }
    }
    logger.info('Sending order to bot API: {}'.format(order))
    orders_queue.put((json.dumps(order), ))

    start = time.time()
    timeout = 10 if 'timeout' not in strategy.keys() else strategy['timeout']
    waiting = True
    while waiting and time.time() - start < timeout:
        if listener.game_state['zaap_dialog_open']:
            waiting = False
        time.sleep(0.05)
    execution_time = time.time() - start

    if waiting:
        logger.warn('Failed to open zaap menu in {}s'.format(execution_time))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': execution_time,
                'Reason': 'Timeout when opening zaap menu'
            }
        }
        log.close_logger(logger)
        return strategy

    logger.info('Opened zaap menu in {}s'.format(execution_time))

    target_map_id = int(
        strategies.support_functions.fetch_map(
            assets['map_info'],
            coord='{};{}'.format(strategy['parameters']['destination_x'],
                                 strategy['parameters']['destination_y']),
            worldmap=1)['id'])
    selected_destination = None
    for destination in listener.game_state['zaap_destinations']:
        if destination['mapId'] == target_map_id:
            selected_destination = destination

    if selected_destination is None:
        logger.warn('Zaap at destination [{},{}] is not known'.format(
            strategy['parameters']['destination_x'],
            strategy['parameters']['destination_y']))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time':
                execution_time,
                'Reason':
                'Zaap at destination [{},{}] is not known'.format(
                    strategy['parameters']['destination_x'],
                    strategy['parameters']['destination_y'])
            }
        }
        log.close_logger(logger)
        return strategy

    if selected_destination['cost'] > listener.game_state['kamas']:
        logger.warn(
            'Not enough money to use zaap: needed {}, available: {}'.format(
                selected_destination['cost'], listener.game_state['kamas']))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time':
                execution_time,
                'Reason':
                'Not enough money to use zaap: needed {}, available: {}'.
                format(selected_destination['cost'],
                       listener.game_state['kamas'])
            }
        }
        log.close_logger(logger)
        return strategy

    order = {
        'command': 'travel_by_zaap',
        'parameters': {
            'target_map_id': selected_destination['mapId']
        }
    }
    logger.info('Sending order to bot API: {}'.format(json.dumps(order)))
    orders_queue.put((json.dumps(order), ))

    waiting = True
    while waiting and time.time() - start < timeout:
        if 'pos' in listener.game_state.keys(
        ) and 'worldmap' in listener.game_state.keys():
            if listener.game_state['map_id'] == selected_destination['mapId']:
                waiting = False
        time.sleep(0.05)
    execution_time = time.time() - start

    if waiting:
        logger.warn('Failed to use zaap in {}s'.format(execution_time))
        strategy['report'] = {
            'success': False,
            'details': {
                'Execution time': execution_time,
                'Reason': 'Teleport by zaap failed'
            }
        }
        log.close_logger(logger)
        return strategy

    strategy['report'] = {
        'success': True,
        'details': {
            'Execution time': execution_time
        }
    }

    log.close_logger(logger)
    return strategy