Ejemplo n.º 1
0
 def test_continent_status(self):
     assert command_handler_setup.serve(
         "!continentstatus emerald") != change_color(
             "Invalid server name.", ColorCodes.RED)
     assert command_handler_setup.serve(
         "!continentstatus foo") == change_color("Invalid servername: foo",
                                                 ColorCodes.RED)
Ejemplo n.º 2
0
    def test_player_stats(self):
        assert command_handler_setup.serve("!playerstats hiimnotreal") != \
            change_color("Could not retrieve player information.", ColorCodes.RED)

        assert command_handler_setup.serve("!playerstats Mentis2k6") != \
            change_color("Could not retrieve player information.", ColorCodes.RED)

        assert command_handler_setup.serve("!playerstats IHacksXVS") != \
            change_color("Could not retrieve player information.", ColorCodes.RED)
Ejemplo n.º 3
0
def gizoogle(text):
    """
    Take a string and 'gizoogle' it, then return the result.

    If the function fails to do so, then an error message is returned.

    :param text: The string to be gizoogled.
    :return: If successful, then return the result.
    """
    url = 'http://www.gizoogle.net/textilizer.php'

    html = requests.post(url, data={'translatetext': text}).text
    try:
        return str(
            BeautifulSoup(html, "html5lib").textarea.contents[0].strip())
    except (AttributeError, requests.ConnectionError) as e:
        logging.error("Failed to receive gizoogled text: %r" % e)
        return change_color("Failed to grab gizoogled text.", ColorCodes.RED)
    except TypeError:
        return change_color("Word must be a valid string.", ColorCodes.RED)
Ejemplo n.º 4
0
def dictionary_define(word, def_num):
    """
    Grabs the definition of a word from the owlbot.info site.
    :param word: The word to be searched for.
    :param def_num: If multiple definitions are found, then this is the number indicating which to grab.
    :return: If a word doesn't exist, then it defaults to "Failed to grab definition." Otherwise, it returns
    the definition.
    """
    try:
        r = requests.get("https://owlbot.info/api/v1/dictionary/%s" % quote(word, safe=''))
        data = r.json()
        definition = data[int(def_num)].get("defenition")
        return "Got definition for %s: %s" % (change_style(str(word), StyleCodes.BOLD), str(definition))

    except (IndexError, requests.ConnectionError) as e:
        logging.error("Failed to grab Owl Dictionary definition for word %s, exception info: %r" % (word, e))
        return change_color("Failed to grab definition.", ColorCodes.RED)
    except TypeError:
        return change_color("Word must be a valid string.", ColorCodes.RED)
    except ValueError:
        return change_color("Definition number must be a valid int.", ColorCodes.RED)
Ejemplo n.º 5
0
def define_word(word):
    """
    Attempt to grab the first definition of a given word from the Urban Dictionary site.
    :param word: The word to look up.
    :return: Upon success, return the definition of the word. If the definition was not found, the resulting
    index_error exception is caught and an error message is returned.
    """
    r = requests.get("http://api.urbandictionary.com/v0/define?term=%s)" %
                     quote(word, safe=''))
    data = r.json()

    try:
        definition = data['list'][0]['definition']
        return "Got definition for %s: %s" % (change_style(
            str(word), StyleCodes.BOLD), str(definition))
    except (IndexError, requests.ConnectionError) as e:
        logging.error(
            "Failed to grab Urban Dictionary definition for word %s, exception info: %r"
            % (word, e))
        return change_color("Failed to grab definition.", ColorCodes.RED)
    except TypeError:
        return change_color("Word must be a valid string.", ColorCodes.RED)
Ejemplo n.º 6
0
def grab_player_stats(player_name, api_key):
    """
    Attempt to grab a specified player's battlerank, faction, certs, kill/death count and KDR.

    The api key is retrieved from the Servo.ini file. If it is invalid, then the function simply
    returns its usual error message.

    :param player_name: This is the player to search for. If the player is not found, then this usually results in an
    indexerror/keyerror. ZeroDivisionErrors occur when a player is outdated and has no kills/deaths in the census db.

    :return: Return a formatted string containing the discovered information.

    """

    factionids_dict = {1: "VS", 2: "NC", 3: "TR"}
    try:
        data = requests.get(
            "http://census.daybreakgames.com/s:" + api_key +
            "/get/ps2:v2/character/?name.first_lower=" + player_name.lower() +
            "&c:resolve=stat_history&c:resolve=world&c:join=world^on:world_id^to:"
            "world_id^inject_at:world_id").json()
        census_char = data['character_list'][0]
        char_br = str(census_char['battle_rank']['value'])
        char_faction = str(
            factionids_dict.get(int(census_char['faction_id'][0])))
        char_certs = str(census_char['certs']['available_points'])
        char_kills = str(census_char['stats']['stat_history'][5]['all_time'])
        char_deaths = str(census_char['stats']['stat_history'][2]['all_time'])
        char_kd = round(int(char_kills) / int(char_deaths), 2)
        return "Got stats for %s - battlerank: %s, faction: %s, certcount: %s, kills: %s, deaths: %s, KD: %s" % \
               (change_style(player_name, StyleCodes.BOLD), char_br, char_faction, char_certs,
                char_kills, char_deaths, char_kd)
    except (IndexError, ZeroDivisionError, KeyError,
            requests.ConnectionError) as e:
        logging.error(
            "Failed to grab Planetside 2 player %s's info. Exception info: %r"
            % (player_name, e))
        return change_color("Could not retrieve player information.",
                            ColorCodes.RED)
