Exemple #1
0
 async def res(self):
     destiny = pydest.Pydest(api_key)
     group = await destiny.api.get_groups_for_member(1, self._membership_id)
     group_id = group['Response']['results'][0]['member']['groupId']
     r = await destiny.api.get_members_of_group(group_id)
     await destiny.close()
     return r
Exemple #2
0
async def main():
    """You will need to add your api key!"""
    destiny = pydest.Pydest('0ec20be77ac249838fa84fd6fc1806df')

    platform = 3
    while not platform:
        user_input = input('Enter your platform (xbox, playstation, or pc): ')
        if user_input.upper() in platforms.keys():
            platform = platforms.get(user_input.upper())
        else:
            print('Invalid platform.')

    username = input('Enter the username to locate: ')
    res = await destiny.api.search_destiny_player(platform, username)

    if res['ErrorCode'] == 1 and len(res['Response']) > 0:
        print("---")
        print("Player found!")
        print(res)
        for result in res['Response']:
            print("Display Name: {}".format(res['Response'][0]['displayName']))
            print("Membership ID: {}".format(
                res['Response'][0]['membershipId']))
    else:
        print("Could not locate player.")

    await destiny.close()
Exemple #3
0
 async def res(self):
     destiny = pydest.Pydest(api_key)
     r = await destiny.api.get_item(self._membership_type,
                                    self._membership_id, '1048266744',
                                    ['ItemCommonData'])
     await destiny.close()
     return r
Exemple #4
0
    def __init__(self, *args, **kwargs):
        self.description = 'To be continued'

        # Configs & token
        with open('config.json') as f:
            self.config = json.load(f)

        super().__init__(command_prefix=commands.when_mentioned,
                         description=self.description,
                         pm_help=None,
                         *args,
                         **kwargs)

        # Startup extensions (none yet)
        self.startup_ext = [x.stem for x in Path('cogs').glob('*.py')]

        # aiohttp session
        self.session = aiohttp.ClientSession(loop=self.loop)

        # Make room for the help command
        self.remove_command('help')

        # Embed color
        self.user_color = 0x781D1D
        self.pyd = pydest.Pydest(self.config['key'])
        self.fapp_proc = Process(target=run)
        self.easy_access = {}
Exemple #5
0
 async def res(self):
     destiny = pydest.Pydest(api_key)
     r = await destiny.api.get_activity_history(self._membership_type,
                                                self._membership_id, 0, 1,
                                                None, 0)
     await destiny.close()
     return r
Exemple #6
0
 async def res(self):
     destiny = pydest.Pydest(api_key)
     res = await destiny.api.get_groups_for_member(self._membership_type,
                                                   self._membership_id)
     group_id = res['Response']['results'][0]['member']['groupId']
     r = await destiny.api.get_clan_weekly_reward_state(group_id)
     await destiny.close()
     return r
async def initialize_destiny():
    destiny = pydest.Pydest(BUNGIE_KEY)

    await destiny.update_manifest()

    logger.info("Initialized Pydest")

    return destiny
Exemple #8
0
 def __init__(self, token, bungie_api_key, bungie_client_id):
     super().__init__(command_prefix=_prefix_callable)
     self.token = token
     self.db = DBase('credentials.json')
     self.destiny = pydest.Pydest(bungie_api_key)
     self.bungie_client_id = bungie_client_id
     self.uptime = datetime.datetime.utcnow()
     self.command_count = 0
 def __init__(self, api_key: str, group_id: int, members_data_path="members.json", loop=None) -> (list, list):
     self.destiny = pydest.Pydest(api_key, loop)
     # 한국어가 pydest 모듈에만 목록에 존재하지 않아서 임시로 땜빵...
     self.destiny._manifest.manifest_files["ko"] = ""
     self.group_id = group_id
     self.members_data_path = members_data_path
     self.members_data_cache = []
     if not os.path.exists(members_data_path):
         with open(members_data_path, "w", encoding="utf-8") as f:
             f.write("[]")
