Esempio n. 1
0
def test_kwarg_instance():
    assert SteamID(id=5, instance=1234).instance == 1234

    for type in EType:
        assert (SteamID(id=5, type=type).instance == 1 if type in (
            EType.Individual,
            EType.GameServer) else SteamID(id=5, type=type).instance == 0)
Esempio n. 2
0
    def get_user(self, user: str):
        if user.startswith(
                "https://steamcommunity.com/id/") or user.startswith(
                    "https://steamcommunity.com/profiles/"):
            u = user.replace("//", "/", 1).split("/", 3)[-1]
            return steam.steamid.from_url(user), u if u[-1] != "/" else u[:-1]

        res = self._api.call("ISteamUser.ResolveVanityURL",
                             vanityurl=user,
                             url_type=1)
        if res["response"]["success"] == 1:
            return SteamID(res["response"]["steamid"]), user
        else:
            # TODO: Logging
            print(res)
            pass

        if user.isnumeric():
            res = self._api.call("ISteamUser.GetPlayerSummaries",
                                 steamids=user)
            if isinstance(res["response"]["players"], list) and len(
                    res["response"]["players"]) == 1:
                u = res["response"]["players"][0]
                return SteamID(u["steamid"]), u["personaname"]
            elif isinstance(res["response"]["players"], dict) and len(
                    res["response"]["players"]["player"]) == 1:
                u = res["response"]["players"]["player"][0]
                return SteamID(u["steamid"]), u["personaname"]
            else:
                print(res)
                pass
            pass
        raise SteamMatchException(f"User {user} not found.")
Esempio n. 3
0
def test_arg_steam64():
    compare(SteamID(76580280500085312),
            [123456, EType.Individual, EUniverse.Public, 4444])
    compare(SteamID("76580280500085312"),
            [123456, EType.Individual, EUniverse.Public, 4444])
    compare(SteamID(103582791429521412), [4, EType.Clan, EUniverse.Public, 0])
    compare(SteamID("103582791429521412"),
            [4, EType.Clan, EUniverse.Public, 0])
Esempio n. 4
0
def test_kwarg_instance() -> None:
    assert SteamID(
        id=5, instance=InstanceFlag.Console).instance == InstanceFlag.Console

    for type in Type:
        assert (SteamID(id=5, type=type).instance == InstanceFlag.Desktop
                if type in (Type.Individual, Type.GameServer) else SteamID(
                    id=5, type=type).instance == InstanceFlag.All)
 def convert_from_vanity_url_to_SteamID(self, user_string):
     """ Tries to create a SteamID object via the URL. """
     if user_string.isdigit():
         return SteamID.from_url(
             "http://steamcommunity.com/profiles/{}".format(user_string))
     else:
         return SteamID.from_url(
             "http://steamcommunity.com/id/{}".format(user_string))
Esempio n. 6
0
def test_kwarg_type():
    with pytest.raises(InvalidSteamID):
        SteamID(id=5, type="doesn't exist")
    with pytest.raises(InvalidSteamID):
        SteamID(id=5, type=99999999)

    assert SteamID(id=5, type=1).type == EType.Individual
    assert SteamID(id=5, type="Individual").type == EType.Individual
    assert SteamID(id=5, type="AnonUser").type == EType.AnonUser
Esempio n. 7
0
def test_kwarg_universe():
    with pytest.raises(InvalidSteamID):
        SteamID(id=5, universe="doesn't exist")
    with pytest.raises(InvalidSteamID):
        SteamID(id=5, universe=99999999)

    assert SteamID(id=5, universe=1).universe == EUniverse.Public
    assert SteamID(id=5, universe="Public").universe == EUniverse.Public
    assert SteamID(id=5, universe="Dev").universe == EUniverse.Dev