Ejemplo n.º 7
0
def grab_server_status(server_name):
    name_arg = str(server_name).lower()
    if name_arg not in server_ids:
        return change_color("Error: That server does not exist.",
                            ColorCodes.RED)

    r = requests.get("http://www.planetside-universe.com/server_status.php")
    rp = requests.get("http://ps2.fisu.pw/api/population/?world=%s" %
                      server_ids.get(name_arg))

    if rp.status_code != 200:
        logging.error(
            "Error - Failed to grab population status. Status code: %s" %
            str(rp.status_code))
        return change_color("Error: Failed to retrieve population statistics.",
                            ColorCodes.RED)

    if r.status_code != 200:
        logging.error(
            "Error - Failed to grab population status. Status code: %s" %
            str(rp.status_code))
        return change_color("Error: Server returned %s" % r.status_code,
                            ColorCodes.RED)

    rp = rp.json()

    vs_population = rp['result'][0]['vs']
    tr_population = rp['result'][0]['tr']
    nc_population = rp['result'][0]['nc']
    total_population = str(
        int(vs_population) + int(tr_population) + int(nc_population))

    rc = r.content

    data = []
    table = BeautifulSoup(rc).find('table', attrs={'id': 'servers'})
    table_body = table.find('tbody')

    for row in table_body.findAll("tr"):
        cells = row.findAll("td")
        cells = [ele.text.strip() for ele in cells]
        data.append([ele for ele in cells if ele])

    status = ""
    for i in data:
        if i[1] == name_arg.title():
            if i[3] != 'Up':
                status = "'%s' is down." % change_style(i[1], StyleCodes.BOLD)
            else:
                status = "%s is online with a total population of %s --- %s, %s, and %s." \
                         % (change_style(i[1], StyleCodes.BOLD),
                            change_color(total_population, ColorCodes.GREEN),
                            change_color(str(vs_population) + " VS", ColorCodes.PURPLE),
                            change_color(str(tr_population) + " TR", ColorCodes.RED),
                            change_color(str(nc_population) + " NC", ColorCodes.TEAL))
        else:
            status = change_color(
                "Error: failed to get proper result. Try again?",
                ColorCodes.RED)  # bad

    return status
Ejemplo n.º 8
0
 def test_urbandictionary(self):
     assert command_handler_setup.serve("!ud test") == "Got definition for %s: A process for testing things" % \
            change_style("test", StyleCodes.BOLD)
     assert command_handler_setup.serve(
         "!ud ijaderogaejoiy") == change_color("Failed to grab definition.",
                                               ColorCodes.RED)
Ejemplo n.º 9
0
 def test_color(string, color):
     return change_color(string, color)
Ejemplo n.º 10
0
def grab_continent_info(server_name, api_key):
    """
    Attempt to grab information pertaining to which faction has locked which continents on a given server.

    server_name is searched for in the server_ids, and if it is found, then the id of the server is retrieved,
    otherwise, an error message is returned notifying the user the server doesn't exist.

    api_key is the Daybreak games API key retrieved from the Servo.ini. If it's an invalid API key, then the
    function will just return its usual error message.

    :param server_name: The server to grab continent information from.
    :param api_key: The api key to be supplied to the api.
    :return: Upon success, a formatted string containing the locked/unlocked continents is returned. Otherwise,
    return an error message.
    """

    server_ids = {
        "Emerald": "17",
        "Connery": "1",
        "Briggs": "25",
        "Cobalt": "13",
        "Miller": "10"
    }

    faction_ids = {
        1: change_color("VS", ColorCodes.PURPLE),
        2: change_color("NC", ColorCodes.BLUE),
        3: change_color("TR", ColorCodes.RED)
    }

    continent_ids = {
        "Amerish": [6, 0, 1],
        "Esamir": [8, 28, 29],
        "Indar": [2, 9, 10],
        "Hossin": [4, 73, 74]
    }

    server = server_name[0].upper() + server_name[1:].lower()
    if server not in server_ids:
        return change_color("Invalid servername: %s" % server_name, ColorCodes.RED)
    server_id = server_ids.get(server)

    def continent_statuses():
        """
        For the continents on the server, loop through each of them, getting the faction ids of the controlling
        faction of two warpgates. Then, in order to test if the continent is locked, compare the two warpgates
        against each other. If they are both owned by the same faction, then it's locked by that faction.

        Otherwise, it's unlocked.

        Either way, concatenate the status to the continent statuses list, and after looping through the
        continents, join the statuses into a string and return it.

        :return: Return the string that was concatenated from the continent statuses list.
        """
        continent_status_results = []

        for continent_name, continent_values in continent_ids.items():
            continent_data = requests.get(
                "http://census.daybreakgames.com/s:" + api_key + "/get/ps2:v2/map/?world_id=" + server_id + "&zone_ids=" +
                str(continent_values[0])).json()

            continent_map = continent_data['map_list'][0]['Regions']['Row']

            warpgate1_controlling_faction = continent_map[continent_values[1]]['RowData']['FactionId']
            warpgate2_controlling_faction = continent_map[continent_values[2]]['RowData']['FactionId']

            if warpgate1_controlling_faction != warpgate2_controlling_faction:
                continent_status_results.append("%s is unlocked" % change_style(continent_name, StyleCodes.BOLD))
            else:
                continent_status_results.append("%s was locked by the %s" %
                                                (change_style(continent_name, StyleCodes.BOLD),
                                                 faction_ids.get(int(warpgate1_controlling_faction))))

        continent_status_results.insert(3, "and")
        return ', '.join(continent_status_results).replace("and,", "and")

    try:
        return "On %s: %s." % (change_style(server, StyleCodes.BOLD), continent_statuses())
    except (KeyError, requests.ConnectionError) as e:
        logging.error("Failed to return Planetside 2 continent info for server: %s. Exception: %r" % (server_name, e))
        return change_color("Could not retrieve continent information.", ColorCodes.RED)