async def pull_manifest():
    # open API connection
    destiny = pydest.Pydest(BUNGIE_API)
    # grab the manifest data
    res = await destiny.api._get_request(
        'https://www.bungie.net/Platform/Destiny2/Manifest/')
    # close API connection
    await destiny.close()
    # return manifest data
    return res
Exemple #11
0
    async def test_update_manifest_called(self):
        mock = MagicMock()
        mock.method.return_value = None
        update_manifest_mock = asyncio.coroutine(mock.method)

        destiny = pydest.Pydest('123')
        destiny._manifest.update_manifest = update_manifest_mock
        res = await destiny.update_manifest(language='en')
        destiny.close()

        mock.method.assert_called_with('en')
Exemple #12
0
    async def test_decode_hash_called(self):
        mock = MagicMock()
        mock.method.return_value = None
        decode_hash_mock = asyncio.coroutine(mock.method)

        destiny = pydest.Pydest('123')
        destiny._manifest.decode_hash = decode_hash_mock
        res = await destiny.decode_hash(123, 'ActivityDefinition', language='fr')
        await destiny.close()

        mock.method.assert_called_with(123, 'ActivityDefinition', 'fr')
Exemple #13
0
async def main():
    destiny = pydest.Pydest(os.getenv('BUNGIE_API'))

    res = await destiny.api._get_request(
        'https://www.bungie.net/Platform/Destiny2/Manifest/')

    # print results
    print(res)

    # make sure loop is closed
    await destiny.close()
Exemple #14
0
    async def update(self):
        destiny = pydest.Pydest(self._api_key)

        await destiny.update_manifest()

        """Searches for the given player name, and grabs their platform and ID"""
        search = await destiny.api.search_destiny_player(-1, self._name)
        data = search['Response'][0]
        self.membership_id = data['membershipId']
        self.membership_type = data['membershipType']
        self._name = data['displayName']
        profile = await destiny.api.get_profile(data['membershipType'], data['membershipId'], [200])

        """Finds all characters, and checks to see which character was last logged in"""
        character_dates = []

        for i, (key, value) in enumerate(profile['Response']['characters']['data'].items()):
            print(key, value)
            character_dates.append(value['dateLastPlayed'])

        latest_character_played_date = max(character_dates)

        latest_character = None

        for i, (key, value) in enumerate(profile['Response']['characters']['data'].items()):
            if value['dateLastPlayed'] == latest_character_played_date:
                latest_character = value
                self.latest_character_played_date = latest_character_played_date
                self.current_character_id = value['characterId']

        latest_character = await destiny.api.get_character(data['membershipType'], data['membershipId'],
                                                           latest_character['characterId'], [204])

        """Attempts to find attributes about current activity/place"""

        if 'currentActivityHash' in latest_character['Response']['activities']['data']:
            current_activity = await destiny.decode_hash(
                latest_character['Response']['activities']['data']['currentActivityHash'], "DestinyActivityDefinition")
            self.current_activity_started = latest_character['Response']['activities']['data']['dateActivityStarted']

            try:
                current_activity_mode = await destiny.decode_hash(
                    latest_character['Response']['activities']['data']['currentActivityModeHash'],
                    "DestinyActivityModeDefinition")
            except pydest.PydestException:
                current_activity_mode = 'Unknown'
        if 'currentActivityModeType' in latest_character['Response']['activities']['data']:
            self.current_activity_type = latest_character['Response']['activities']['data']['currentActivityModeType']
        else:
            self.current_activity_type = 0

        self.place = await destiny.decode_hash(current_activity["placeHash"], "DestinyPlaceDefinition")['displayProperties']['name']
        self._state = await destiny.decode_hash(current_activity["placeHash"], "DestinyPlaceDefinition")['displayProperties']['description']
        destiny.close()