Esempio n. 8
0
    async def steamsync(self,
                        ctx: commands.Context,
                        steam_id: str,
                        user: Optional[discord.Member] = None) -> None:
        """
        Sync a Steam profile's games with a Discord ID

        steam_id: Steam Name (found in your Custom URL -> steamcommunity.com/id/<name>) or Steam ID (64-bit ID -> steamcommunity.com/profiles/<id>)
        user: If given, sync library to user, otherwise default to user of the message

        Examples:
        ```
            [p]game steamsync Alyx
            [p]game steamsync Alyx @Alyx
            [p]game steamsync 76561198221914843
            [p]game steamsync 76561198221914843 @Alyx
        ```
        """

        await ctx.trigger_typing()

        if not user:
            user = ctx.author

        steam_user = SteamID(steam_id)
        if steam_user.is_valid():
            # Either use the given 64-bit Steam ID to sync with Steam...
            steam_id_64 = steam_user.as_64
        else:
            # ...or convert given name to a 64-bit Steam ID
            steam_client = await self.get_steam_client(ctx)

            if steam_client is None:
                return

            steam_name = steam_client.ISteamUser.ResolveVanityURL(
                vanityurl=steam_id)

            if steam_name.get("response", {}).get("success") != 1:
                await ctx.send(
                    f"There was a problem syncing {user.mention}'s account with Steam ID '{steam_id}'. Please try again with the 64-bit Steam ID instead."
                )
                return

            steam_id_64 = steam_name.get("response", {}).get("steamid")

        await self.config.user(user).steam_id.set(steam_id_64)

        steam_game_list = await self.get_steam_games(ctx, user)
        if steam_game_list:
            game_list = await self.config.user(user).games()
            game_list.extend(steam_game_list)
            game_list = list(set(game_list))
            await self.config.user(user).games.set(game_list)

        await ctx.send(f"{user.mention}'s account was synced with Steam.")
Esempio n. 9
0
def test_as_invite_url():
    assert SteamID(0, EType.Individual, EUniverse.Public,
                   instance=1).invite_url is None
    assert SteamID(123456, EType.Individual, EUniverse.Public,
                   instance=1).invite_url == "https://s.team/p/cv-dgb"
    assert SteamID(123456, EType.Individual, EUniverse.Beta,
                   instance=1).invite_url == "https://s.team/p/cv-dgb"
    assert SteamID(123456, EType.Invalid, EUniverse.Public,
                   instance=1).invite_url is None
    assert SteamID(123456, EType.Clan, EUniverse.Public,
                   instance=1).invite_url is None
Esempio n. 10
0
def test_as_invite_code():
    assert SteamID(0, EType.Individual, EUniverse.Public,
                   instance=1).invite_code is None
    assert SteamID(123456, EType.Individual, EUniverse.Public,
                   instance=1).invite_code == "cv-dgb"
    assert SteamID(123456, EType.Individual, EUniverse.Beta,
                   instance=1).invite_code == "cv-dgb"
    assert SteamID(123456, EType.Invalid, EUniverse.Public,
                   instance=1).invite_code is None
    assert SteamID(123456, EType.Clan, EUniverse.Public,
                   instance=1).invite_code is None
Esempio n. 11
0
def test_community_url():
    # user url
    assert SteamID(
        76580280500085312
    ).community_url == "https://steamcommunity.com/profiles/76580280500085312"
    # group url
    assert SteamID(
        "[g:1:4]"
    ).community_url == "https://steamcommunity.com/gid/103582791429521412"
    # else None
    assert SteamID("[A:1:4]").community_url is None
Esempio n. 12
0
 def add_ban(self, target, duration=0, admin=0, reason=None):
     target_id = SteamID.Parse(uniqueid_from_index(target)).to_uint64()
     if admin == 0:
         admin_id = None
     else:
         admin_id = SteamID.Parse(uniqueid_from_index(admin)).to_uint64()
     ban_record = BanRecord(target_id=target_id,
                            admin_id=admin_id,
                            duration=duration,
                            reason=reason)
     with session_scope() as session:
         session.add(ban_record)
