Пример #1
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)
Пример #2
0
    def __init__(self, *users):
        self._api: WebAPI = WebAPI(config.STEAM_KEY)

        if len(users) < 2:
            raise SteamException("At least two users must be entered.")
        self._users = list(map(self.get_user, users))
        pass
Пример #3
0
def create_user_games_list(steam_ids):
    """ Grabs list of multiplayer steam games for each valid user. """

    env = environ.Env()
    web_api = WebAPI(env('STEAM_API_KEY'))

    users = OrderedDict()
    for user_string, steam_id in steam_ids.items():
        games = web_api.IPlayerService.GetOwnedGames(
            steamid=steam_id.as_64,
            include_played_free_games=True, appids_filter=[],
            include_appinfo=True)
        if not games['response']:
            users[user_string] = None
        else:
            users[user_string] = {}
            for game in games['response']['games']:
                appid = int(game['appid'])
                try:
                    db_entry = Game.objects.get(pk=appid)
                except Game.DoesNotExist as e:
                    db_entry = find_new_game(str(appid))
                    if db_entry is None:
                        continue
                if db_entry.is_multiplayer:
                    users[user_string][str(game['appid'])] = db_entry

    return users
    def __init__(self, user_strings, database):
        self.database = database

        self.steam_IDs = self.convert_to_steam_IDs(user_strings)
        print(self.steam_IDs)
        self.web_api = WebAPI(SteamLanGameFinder.api_key)
        self.users = self.create_user_games_list()
        self.combinations = self.create_combinations()
        self.filter_multiplayer()
Пример #5
0
def search(query=''):
    # Request
    # GET https://steamcommunity.com/search/SearchCommunityAjax

    fake_session = uuid.uuid4().hex
    try:
        response = requests.get(
            url="https://steamcommunity.com/search/SearchCommunityAjax",
            params={
                "text": query,
                "filter": "users",
                "sessionid": fake_session,
                "steamid_user": "******",
                "page": "1",
            },
            headers={
                "Host": "steamcommunity.com",
                "Pragma": "no-cache",
                "Cookie": "sessionid=" + fake_session,
                "Content-Type":
                "multipart/form-data; charset=utf-8; boundary=__X_PAW_BOUNDARY__",
                "Referer": "https://steamcommunity.com/search/users/",
            },
            files={},
        )
        response = json.loads(response.content.decode())

        html = etree.HTML(response['html'])
        results = CSSSelector('div.search_row')
        credentials = CSSSelector('a.searchPersonaName')
        image = CSSSelector('div.avatarMedium img')

        output = []

        api = WebAPI(settings.SOCIAL_AUTH_STEAM_API_KEY)
        for result in results(html):
            tmp = {}
            tmp['name'] = credentials(result)[0].text

            uri = credentials(result)[0].attrib['href']
            if '/id/' in uri:
                response = api.ISteamUser.ResolveVanityURL(
                    vanityurl=uri.split('/id/')[-1], url_type=1)
                tmp['url'] = response['response']['steamid']
            else:
                tmp['url'] = uri.split('/profiles/')[-1]

            tmp['image'] = image(result)[0].attrib['src']
            output.append(tmp)

        return output
    except requests.exceptions.RequestException:
        print('HTTP Request failed')
        return ''
Пример #6
0
def get_persona_name(steam_id):
    """ Attempts to get persona name of steam user. """
    if isinstance(steam_id, SteamID):
        env = environ.Env()
        web_api = WebAPI(env('STEAM_API_KEY'))

        content = web_api.ISteamUser.GetPlayerSummaries(
            steamids=steam_id.as_64)
        try:
            persona_name = content["response"]["players"][0]["personaname"]
            return "_".join([persona_name, str(steam_id.as_64)])
        except Exception as e:
            print(e)
            return None
    else:
        return None
Пример #7
0
    async def get_steam_client(self,
                               ctx: commands.Context) -> Union[WebAPI, None]:
        key = await self.config.steamkey()

        if not key:
            await ctx.send(
                f"Sorry, you need a Steam API key to make requests to Steam. Use `{ctx.prefix}game steamkey` for more information."
            )
            return

        try:
            steam_client = WebAPI(key=key)
        except OSError:
            await ctx.send(
                f"There was an error connecting to Steam. Either the provided Steam key is invalid, or try again later."
            )
            return

        return steam_client