Exemple #15
0
    async def res(self):
        destiny = pydest.Pydest(api_key)
        milestone_r = await destiny.api.get_public_milestones()
        ms = milestone_r['Response']
        milestone_hash = ""
        for item in ms:
            milestone_hash = item
            break

        r = await destiny.api.get_milestone_definitions(milestone_hash)
        await destiny.close()
        return r
async def pull_sql(manifest):
    # open API connection
    destiny = pydest.Pydest(BUNGIE_API)
    # grab SQL data from manifest
    URL = 'https://www.bungie.net' + \
        manifest['Response']['mobileWorldContentPaths']['en']
    print('Pulling data from ' + URL)
    res = await destiny.api._get_request(URL)
    # close API connection
    await destiny.close()
    # return manifest data
    return res
Exemple #17
0
async def main():
    """You will need to add your api key!"""
    destiny = pydest.Pydest('api-key')

    activity1 = await destiny.decode_hash(18699611, 'DestinyActivityDefinition')
    await destiny.update_manifest()
    activity2 = await destiny.decode_hash(80726883, 'DestinyActivityDefinition')

    print("Activity Name: {}".format(activity1['displayProperties']['name']))
    print("Description: {}".format(activity1['displayProperties']['description']))
    print("")
    print("Activity Name: {}".format(activity2['displayProperties']['name']))
    print("Description: {}".format(activity2['displayProperties']['description']))

    await destiny.close()
Exemple #18
0
async def main():
    """You will need to add your api key!"""
    destiny = pydest.Pydest('KEY_GOES_HERE')

    """Insert your gamertag/PSN ID/Battle Net name here"""
    player_name = "CivilExponent"
    await destiny.update_manifest()

    """Searches for the given player name, and grabs their platform and ID"""
    search = await destiny.api.search_destiny_player(-1, player_name)
    data = search['Response'][0]
    profile = await destiny.api.get_profile(data['membershipType'], data['membershipId'], [200])

    """Finds all characters, and checks to see which character was last logged in"""
    character_dates = []

    for i, (key, value) in enumerate(profile['Response']['characters']['data'].items()):
        print(key, value)
        character_dates.append(value['dateLastPlayed'])

    latest_character_played_date = max(character_dates)

    latest_character = None

    for i, (key, value) in enumerate(profile['Response']['characters']['data'].items()):
        if value['dateLastPlayed'] == latest_character_played_date:
            latest_character = value

    latest_character = await destiny.api.get_character(data['membershipType'], data['membershipId'], latest_character['characterId'], [204])

    """Attempts to find attributes about current activity/place"""

    if 'currentActivityHash' in latest_character['Response']['activities']['data']:
        current_activity = await destiny.decode_hash(latest_character['Response']['activities']['data']['currentActivityHash'], "DestinyActivityDefinition")
        current_activity_started = latest_character['Response']['activities']['data']['dateActivityStarted']

        try:
            current_activity_mode = await destiny.decode_hash(latest_character['Response']['activities']['data']['currentActivityModeHash'], "DestinyActivityModeDefinition")
        except pydest.PydestException:
            current_activity_mode = 'Unknown'
    if 'currentActivityModeType' in latest_character['Response']['activities']['data']:
        current_activity_mode_type = latest_character['Response']['activities']['data']['currentActivityModeType']
    else:
        current_activity_mode_type = 0

    place = await destiny.decode_hash(current_activity["placeHash"], "DestinyPlaceDefinition")
    destiny.close()
Exemple #19
0
    async def res(self):
        destiny = pydest.Pydest(api_key)
        profile = await destiny.api.get_profile(self._membership_type,
                                                self._membership_id,
                                                ["Characters"])
        res = profile['Response']['characters']['data']
        character_hash = ""
        for item in res:
            character_hash = item
            break

        r = await destiny.api.get_character(self._membership_type,
                                            self._membership_id,
                                            character_hash,
                                            ['CharacterActivities'])
        await destiny.close()
        return r