Esempio n. 13
0
 async def names(self, ctx, member: discord.Member = None, service=None):
     if member == None:
         member = ctx.message.author
     discordID = str(member.id)
     with open('matchacat/matchacat.json', 'r') as f:
         matchacatJSON = json.load(f)
     if matchacatJSON['users'].get(discordID, None) != None:
         if service == None:
             UserList = []
             if matchacatJSON['users'][discordID].get('steamID') != None:
                 UserList += [
                     'Steam: ' + (SteamID(matchacatJSON['users'][discordID]
                                          ['steamID']).community_url)
                 ]
             if matchacatJSON['users'][discordID].get('MCuuid') != None:
                 print(matchacatJSON['users'][discordID].get('MCuuid'))
                 MCuser = mcutil.search(member)
                 print(MCuser)
                 if MCuser != None:
                     UserList += ['Minecraft: ' + MCuser]
             if matchacatJSON['users'][discordID].get('PSuser') != None:
                 UserList += [
                     'Showdown: ' +
                     matchacatJSON['users'][discordID].get('PSuser')
                 ]
             if UserList != []:
                 await ctx.send('\n'.join(UserList))
             else:
                 await ctx.send('This user has no names registered.')
         if service == self.services[0]:  #Steam
             if matchacatJSON['users'][discordID].get('steamID',
                                                      None) != None:
                 steamurl = SteamID(matchacatJSON['users'][discordID]
                                    ['steamID']).community_url
                 await ctx.send(steamurl)
         if service == self.services[1]:  #Minecraft
             MCuser = mcutil.search(member)
             if MCuser == None:
                 await ctx.send('Could not find username.')
             else:
                 await ctx.send('{}'.format(MCuser))
         if service == self.services[2]:  #Showdown
             showdown = matchacatJSON['users'][discordID].get('PSuser')
             if showdown != None:
                 ctx.send(showdown)
             else:
                 ctx.send('This user has no pokemon showdown nickname.')
     else:
         await ctx.send('This user has no usernames registered')
Esempio n. 14
0
def test_from_id():
    compare(SteamID(1), [1, EType.Individual, EUniverse.Public, 1])
    compare(SteamID("1"), [1, EType.Individual, EUniverse.Public, 1])
    compare(SteamID(12), [12, EType.Individual, EUniverse.Public, 1])
    compare(SteamID("12"), [12, EType.Individual, EUniverse.Public, 1])
    compare(SteamID(123), [123, EType.Individual, EUniverse.Public, 1])
    compare(SteamID("123"), [123, EType.Individual, EUniverse.Public, 1])
    compare(SteamID(12345678),
            [12345678, EType.Individual, EUniverse.Public, 1])
    compare(SteamID("12345678"),
            [12345678, EType.Individual, EUniverse.Public, 1])
    compare(SteamID(0xFFFFFFFF),
            [0xFFFFFFFF, EType.Individual, EUniverse.Public, 1])
    compare(SteamID(str(0xFFFFFFFF)),
            [0xFFFFFFFF, EType.Individual, EUniverse.Public, 1])
Esempio n. 15
0
    def login_callback(resp):
        """Callback fired after steam login, log user in the application by generating a refresh token.
        Also create a basic profil from steam information if this is the first login.

        Args:
            resp: OpenID response.
        Returns:
            Redirects to the callback url defined in the config with the refresh token as a parameter.
        """
        match = _steam_id_re.search(resp.identity_url)
        steam_id = SteamID(match.group(1))

        token = {
            'steamid': str(steam_id.as_64),
            'aud': 'refresh',
            'exp': datetime.utcnow() + timedelta(days=60)
        }
        token = jwt.encode(token, app.config['SECRET_KEY'])

        UserRefreshToken.upsert(steam_id, token.decode('utf-8'))
        user = User.get(steam_id)
        if user is None:
            user = User(steam_id)

            api = WebAPI(key=app.config['STEAM_KEY'])
            resp = api.ISteamUser.GetPlayerSummaries_v2(steamids=steam_id)
            user.nickname = resp['response']['players'][0]['personaname']
            user.avatar = UrlImageToBase64(resp['response']['players'][0]['avatarfull'])
            db.session.add(user)
            db.session.commit()

        url = '{0}?token={1}'.format(app.config['FRONTEND_LOGIN_REDIRECT'],
                                     token.decode('utf-8'))
        return redirect(url)
Esempio n. 16
0
    def login_callback(resp):
        """Callback fired after steam login, log user in the application by generating a refresh token.
        Also create a basic user entry from steam id if this is the first login.

        Args:
            resp: OpenID response.
        Returns:
            Redirects to the callback url defined in the config with the refresh token as a parameter.
        """
        match = _steam_id_re.search(resp.identity_url)
        steam_id = SteamID(match.group(1))

        token = {
            'aud': 'refresh',
            'client': {
                'type': 'user',
                'steamid': str(steam_id.as_64)
            },
            'exp': datetime.utcnow() + timedelta(days=60)
        }
        token = jwt.encode(token, app.config['SECRET_KEY'])

        user = User.get(steam_id)
        if user is None:
            user = User(steam_id)
            db.session.add(user)
        user.refresh_token = token.decode('utf-8')
        db.session.commit()

        url = '{0}?token={1}'.format(app.config['FRONTEND_LOGIN_REDIRECT'],
                                     user.refresh_token)
        return redirect(url)