Пример #8
0
    def create_or_login(resp):
        """Callback fired after steam login, log user in the application.

        Args:
            resp: OpenID response.
        Returns:
            Index page after login.
        """
        match = _steam_id_re.search(resp.identity_url)
        steam_id = int(match.group(1))

        user = User.get_or_create(steam_id)

        api = WebAPI(key=current_app.config['STEAM_KEY'])
        resp=api.ISteamUser.GetPlayerSummaries_v2(steamids=steam_id)
        user.avatar = resp['response']['players'][0]['avatar']
        user.avatar_medium = resp['response']['players'][0]['avatarmedium']
        user.avatar_full = resp['response']['players'][0]['avatarfull']
        db.session.commit()

        login_user(user, remember=True)
        return redirect(url_for('index'))
Пример #9
0
    def accept_gifts(self):
        gifts = self.web_account.get_pending_gifts()

        if type(gifts) == enums.WebAccountResult:
            log.error(
                u'Could not accept pending gifts. Received {}'.format(repr(gifts))
            )

            return gifts

        log.info(u'Found {0} pending gifts'.format(len(gifts)))

        for gift in gifts:
            if not gift.gift_javascript:
                log.error(u'Unable to find gift javascript object')

                continue

            matches = re.findall(
                r'BuildHover\( .*, ({.*}), .*\)',
                gift.gift_javascript,
                re.DOTALL
            )

            if not len(matches):
                log.error(u'Regex failed to retrieve gift javascript object')

                continue

            gift_object = json.loads(matches[0])

            log.info(
                u'Found pending gift {0} from {1} ({2})'.format(
                    gift_object.get('name'),
                    gift.from_username,
                    gift.from_link
                )
            )

            match = re.match(
                r'^https?://steamcommunity.com/(?P<type>profiles|id|gid|groups)/(?P<value>.*)/?$',
                gift.from_link
            )

            if not match:
                log.error(u'Could not match steamcommunity URL from {}'.format(gift.from_link))

                continue

            if match.group('type') == 'profiles':
                sender_steam_id = match.group('value')
            else:
                api = WebAPI(backend_config.STEAM_API_KEY)

                api_result = api.call(
                    'ISteamUser.ResolveVanityURL',
                    vanityurl=match.group('value'),
                    url_type=1,
                    format='json'
                )

                if (
                    not api_result.get('response') or
                    api_result.get('response').get('success') != 1
                ):
                    log.error(
                        u'Unable to resolve sender steamid, ResolveVanityURL returned {}'.format(
                            api_result
                        )
                    )

                    continue
                else:
                    sender_steam_id = api_result.get('response').get('steamid')

            if not gift.accept_button or 'UnpackGift' in gift.accept_button:
                log.info(u'Gift cannot be accepted to inventory')

                log.info(
                    u'Declining gift id {0} to sender id {1}'.format(
                        gift_object.get('id'),
                        sender_steam_id
                    )
                )

                result = self.web_account.decline_gift(
                    gift_object.get('id'),
                    sender_steam_id
                )

                if result != EResult.OK:
                    log.error(
                        u'Could not accept gift id {0}. Received {1}'.format(
                            gift_object,
                            repr(result)
                        )
                    )

            elif 'ShowAcceptGiftOptions' in gift.accept_button:
                log.info(
                    u'Accepting gift id {0} to gift inventory'.format(
                        gift_object.get('id')
                    )
                )

                result = self.web_account.accept_gift(
                    gift_object.get('id'),
                    sender_steam_id
                )

                if result != EResult.OK:
                    log.error(
                        u'Could not accept gift id {0}. Received {1}'.format(
                            gift_object,
                            repr(result)
                        )
                    )
Пример #10
0
import datetime
import natural.date
import humanize
from steam import WebAPI, SteamID
from django.conf import settings
from django.template.defaulttags import register

api = WebAPI(key=settings.SOCIAL_AUTH_STEAM_API_KEY)


@register.filter
def as32(value):
    return SteamID(value).as_32


@register.filter
def as2(value):
    return SteamID(value).as_steam2


@register.filter
def as3(value):
    return SteamID(value).as_steam3


@register.filter
def vac(value):
    ban = api.ISteamUser.GetPlayerBans(steamids=value)['players'][0]
    if ban['VACBanned']:
        return "currently banned"
    elif ban['DaysSinceLastBan'] == 0:
Пример #11
0
def get_profiles(steamid):
    ids = ""
    # if arg is string, expect single steam64id
    if type(steamid) == str:
        ids = steamid
    # if arg is int, generate n random steam64ids
    elif type(steamid) == int:
        # [NEEDS IMPROVED]
        # this isn't random, nor conclusive method of generating steamids
        for i in range(0, steamid):
            ids = ids + ",%s" % SteamID(id=randint(1, 1000000000),
                                        type="Individual",
                                        universe="Public",
                                        instance=1).as_64
    # get player info via steam WebAPI (100 max)
    s_api_key = environ['STEAM_API_KEY']
    steam_api = WebAPI(key=s_api_key)
    players = steam_api.call('ISteamUser.GetPlayerSummaries',
                             steamids=ids)['response']['players']
    # return empty profile only for single steamid scan
    if not players and len(steamid) == 17:
        # empty profile
        p = Profile(steamid, 0, 0, 0, 0, 0, 0)
        p.steamid_found = False
        return [p]
    # build profile objects
    profiles = []
    for p in players:
        try:
            # profile is configured
            state = p["profilestate"]
        except:
            # profile is not configured
            state = 0
        try:
            # this attribute is missing from some profiles, unsure why
            tc = p["timecreated"]
        except:
            # handle gracefully
            tc = 0
        try:
            # create profile object
            profiles.append(
                Profile(p["steamid"], p["communityvisibilitystate"], state,
                        p["personaname"], p["profileurl"], p["avatar"], tc))
        except Exception as e:
            # if no steam64id, discard
            if str(e) == "'steamid'":
                continue
    # if profile is configured and public
    for p in profiles:
        if p.profilestate == 1 and p.communityvisibilitystate == 3:
            # get attributes from community profile
            p.summary, p.vacBanned, p.tradeBanState, p.links = get_community_profile(
                p.steamid)
    # commit profiles to db
    for p in profiles:
        db = connect_db()
        db.execute(
            "INSERT INTO profiles (steamid, communityvisibilitystate, profilestate, personaname, profileurl, avatar, timecreated, summary, vacBanned, tradeBanState) "
            "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) "
            "ON DUPLICATE KEY UPDATE updated_at=NOW()",
            (p.steamid, p.communityvisibilitystate, p.profilestate,
             p.personaname, p.profileurl, p.avatar, p.timecreated, p.summary,
             p.vacBanned, p.tradeBanState))
        db.close()
    return profiles
Пример #12
0
import xml.etree.ElementTree as etree

from discord.ext import commands
from steam import WebAPI
from steam import SteamID
from steam.enums import EPersonaState
from utils.config import Config
from utils.tools import *
from utils import checks
from datetime import datetime
config = Config()

steamAPI = WebAPI(config._steamAPIKey)


class Steam():
    def __init__(self, bot):
        self.bot = bot

    @commands.command(hidden=True)
    @checks.is_dev()
    async def steamdebug(self, ctx, *, shit: str):
        """This is the part where I make 20,000 typos before I get it right"""
        # "what the f**k is with your variable naming" - EJH2
        # seth seriously what the f**k - Robin
        import asyncio
        import os
        import random
        import re
        from datetime import datetime, timedelta
        try:
Пример #13
0
async def csgo(cmd, message, args):
    if not args:
        return
    csgo_input = ' '.join(args)

    try:
        api = WebAPI(SteamAPI)
        userID = api.call('ISteamUser.ResolveVanityURL',
                          vanityurl=csgo_input,
                          url_type=1)['response']['steamid']
        stats = api.call('ISteamUserStats.GetUserStatsForGame',
                         steamid=userID,
                         appid='730')['playerstats']['stats']
        summary = api.call('ISteamUser.GetPlayerSummaries',
                           steamids=userID)['response']['players'][0]

        nickname = str(summary['personaname'])
        avatar_url = str(summary['avatarfull'])
        v = 'value'
        n = 'name'
        stat_bases = {
            "total_kills": 0,
            "total_deaths": 0,
            "total_time_played": 0,
            "total_kills_knife": 0,
            "total_kills_headshot": 0,
            "total_shots_fired": 0,
            "total_shots_hit": 0,
            "total_rounds_played": 0,
            "total_mvps": 0,
            "total_matches_won": 0,
            "total_matches_played": 0
        }

        for stat in stats:
            nam = stat[n]
            val = stat[v]
            if nam in stat_bases:
                stat_bases[nam] = val

        kdr = stat_bases['total_kills'] / stat_bases['total_deaths']
        accuracy = stat_bases['total_shots_hit'] / stat_bases[
            'total_shots_fired']
        total_matches_lost = stat_bases['total_matches_played'] - stat_bases[
            'total_matches_won']
        win_percent = stat_bases['total_matches_won'] / stat_bases[
            'total_matches_played']

        data = {
            'Playtime':
            str(stat_bases['total_time_played'] // 3600) + ' Hours',
            'Kills': str(stat_bases['total_kills']),
            'Deaths': str(stat_bases['total_deaths']),
            'Kill/Death Ratio': "{0:.2f}".format(kdr),
            'Shots Fired': str(stat_bases['total_shots_fired']),
            'Shots Hit': str(stat_bases['total_shots_hit']),
            'Accuracy': "{0:.2f}".format(accuracy * 100) + '%',
            'Headshots': str(stat_bases['total_kills_headshot']),
            'Knife Kills': str(stat_bases['total_kills_knife']),
            'Rounds Played': str(stat_bases['total_rounds_played']),
            'Total MVPs': str(stat_bases['total_mvps']),
            'Matches Played': str(stat_bases['total_matches_played']),
            'Matches Won': str(stat_bases['total_matches_won']),
            'Matches Lost': str(total_matches_lost),
            'Win Percentage': "{0:.2f}".format(win_percent * 100) + '%'
        }
        embed = discord.Embed(color=0x1ABC9C)
        embed.set_author(name=nickname, icon_url=avatar_url, url=avatar_url)
        for unit in data:
            embed.add_field(name=unit, value=data[unit])
        await cmd.bot.send_message(message.channel, None, embed=embed)

    except Exception as e:
        cmd.log.error(e)
        await cmd.bot.send_message(
            message.channel, 'Something went wrong or the user was not found.')
Пример #14
0
from steam import SteamID
from steam import WebAPI
from keys import steamKey
import re


STEAM_API_KEY = WebAPI(steamKey)

def idMapping(identifier):
    
    if identifier == None:
        return None
    
    elif re.match(r"https://steamcommunity\.com/id/[^/]+/",
         identifier) != None:
        return SteamID.from_url(identifier)

    elif re.match(r"https://steamcommunity\.com/profiles/[^/]+/",
         identifier) != None:
        return SteamID(identifier[36:-1])
    
    elif re.match(r"\d+", identifier) != None:
        return SteamID(identifier)

    elif re.match(r"\w+", identifier) != None:
        return SteamID.from_url("https://steamcommunity.com/id/" + identifier)

    else:
        return None

Пример #15
0
from rest_framework import viewsets
from steam import WebAPI

from .models import Game
from .serializers import GameSerializer

# TODO move variable to env
api = WebAPI(key='1AD897533C698E617B4F351C640EC53E')
res = api.IPlayerService.GetOwnedGames(key='1AD897533C698E617B4F351C640EC53E',
                                       steamid='76561198080321262',
                                       include_appinfo=True,
                                       include_free_sub=False,
                                       include_played_free_games=True,
                                       appids_filter=[])

games = res.get('response').get('games')

for game in games:
    appid = game.get('appid')
    defaults = {
        'name':
        game.get('name'),
        'appid':
        appid,
        'playtime_forever':
        game.get('playtime_forever'),
        'icon_url':
        f'http://media.steampowered.com/steamcommunity/public/images/apps/{appid}/{game.get("img_icon_url")}.jpg',
        'logo_url':
        f'http://media.steampowered.com/steamcommunity/public/images/apps/{appid}/{game.get("img_logo_url")}.jpg'
    }
Пример #16
0
    def getGlobalAchievementPercentagesForApp(self):

        self.globalAchievements = api.ISteamUserStats.GetGlobalAchievementPercentagesForApp(
            gameid=self.appID)['achievementpercentages']['achievements']
        return self.globalAchievements

    def getSchemaForGame(self):

        self.schemaForGame = api.ISteamUserStats.GetSchemaForGame(
            appid=self.appID)
        return self.schemaForGame


##############
api = WebAPI(apiKey)
##############

### Testing GetGameInfo() ####

getGameInfo = GetGameInfo(480490)
print getGameInfo.getNumberofCurrentPlayers()
# print getGameInfo.getGlobalAchievementPercentagesForApp()
# print getGameInfo.getSchemaForGame()

#### Testing GetProfileInfo() ####

getSteamID = getSteamID()
corvoID = getSteamID.fromURL('http://steamcommunity.com/id/kaf/')
corvoProfileInfo = GetProfileInfo(corvoID)
print corvoProfileInfo.getUserStatsforGame(730)
Пример #17
0
dota = Dota2Client(client)

OPEN_SPEED = 0.2

api_key = ''
api = ''

print("\n\nDue to limitations imposed by valve (f**k you skin gambling) you will need:")
print("\t1. An API KEY")
print("\t2. Your profile and inventory temporarily set to public")
print("API keys can be optained easily from: http://steamcommunity.com/dev/apikey\n\n")

while True:
    api_key = input("Enter your API key: ")
    try:
        api = WebAPI(key = api_key)
        break
    except:
        print("invalid key")

print("You will now be prompted to log in. You will not see any input when entering password.")

@client.on('logged_on')
def start_dota():
    print("Logged into steam, starting dota")
    dota.launch()
    pass

@dota.on('ready')
def ready0():
    print("Preparing to open.\nSometimes, if requests are recieved too fast they will be ignored.\nThe bot will go through several iterations to open all of them")
Пример #18
0
from steam import WebAPI
from steam import steamid
import valve.source.a2s

api = WebAPI("YOUR STEAM KEY GOES HERE")

SERVER_USERS = []
POSSIBLE_GROUP = []


def compareGroups(friend_info, server_users):
    # Checks for similar names player's friends and server's users

    print("[+] Comparing data.")

    group = {}

    for name in friend_info.keys():
        if name in server_users:
            print("[-] Found relationship with {}.".format(name))
            group[name] = friend_info[name]

    if len(group) is 0:
        print("[-] Found no relationships.")
        return

    return group

def getPlayerInfo(id):
    # Get player information from a URL
Пример #19
0
from steam import SteamID, WebAPI
import requests
import ast

allUsersGames = {}
i = 0
successes = []
failures = []

api = WebAPI(key="XXX")

allUsersGamesInfo = api.IPlayerService.GetOwnedGames(include_appinfo=True, appids_filter=100, include_played_free_games=True, steamid="XXX")

def helperSingleAppId(appId):
    requestURL = "https://store.steampowered.com/api/appdetails?appids=" + appId
    gameInfo = requests.get(requestURL)
    print(gameInfo)
    print(str(gameInfo.status_code))
    print(gameInfo.json())
    print(type(gameInfo.json()))
    if gameInfo.json() is None:
        print("its none")
    if gameInfo.json()[str(appId)]['success'] is True:
        print("its not none")
    print(gameInfo.json()[str(appId)]['data']['genres'])

helperSingleAppId("XXX")


i=1
for game in allUsersGamesInfo['response']['games']:
Пример #20
0
async def csgo(cmd, message, args):
    csgo_input = ' '.join(args)

    try:
        api = WebAPI(SteamAPI)
        userID = api.call('ISteamUser.ResolveVanityURL', vanityurl=csgo_input, url_type=1)['response']['steamid']
        stats = api.call('ISteamUserStats.GetUserStatsForGame', steamid=userID, appid='730')['playerstats']['stats']
        summary = api.call('ISteamUser.GetPlayerSummaries', steamids=userID)['response']['players'][0]

        nickname = str(summary['personaname'])
        v = 'value'
        n = 'name'
        total_kills = 0
        total_deaths = 0
        total_time_played = 0
        total_kills_knife = 0
        total_kills_headshot = 0
        total_shots_fired = 0
        total_shots_hit = 0
        total_rounds_played = 0
        total_mvps = 0
        total_matches_won = 0
        total_matches_played = 0

        for stat in stats:
            nam = stat[n]
            val = stat[v]
            if nam == 'total_kills':
                total_kills = val
            elif nam == 'total_deaths':
                total_deaths = val
            elif nam == 'total_time_played':
                total_time_played = val
            elif nam == 'total_kills_knife':
                total_kills_knife = val
            elif nam == 'total_kills_headshot':
                total_kills_headshot = val
            elif nam == 'total_shots_fired':
                total_shots_fired = val
            elif nam == 'total_shots_hit':
                total_shots_hit = val
            elif nam == 'total_rounds_played':
                total_rounds_played = val
            elif nam == 'total_mvps':
                total_mvps = val
            elif nam == 'total_matches_won':
                total_matches_won = val
            elif nam == 'total_matches_played':
                total_matches_played = val

        kdr = total_kills / total_deaths
        accuracy = total_shots_hit / total_shots_fired
        total_matches_lost = total_matches_played - total_matches_won
        win_percent = total_matches_won / total_matches_played

        out = '```haskell'
        out += '\nNickname: ' + nickname
        out += '\nPlaytime: ' + str(total_time_played // 3600) + ' Hours'
        out += '\nKills: ' + str(total_kills)
        out += '\nDeaths: ' + str(total_deaths)
        out += '\nKill/Death Ratio: ' + "{0:.2f}".format(kdr)
        out += '\nShots Fired: ' + str(total_shots_fired)
        out += '\nShots Hit: ' + str(total_shots_hit)
        out += '\nAccuracy: ' + "{0:.2f}".format(accuracy * 100) + '%'
        out += '\nHeadshots: ' + str(total_kills_headshot)
        out += '\nKnife Kills: ' + str(total_kills_knife)
        out += '\nRounds Played: ' + str(total_rounds_played)
        out += '\nTotal MVPs: ' + str(total_mvps)
        out += '\nMatches Played: ' + str(total_matches_played)
        out += '\nMatches Won: ' + str(total_matches_won)
        out += '\nMatches Lost: ' + str(total_matches_lost)
        out += '\nWin Percentage: ' + "{0:.2f}".format(win_percent * 100) + '%'
        out += '\n```'

        await cmd.bot.send_message(message.channel, out)

    except Exception as e:
        cmd.log.error(e)
        await cmd.bot.send_message(message.channel, 'Something went wrong or the user was not found.')
Пример #21
0
import asyncio
import xml.etree.ElementTree as etree

from discord.ext import commands
from steam import WebAPI
from steam import SteamID
from steam.enums import EPersonaState
from utils.config import Config
from utils.logger import log
from utils.tools import *
from utils import checks
config = Config()

steamAPI = WebAPI(config._steam_key)

steamapikey = config._steam_key

try:
    api = WebAPI(key=steamapikey)
    log.info("Logged in to Steam via API Key")
except Exception as e:
    log.error("Error!\n" + e)


class Steam(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def steamprofile(self, ctx, communityid: str):
        """Gets steam profile information on a user with the specified community ID"""
Пример #22
0
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
import django.contrib.auth as auth

from django.contrib import messages

from django.conf import settings

from vapor.models import UserProfile, Player
from vapor.data import scrap_for_new_user
import vapor.tasks

from steam import WebAPI
import sqlite3

api = WebAPI(key = settings.STEAM_API_KEY)

def data_ready_reaquired(view):
    def decorated(request, *args, **kwargs):
        profile = UserProfile.objects.get(user=request.user)
        if profile.data_ready == 0:
            return redirect('vapor:setup')
        else:
            return view(request, *args, **kwargs)
    return decorated

def login(request):
    if request.user.is_authenticated():
        return redirect(reverse('vapor:home'))
    else:
        return render(request, 'login.html', {})
Пример #23
0
import logging
import os
import re
import sys

from steam import WebAPI
from common import EPSILON, STEAM, STEAM_WORKSHOP_URL, STEAM_WORKSHOP_PARAMS
from commands import ModRequest

log = logging.getLogger(__name__)

_api = WebAPI(key=STEAM['key'])
_mod_url = "https://steamcommunity.com/sharedfiles/filedetails/?id={}"

_params = {
    # the parts that we're interested in
    "search_text": "",  # required
    "requiredtags": [],  # required
    "numperpage": 1,  # optional

    # static 'settings'
    "query_type":
    3,  # required, this corresponds to the 'relevance' search mode.
    "return_tags":
    True,  # required, we want to get tags back so we can show the Alpha number.
    "appid": STEAM_WORKSHOP_PARAMS['appid'],  # required
    "creator_appid": STEAM_WORKSHOP_PARAMS['appid'],  # required
    "match_all_tags": True,  # optional
    "cache_max_age_seconds": 0,  # optional

    # stuff we don't use, but the API requires