Exemple #20
0
async def item(request):
    api_data_file = open('api.json', 'r')
    api_data = json.loads(api_data_file.read())
    d2 = pydest.Pydest(api_data['key'])
    item_manifest = await d2.decode_hash(request.args['hash'][0],
                                         'DestinyInventoryItemDefinition',
                                         language='ru')
    if 'screenshot' in item_manifest.keys():
        screenshot = '<img class="screenshot" src="https://bungie.net{}">'.format(
            item_manifest['screenshot'])
    else:
        screenshot = '<img class="icon" src="https://bungie.net{}">'.format(
            item_manifest['displayProperties']['icon'])
    await d2.close()
    return response.html(
        '<!DOCTYPE html lang="ru">\n'
        '<html lang="ru">\n'
        '<meta name="theme-color" content="#222222">\n'
        '<meta name="viewport" content="width=device-width, initial-scale=1">\n'
        '<link rel="stylesheet" type="text/css" href="/static/style.css">\n'
        '<header class="header-fixed">\n'
        '    <div class="header-limiter">\n'
        '		<h1><a href="/">d2info</a></h1>\n'
        '		<nav>\n'
        '			<a href="/">Главная</a>\n'
        '            <a href="/daily">Сегодня</a>\n'
        '            <a href="/weekly">На этой неделе</a>\n'
        '			<a href="/eververse">Эверверс</a>\n'
        '		</nav>\n'
        '	</div>\n'
        '</header>\n'
        '<div class="header-fixed-placeholder"></div>\n'
        '<title>{}</title>\n'
        '<link rel="icon" type="image/png" sizes="32x32" href="https://bungie.net{}">\n'
        '{}\n'
        '<h3>{}</h3>\n'
        '<a>{}</a><br>\n'
        '<form method="get" action="javascript:history.back()">\n'
        '    <button type="submit">Вернуться назад</button>\n'
        '</form>\n'.format(item_manifest['displayProperties']['name'],
                           item_manifest['displayProperties']['icon'],
                           screenshot,
                           item_manifest['displayProperties']['name'],
                           item_manifest['displayProperties']['description']))
Exemple #21
0
async def get_stats(user_platform):
    destiny = pydest.Pydest(api_key)

    username, platform = user_platform.split(',')

    membership_type = membership_types[platform]

    membership_id = await get_membership_id(destiny, username, membership_type)

    character_id = await get_character_id(destiny, membership_type,
                                          membership_id)

    stats = await destiny.api.get_historical_stats(membership_type,
                                                   membership_id, character_id)

    stats = clean_stats(stats)

    destiny.close()

    return stats
Exemple #22
0
 async def res(self):
     destiny = pydest.Pydest(api_key)
     r = await destiny.api.get_membership_data_by_id(637429)
     await destiny.close()
     return r
Exemple #23
0
 async def res(self):
     destiny = pydest.Pydest(api_key)
     r = await destiny.api.get_profile(self._membership_type,
                                       self._membership_id, ['Characters'])
     await destiny.close()
     return r
Exemple #24
0
 async def res(self):
     destiny = pydest.Pydest(api_key)
     r = await destiny.api.get_destiny_manifest()
     await destiny.close()
     return r
Exemple #25
0
import pydest, bungoAPI, asyncio
destiny = pydest.Pydest(bungoAPI.APIKey)
categories = []


async def getUserStats(membershipID, membershipType):
    res2 = await destiny.api.get_historical_stats(membershipType, membershipID)
    print(res2)
    for item in res2["Response"]:
        categories.append(str(item))
        print(item)

    for subcat in res2["allPvP"]:
        print[subcat]