Esempio n. 17
0
def get_model_by_steamid(steamid):
    try:
        return apps.get_model(
            "steamauthprovider",
            "SteamUser").objects.get(steamid64=SteamID(steamid).as_64)
    except ObjectDoesNotExist:
        return False
Esempio n. 18
0
    def scan_profile_result(self, account_id, profile_card):
        """Process the profile information returned by Steam.

        Extract the SoloMMR from the profile and insert the user in the good ladder.

        Args:
            account_id: steam_id (as 32bits) of the profile result
            profile_card: profile information as a protobuff message
        """
        self.print_info('Processing profile of user %s' %
                        SteamID(account_id).as_64)
        solo_mmr = None
        for slot in profile_card.slots:
            if not slot.HasField('stat'):
                continue
            if slot.stat.stat_id != 1:
                continue
            solo_mmr = int(slot.stat.stat_score)

        with self.app.app_context():
            user = User.query.filter_by(id=self.job.steam_id).first()
            user.profile_scan_info.last_scan = datetime.utcnow()
            if solo_mmr is not None:
                user.solo_mmr = solo_mmr

            if user.solo_mmr is None:
                user.section = None
            else:
                if user.solo_mmr > 4500:
                    user.section = constants.LADDER_HIGH
                else:
                    user.section = constants.LADDER_LOW

            db.session.commit()
        self.job.scan_finish = True
Esempio n. 19
0
async def steam(ctx, *args):
    """Link your steam account to your profile
    !steam < steam link >"""
    author = ctx.author.mention
    if len(args) == 0:
        await ctx.send(f"{author}, incorrect format please see !help steam")
    elif len(args) > 1:
        await ctx.send(f"{author}, inccorect format please see !help steam")
    else:
        steamID = str(SteamID.from_url(f"{args[0]}", http_timeout=10))
        if steamID == "None":
            await ctx.send(f"{author}, sorry that is not a valid link.")
        else:
            conn = sql.connect("data.db")
            cursor = conn.cursor()
            if cursor.execute(
                    f"SELECT * FROM users WHERE nickname = '{ctx.author}';"
            ).fetchone() == None:
                cursor.execute(
                    f"""INSERT INTO users(steamID, nickname) VALUES ('{steamID}','{ctx.author}')"""
                )
            else:
                cursor.execute(
                    f"UPDATE users SET steamID = '{steamID}' WHERE nickname = '{ctx.author}'"
                )
            conn.commit()
            await ctx.send(f"{author}, success you're accounts are now linked."
                           )
    def get_prof_names(self, args):
        try:
            for self.nm, self.u_32 in enumerate(self.get_local_32()):
                self.url = SteamID(self.u_32).community_url
                req = requests.get(self.url + '/ajaxaliases')
                if req.status_code:
                    self.user_name = json.loads(req.content)[0]['newname']
                    if not self.u_32 in self.cfg['profiles'].keys():
                        self.cfg['profiles'][self.u_32] = {
                            'user_name': self.user_name,
                            'details': {}
                        }
                    else:
                        self.cfg['profiles'][
                            self.u_32]['user_name'] = self.user_name

                    self.cfg['users'][self.user_name] = self.u_32

                    print(f'Found : {self.user_name} : {self.u_32}')

                else:
                    print(
                        f'bad status request for {self.u_32} : {self.user_name}'
                    )

            print(f'Found {self.nm+1} accounts...')
            self.save_cfg()
        except Exception as error:
            pass
Esempio n. 21
0
def chatHistory(request, steamid):
    if steamid.startswith("STEAM_") or steamid.isdigit():
        try:
            steamid64 = SteamID(steamid)
            steamid2 = steamid64.as_steam2
        except (TypeError, ValueError) as e:
            content = {'error': 'Please enter a valid steamid or steamid64'}
            return Response(content, status=status.HTTP_404_NOT_FOUND)
        else:
            try:
                chats = Chatlogs.objects.using('Chatlogs').filter(
                    steamid=steamid2).order_by('-date')
                if not chats:
                    content = {'error': 'Player not in database'}
                    return Response(content, status=status.HTTP_404_NOT_FOUND)
            except TypeError:
                content = {
                    'error': 'Please enter a valid steamid or steamid64'
                }
                return Response(content, status=status.HTTP_404_NOT_FOUND)
            else:
                chat = []
                for x in chats:
                    chat.append(x.text)
                return Response({"chatHistory": chat})
    else:
        content = {'error': 'Please enter a valid steamid or steamid64'}
        return Response(content, status=status.HTTP_404_NOT_FOUND)
Esempio n. 22
0
def topTen(request):
    sql = "SELECT id, auth, SUM(duration) duration FROM player_analytics GROUP BY auth ORDER BY duration DESC LIMIT 10"
    top_players = PlayerAnalytics.objects.using('Analytics').raw(sql)
    top_ten = defaultdict(dict)
    i = 0
    for x in top_players:
        i += 1
        steamid64 = SteamID(x.auth)
        steamid2 = steamid64.as_steam2
        top_ten[i]['hours'] = int(
            PlayerAnalytics.objects.using('Analytics').filter(
                auth=steamid2).aggregate(Sum('duration'))['duration__sum'] /
            3600)
        top_ten[i]['profile'] = "http://steamcommunity.com/profiles/{}".format(
            steamid64)
        top_ten[i]['steamid2'] = steamid2

        file = urllib.request.urlopen(
            "http://steamcommunity.com/profiles/{}/?xml=1".format(steamid64))
        data = file.read()
        file.close()
        data = xmltodict.parse(data)

        top_ten[i]['picture'] = data["profile"]["avatarIcon"]
        top_ten[i]['name'] = data["profile"]["steamID"]

    return Response({'topten': top_ten})
Esempio n. 23
0
def test_as_steam3():
    assert SteamID("[U:1:1234]").id3, "[U:1:1234]"
    assert SteamID("[U:1:1234:56]").id3, "[U:1:1234:56]"
    assert SteamID("[g:1:4]").id3, "[g:1:4]"
    assert SteamID("[A:1:1234:567]").id3 == "[A:1:1234:567]"
    assert SteamID("[G:1:1234:567]").id3 == "[G:1:1234]"
    assert SteamID("[T:1:1234]").id3 == "[T:1:1234]"
    assert SteamID("[c:1:1234]").id3 == "[g:1:1234]"
    assert SteamID("[L:1:1234]").id3 == "[L:1:1234]"
Esempio n. 24
0
 async def __getSteamProfile(self, uid):
     async with aiohttp.ClientSession() as session:
         params = {  "key" : keys.STEAM_WEBAPI, 
                     "steamids" : SteamID(uid).as_64  }
         async with session.get(self.steamProfileUrl, params = params) as r:
             if r.status == 200:
                 js = await r.json()
                 return(js['response']['players'][0])
Esempio n. 25
0
    def process_cart_result(self, edge_task, task_result):
        succesful_items = task_result.get('items')
        failed_items = task_result.get('failed_items')
        failed_shopping_cart_gids = task_result.get(
            'failed_shopping_cart_gids')

        RelationController().rollback_pushed_relations(edge_task.task_id)

        if len(failed_shopping_cart_gids):
            log.info(
                u'Received a list of previously commited shoppingCartGID that failed'
            )

            for shopping_cart_gid in failed_shopping_cart_gids:
                if shopping_cart_gid is not None:
                    RelationController().rollback_failed_relations(
                        shopping_cart_gid)

        if len(failed_items):
            log.info(u'Received a list of relations that fail to add to cart')

            for item in failed_items:
                relation_type = item.get('relation_type')
                relation_id = item.get('relation_id')

                RelationController().set_relation_commitment(
                    relation_type,
                    relation_id,
                    enums.ERelationCommitment.FailedToAddToCart.value,
                    edge_task.task_id,
                    commited_on_bot=edge_task.edge_bot.network_id)

        log.info(u'Received {} succesful items'.format(len(succesful_items)))

        for item in succesful_items:
            shopping_cart_gid = task_result.get('shoppingCartGID')

            relation_type = item.get('relation_type')
            relation_id = item.get('relation_id')

            RelationController().set_relation_commitment(
                relation_type,
                relation_id,
                enums.ERelationCommitment.AddedToCart.value,
                shopping_cart_gid=shopping_cart_gid)

        if len(succesful_items):
            # Assume there is one cart-push per user, so just grab the first on the list

            user_id = succesful_items[0].get('user_id')
            user = self.user_model.get(id=user_id)
            account_id = SteamID(user.steam).as_32

            self.call_checkout(edge_task.edge_bot, edge_task.edge_server,
                               account_id)
        else:
            self.set_edge_bot_status(edge_task.edge_bot.network_id,
                                     enums.EEdgeBotStatus.StandingBy.value)