async def getUser():

    platform = input(
        'Enter your platform (xbox[1], playstation[2], or pc[3]): ')
    username = input('Enter the username to locate: ')

    res = await destiny.api.search_destiny_player(platform, username)
    print(res)

    if res['ErrorCode'] == 1 and len(res['Response']) > 0:
        membershipID = res['Response'][0]['membershipId']
        membershipType = res['Response'][0]['membershipType']
        print(membershipID)
        print("---" * 20)
        print("Player found!")
Exemple #26
0
 async def res(self):
     destiny = pydest.Pydest(api_key)
     r = await destiny.api.search_destiny_player(1, 'dummy')
     await destiny.close()
     return r
Exemple #27
0
async def search_destiny_player():
    destiny = pydest.Pydest(BUNGIE_KEY)

    await destiny.api.search_destiny_player()

    await destiny.close()
Exemple #28
0
 def test_close(self):
     destiny = pydest.Pydest('123')
     destiny.close()
     assert destiny._session.closed
Exemple #29
0
import pydest
import asyncio
import time

HEADERS = {"X-API-Key": '19a8efe4509a4570bee47bd9883f7d93'}
API_KEY = '19a8efe4509a4570bee47bd9883f7d93'
ROOT = 'https://www.bungie.net/Platform'
destiny = pydest.Pydest(API_KEY)


async def main():

    time_start = time.time()
    weaponlist = {}
    activities = await destiny.api.get_activity_history(
        3, 4611686018497181967, 2305843009574424386, 20, 5, 0)
    for i in activities['Response']['activities']:
        activityid = i['activityDetails']['instanceId']
        detail = await destiny.api.get_post_game_carnage_report(int(activityid)
                                                                )
        for j in detail['Response']['entries']:
            if j['player']['destinyUserInfo'][
                    'membershipId'] == '4611686018497181967':
                if 'weapons' in j['extended']:
                    for weapon in j['extended']['weapons']:
                        Weaponid = weapon['referenceId']
                        Kills = weapon['values']['uniqueWeaponKills']['basic'][
                            'value']
                        PrecisionKills = weapon['values'][
                            'uniqueWeaponPrecisionKills']['basic']['value']
                        if Weaponid in weaponlist:
Exemple #30
0
    async def d2(self, ctx, battletag_or_discord="myself", character=1):
        """
        Get Destiny 2 Stats and Equipped Items

        Defaults to yourself if no one else is specified (this'll require your battletag to be on the list)
        Defaults to character 1 if no character is specified
        """
        # Some code from https://github.com/jgayfer/spirit/blob/master/cogs/destiny.py

        # TODO allow for something like "?d2 2" (will think you're changing battletag atm)

        if battletag_or_discord == "myself":
            battletag_or_discord = ctx.message.author.id

        bnet = battle_net_parse_user(battletag_or_discord)
        if bnet == 0:
            await self.bot.say("'{}' is not a BattleTag or Discord Mention.".format(battletag_or_discord))
            return
        elif bnet == 1:
            await self.bot.say("User '{}' has no associated BattleTag. Tell {} to add it to the list! Until it is added"
                               " type their battletag instead. (i.e. ?d2 ExtraRandom#2501)."
                               "".format(battletag_or_discord, self.er_id))
            return

        destiny = pydest.Pydest(t.d2_api)
        pre_data = await destiny.api.search_destiny_player(4, bnet)  # print(pre_data)
        try:
            user_id = pre_data['Response'][0]['membershipId']  # print("user id: {}".format(user_id))
        except IndexError:
            await self.bot.say("User '{}' does not own Destiny 2.".format(bnet))
            return

        try:
            profile_data = await destiny.api.get_profile(4, user_id, ['characters', 'characterEquipment', 'profiles'])
        except pydest.PydestException as e:
            await self.bot.say("Error getting Guardian Stats (Code: 1)")
            return

        if profile_data['ErrorCode'] != 1:
            await self.bot.say("Error getting Guardian Stats (Code: 2)")
            return

        chars = len(profile_data['Response']['characters']['data'])
        if character > chars or character < 1:
            await self.bot.say("No chatacter #{} found, defaulting to character #1 instead".format(character))
            character = 1

        char = character - 1
        char_id = 0

        try:
            char_id = profile_data['Response']['profile']['data']['characterIds'][char]
        except Exception as e:
            await self.bot.say("Error getting Guardian Stats (Code: 3)")
            return

        try:
            char_data = profile_data['Response']['characters']['data'][char_id]

            role_dict = await destiny.decode_hash(char_data['classHash'], 'DestinyClassDefinition')
            role = role_dict['displayProperties']['name']

            gender_dict = await destiny.decode_hash(char_data['genderHash'], 'DestinyGenderDefinition')
            gender = gender_dict['displayProperties']['name']

            race_dict = await destiny.decode_hash(char_data['raceHash'], 'DestinyRaceDefinition')
            race = race_dict['displayProperties']['name']

            level = char_data['levelProgression']['level']
            light = char_data['light']

            avatar = self.img_base + char_data['emblemPath']

            mins_played = int(char_data['minutesPlayedTotal'])
            time_played = mins_played / 60

            equipped = profile_data['Response']['characterEquipment']['data'][char_id]['items']

            weapon_i = 0
            armour_i = 0

            weapons = []
            armours = []

            for item in equipped:

                item_dict = await destiny.decode_hash(item['itemHash'], 'DestinyInventoryItemDefinition')
                item_name = item_dict['displayProperties']['name']

                if weapon_i < 3:
                    weapons.append(item_name)
                    weapon_i += 1

                elif armour_i < 5:
                    armours.append(item_name)
                    armour_i += 1

            stat_hashs = char_data['stats']

            s_recovery = -1
            s_resilience = -1
            s_mobility = -1

            for stat in stat_hashs:
                stat_dict = await destiny.decode_hash(stat, 'DestinyStatDefinition')  # print(stat, stat_dict)
                try:
                    if stat_dict['displayProperties']['name'] == "Recovery":
                        s_recovery = stat_hashs[stat]
                    elif stat_dict['displayProperties']['name'] == "Mobility":
                        s_mobility = stat_hashs[stat]
                    elif stat_dict['displayProperties']['name'] == "Resilience":
                        s_resilience = stat_hashs[stat]

                    if s_mobility > -1 and s_recovery > -1 and s_resilience > -1:
                        break

                except KeyError:
                    pass

            if s_resilience == -1: s_resilience = 0
            if s_recovery == -1: s_recovery = 0
            if s_mobility == -1: s_mobility = 0

            embed = discord.Embed(colour=discord.Colour.blue())
            embed.set_author(name=bnet.replace("%23", "#"), icon_url="https://i.imgur.com/NF5PVtL.png")
            embed.set_thumbnail(url=avatar)
            embed.description = "Level {} {} {} {} |" \
                                ":small_blue_diamond:{}\n" \
                                "{} Mobility - {} Resilience - {} Recovery" \
                                "".format(level, race, gender, role, light,
                                          s_mobility, s_resilience, s_recovery)
            embed.add_field(name="Weapons", value="**Kinetic:** {}\n"
                                                  "**Energy:** {}\n"
                                                  "**Power:** {}"
                                                  "".format(weapons[0], weapons[1], weapons[2]))
            embed.add_field(name="Armour", value="**Helmet:** {}\n"
                                                 "**Gauntlets:** {}\n"
                                                 "**Chest:** {}\n"
                                                 "**Legs:** {}\n"
                                                 "**Class Item:** {}"
                                                 "".format(armours[0], armours[1], armours[2], armours[3], armours[4]))
            embed.add_field(name="Other Stats", value="**Time Played:** {} hours"
                                                      "".format(round(time_played, 2)))

            await self.bot.say(embed=embed)
        except Exception as e:
            log.warn("D2 command Error: ", e)
            await self.bot.say("Error getting Guardian Stats (Code: 4)")

        destiny.close()