Esempio n. 26
0
async def map(ctx, arg):
    if ctx.message.channel.id == PLAYER_COMMANDS:
        sql = "SELECT time, auth FROM playertimes WHERE map = '" + arg + "' ORDER by 'time' ASC"
        crs = mydb.cursor(buffered=True)
        crs.execute(sql)
        maptime = crs.fetchone()
        user = SteamID(maptime[1])
        user = user.community_url
        await ctx.send("Best time on map: ***" + arg + "*** is ***" + str(maptime[0]) + "*** sekund, ustanowiony przez " + user)
Esempio n. 27
0
def convert_to_steam_id(user_string):
    """ Generates valid steam IDs from user input.

        Keyword arguments:
        user_string -- input from user
    """

    # Converts URL format to standard format.
    user_string = user_string.split("/")[-1]
    steam_id = SteamID(user_string)
    if steam_id.is_valid():
        return steam_id
    else:  # Failure can be due to vanity usernames.
        steam_id = convert_from_vanity_url_to_steam_id(user_string)
        if steam_id:
            return steam_id
        else:
            return None
Esempio n. 28
0
 async def steamid(self, ctx, communityid: str):
     """Gets a steam id in all formats"""
     await ctx.channel.trigger_typing()
     steamID = SteamID.from_url(
         "http://steamcommunity.com/id/{}".format(communityid))
     if steamID is None:
         steamID = SteamID(communityid)
     try:
         name = steamAPI.ISteamUser.GetPlayerSummaries_v2(
             steamids=steamID)["response"]["players"][0]["personaname"]
     except IndexError:
         await ctx.send(
             "User not found! Make sure you are using steam community IDs!")
         return
     await ctx.send(
         xl.format(
             "Steam ID formats for {}:\nSteamID2: {}\nSteamID2Zero: {}\nSteamID3: {}\nSteamID32: {}\nSteamID64: {}"
         ).format(name, steamID.as_steam2, steamID.as_steam2_zero,
                  steamID.as_steam3, steamID.as_32, steamID.as_64))
Esempio n. 29
0
def xmlGetInfo(steamid, query):
    steamid64 = str(SteamID(steamid))
    try:
        h = httplib2.Http()
        resp, content = h.request(
            "http://steamcommunity.com/profiles/{}/?xml=1".format(steamid64),
            "GET")
        data = xmltodict.parse(content)
        return data["profile"][query]
    except KeyError:
        return "-"
Esempio n. 30
0
def xmlGetVac(steamid):
    steamid64 = str(SteamID(steamid))
    try:
        h = httplib2.Http()
        resp, content = h.request(
            "http://steamcommunity.com/profiles/{}/?xml=1".format(steamid64),
            "GET")
        data = xmltodict.parse(content)
        return int(data["profile"]["vacBanned"])
    except KeyError:
        return "-"
Esempio n. 31
0
 async def steamid(self, ctx, communityid:str):
     """Gets a steam id in all formats"""
     await ctx.channel.trigger_typing()
     steamID = SteamID.from_url("http://steamcommunity.com/id/{}".format(communityid))
     if steamID is None:
         steamID = SteamID(communityid)
     try:
         name = steamAPI.ISteamUser.GetPlayerSummaries_v2(steamids=steamID)["response"]["players"][0]["personaname"]
     except IndexError:
         await ctx.send("User not found! Make sure you are using steam community IDs!")
         return
     await ctx.send(xl.format("Steam ID formats for {}:\nSteamID2: {}\nSteamID2Zero: {}\nSteamID3: {}\nSteamID32: {}\nSteamID64: {}").format(name, steamID.as_steam2, steamID.as_steam2_zero, steamID.as_steam3, steamID.as_32, steamID.as_64))
Esempio n. 32
0
 async def steamuser(self, ctx, communityid:str):
     """Gets steam profile information on a user with the specified community ID"""
     await ctx.channel.trigger_typing()
     steamID = SteamID.from_url("http://steamcommunity.com/id/{}".format(communityid))
     if steamID is None:
         steamID = communityid
     try:
         steamUser = steamAPI.ISteamUser.GetPlayerSummaries_v2(steamids=steamID)["response"]["players"][0]
     except IndexError:
         await ctx.send("User not found! Make sure you are using steam community IDs!")
         return
     bans = steamAPI.ISteamUser.GetPlayerBans_v1(steamids=steamID)["players"][0]
     vacBanned = bans["VACBanned"]
     communityBanned = bans["CommunityBanned"]
     ban_info = {"VAC Banned":vacBanned, "Community Banned":communityBanned}
     if vacBanned:
         ban_info["VAC Bans"] = bans["NumberOfVACBans"]
         ban_info["Days Since Last VAC Ban"] = bans["DaysSinceLastBan"]
     if steamUser["communityvisibilitystate"] != 3:
         embed = make_list_embed(ban_info)
         embed.description = "This profile is private."
         embed.title = steamUser["personaname"]
         embed.color = 0xFF0000
         embed.url = steamUser["profileurl"]
         embed.set_thumbnail(url=steamUser["avatarfull"])
         await ctx.send(embed=embed)
         return
     groupCount = len(steamAPI.ISteamUser.GetUserGroupList_v1(steamid=steamID)["response"]["groups"])
     games = requests.get("http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key={}&steamid={}&include_played_free_games=1%format=json".format(config._steamAPIKey, steamID)).json()["response"]
     gamesPlayed = games["game_count"]
     state = EPersonaState(steamUser["personastate"]).name
     gameName = None
     if "gameid" in steamUser.keys():
         state = "In-game"
         gameID = steamUser["gameid"]
         gameName = requests.get("http://store.steampowered.com/api/appdetails?appids={}".format(gameID)).json()[gameID]["data"]["name"]
     lastOnline = format_time(datetime.fromtimestamp(steamUser["lastlogoff"]))
     creationDate = format_time(datetime.fromtimestamp(steamUser["timecreated"]))
     fields = {"Status":state, "Created on":creationDate, "Group Count":groupCount, "Games Owned":gamesPlayed}
     if state == EPersonaState.Offline.name:
         fields["Last Online"] = lastOnline
     if gameName:
         fields["Currently Playing"] = gameName
     if "primaryclanid" in steamUser.keys():
         fields["Primary Group Name"] = etree.fromstring(requests.get("http://steamcommunity.com/gid/{}/memberslistxml".format(steamUser["primaryclanid"])).text).find("groupDetails/groupName").text
     fields.update(ban_info)
     embed = make_list_embed(fields)
     embed.title = steamUser["personaname"]
     embed.color = 0xFF0000
     embed.url = steamUser["profileurl"]
     embed.set_thumbnail(url=steamUser["avatarfull"])
     await ctx.send(embed=embed)
Esempio n. 33
0
    def __missing__(self, steamid):
        """Create, store and return a :class:`PlayerPermissions` object.

        :param str/int steamid: A SteamID2, SteamID3 or SteamID64 value.
        """
        if not isinstance(steamid, int):
            steamid64 = SteamID.parse(steamid).to_uint64()
            if steamid64 in self:
                return self[steamid64]

            # We got a SteamID in a string format, so we can store it by using
            # its SteamID64 value, but keep the original name.
            instance = self[steamid64] = PlayerPermissions(steamid, steamid64)
        else:
            instance = self[steamid] = PlayerPermissions(steamid, steamid)

        return instance
def com_net_steam_id_from_user(user_name):
    return SteamID.from_url('https://steamcommunity.com/id/%s', (user_name,))
 def _convert_steamid_to_db_format(self, steamid):
     return str(SteamID.parse(steamid).to_uint64())