예제 #1
0
def getSteamLibrary(apiKey: str, steamID: int) -> list:
    try:
        api = WebAPI(apiKey, https=True)
    except HTTPError:
        raise PermissionError("403 Client Error: Forbidden.\nWrong API key?")
    else:
        games = api.call("IPlayerService.GetOwnedGames",
                         steamid=steamID,
                         include_appinfo=1,
                         include_played_free_games=1,
                         include_free_sub=0,
                         appids_filter="name")
        if len(games["response"]) == 0:
            raise ValueError("No games found. Wrong SteamID?")
        else:
            gamelist = []
            for game in games["response"]["games"]:
                gamelist.append({
                    "platform": "Steam",
                    "name": game["name"],
                    "region": "Steam",
                    "code": str(game["appid"]),
                    "game": "Yes",
                    "box": "Yes",
                    "manual": "Yes",
                    "year": "",
                    "genre": "",
                    "comment": "",
                    "publisher": "",
                    "developer": "",
                    "platforms": "",
                    "price": "$0,$0,$0,$0"
                })

            return gamelist
예제 #2
0
def main(writer, api_key, ids):
    api = WebAPI(api_key)

    users = [get_user_summary(api, id_) for id_ in ids]

    user_games = {user["steamid"]: [(g["appid"], g["name"]) for g in get_owned(api, user["steamid"])] for user in users}
    game_set = list(set(g for games in user_games.values() for g in games))
    game_prices = {}
    for game_chunk in chunks(game_set, 100):
        game_prices.update({p[0]: p[1] for p in get_prices([str(g[0]) for g in game_chunk])})

    ownership = [[
        gid,
        [gid in user_games[user["steamid"]] for user in users]
    ] for gid in game_set]

    exportable = [
        [r[0][1], game_prices.get(str(r[0][0]), "???"), *r[1]]
        for r in ownership
    ]

    writer.writerows([
        ["Game Name", "Current Price",
         *[f"{user['personaname']} ({user.get('realname', 'Mr. Mystery')}) owns" for user in users]]
    ])
    writer.writerows(exportable)
예제 #3
0
def compare_games(api_key, steam_ids):
    def get_intersection(lists):
        app_ids = set(lists[0].keys())
        for l in lists[1:]:
            app_ids = app_ids.intersection(set(l.keys()))
        return app_ids

    def get_playtimes_for_appid(appid, game_lists):
        return [l[appid]['playtime'] for l in game_lists]

    api = WebAPI(key=api_key)
    game_lists = []
    for s_id in steam_ids:
        game_lists.append(get_games_list_from_steamid(api, s_id))

    overlap = get_intersection(game_lists)

    playtimes = {
        appid: get_playtimes_for_appid(appid, game_lists)
        for appid in overlap
    }

    overlap_games = {
        appid: {
            'name': game_lists[0][appid]['name'],
            'playtime': playtimes[appid]
        }
        for appid in overlap
    }
    return overlap_games
예제 #4
0
def get_player_has_bans(steamd_id):
    if not STEAM_KEY:
        return None

    try:
        api = WebAPI(key=STEAM_KEY)
        bans = api.ISteamUser.GetPlayerBans(steamids=steamd_id)['players'][0]
    except AttributeError:
        logger.error("STEAM_API_KEY is invalid, can't fetch steam profile")
        return None
    except IndexError:
        logger.exception("Steam no player found")
        return None
    except:
        logging.exception('Unexpected error while fetching steam profile')
        return None

    if not bans:
        bans = {}

    bans['has_bans'] = any(
        bans.get(k) for k in [
            'VACBanned', 'NumberOfVACBans', 'DaysSinceLastBan',
            'NumberOfGameBans'
        ])
    return bans
예제 #5
0
def get_owned(api: WebAPI, steamid: str):
    return api.call(
        "IPlayerService.GetOwnedGames",
        steamid=steamid,
        include_appinfo=True,
        include_played_free_games=False,
        appids_filter=[],
        include_free_sub=False
    )["response"]["games"]
예제 #6
0
def get_steam_profile(steamd_id):
    if not STEAM_KEY:
        return None
    try:
        api = WebAPI(key=STEAM_KEY)
        return api.ISteamUser.GetPlayerSummaries(steamids=steamd_id)["response"]["players"][0]
    except AttributeError:
        logger.error("STEAM_API_KEY is invalid, can't fetch steam profile")
        return None
    except IndexError:
        logger.exception("Steam: no player found")
    except:
        logging.exception('Unexpected error while fetching steam profile')
        return None
예제 #7
0
class TCwebapi(unittest.TestCase):
    @test_vcr.use_cassette('webapi.yaml')
    def setUp(self):
        self.api = WebAPI(test_api_key)
        self.api.session.headers['Accept-Encoding'] = 'identity'

    def test_docs(self):
        self.assertTrue(len(self.api.doc()) > 0)

    @test_vcr.use_cassette('webapi.yaml')
    def test_simple_api_call(self):
        resp = self.api.ISteamWebAPIUtil.GetServerInfo_v1()
        self.assertTrue('servertime' in resp)

    @test_vcr.use_cassette('webapi.yaml')
    def test_simple_api_call_vdf(self):
        resp = self.api.ISteamWebAPIUtil.GetServerInfo(format='vdf')
        self.assertTrue('servertime' in resp['response'])

    @test_vcr.use_cassette('webapi.yaml')
    def test_resolve_vanity(self):
        resp = self.api.ISteamUser.ResolveVanityURL(vanityurl='valve', url_type=2)
        self.assertEqual(resp['response']['steamid'], '103582791429521412')

    @test_vcr.use_cassette('webapi.yaml')
    def test_post_publishedfile(self):
        resp = self.api.ISteamRemoteStorage.GetPublishedFileDetails(itemcount=5, publishedfileids=[1,1,1,1,1])
        self.assertEqual(resp['response']['resultcount'], 5)

    @test_vcr.use_cassette('webapi.yaml')
    def test_get(self):
        resp = webapi.get('ISteamUser', 'ResolveVanityURL', 1,
                           session=self.api.session, params={
                               'key': test_api_key,
                               'vanityurl': 'valve',
                               'url_type': 2,
                               })
        self.assertEqual(resp['response']['steamid'], '103582791429521412')

    @test_vcr.use_cassette('webapi.yaml')
    def test_post(self):
        resp = webapi.post('ISteamRemoteStorage', 'GetPublishedFileDetails', 1,
                           session=self.api.session, params={
                               'key': test_api_key,
                               'itemcount': 5,
                               'publishedfileids': [1,1,1,1,1],
                               })
        self.assertEqual(resp['response']['resultcount'], 5)
예제 #8
0
def get_player_bans(steamd_id):
    if not STEAM_KEY:
        return None

    try:
        api = WebAPI(key=STEAM_KEY)
        bans = api.ISteamUser.GetPlayerBans(steamids=steamd_id)['players'][0]
    except AttributeError:
        logger.error("STEAM_API_KEY is invalid, can't fetch steam profile")
        return None
    except IndexError:
        logger.exception("Steam no player found")
        return None
    except:
        logging.exception('Unexpected error while fetching steam profile')
        return None

    if not bans:
        bans = {}
    return bans
예제 #9
0
class Connector:
    def __init__(self):
        self.api = WebAPI(STEAM_KEY)

    def get_list(self) -> Iterator[dict]:

        # TODO: c'e' modo di escludere schifezze tipo i mod, le beta, e anche i film?

        res = self.api.call("IPlayerService.GetOwnedGames",
                            steamid=STEAM_PLAYER_ID,
                            include_appinfo=True,
                            include_played_free_games=True,
                            appids_filter=None)

        # TODO: gestire fallimento

        for game in res['response']['games']:
            yield {
                'service': Service.STEAM,
                'key': str(game['appid']),
                'name': game['name'],
                'validation': Validation.TODO
            }
def main():
    # check whether ASF config is there
    if os.path.exists(PATH_TO_ASF_CONFIG_FILE):
        ASF_config = ASFConfig(PATH_TO_ASF_CONFIG_FILE)
        api = WebAPI(key=STEAM_API_KEY)
        # print(api.ISteamUser.GetPlayerSummaries(steamids=steam_id))

        # if the ownedGames.json is not there, create and cache it
        if not os.path.exists(PATH_TO_OWNED_GAMES_DATA):
            print("ownedGames.json does not exist. Creating new file ...")
            owned_games_data = api.IPlayerService.GetOwnedGames(steamid=STEAM_ID,
                                                                include_appinfo=True,
                                                                include_played_free_games=False,
                                                                appids_filter=[],
                                                                include_free_sub=False)
            with open(PATH_TO_OWNED_GAMES_DATA, 'w') as outfile:
                json.dump(owned_games_data, outfile, sort_keys=True, indent=4)
        else:
            print("Reading data from OwnedGames.json")
            with open(PATH_TO_OWNED_GAMES_DATA) as f2:
                owned_games_data = json.load(f2)

        # get random 32 games
        random_games_list = random.sample(owned_games_data['response']['games'], 32)

        # get random 32 appids
        random_appid_list = []
        print("\nList of games that will be idling:")
        for random_game in random_games_list:
            random_appid_list.append(random_game['appid'])
            print(str(random_game['appid']) + ": " + random_game['name'])

        ASF_config.update_GamesPlayedWhileIdle(random_appid_list)

    else:
        print("Path to the ASF config file is not valid, please quit and change config.json")
        print("Current path: " + PATH_TO_ASF_CONFIG_FILE)
예제 #11
0
 def __init__(self):
     self.api = WebAPI(STEAM_KEY)
예제 #12
0
import xml.etree.ElementTree as etree

from discord.ext import commands
from steam.webapi import WebAPI
from steam.steamid 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(commands.Cog):
    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
파일: main.py 프로젝트: erplsf/sfcg
if __name__ == "__main__":
    save = questionary.confirm(
        default=True, message="Save your input to a cache file?").ask()
    pre_username = load_from_cache('username')
    pre_password = load_from_cache('password')
    pre_selected_friends = load_from_cache('selected_friends')
    username = questionary.text(default=pre_username,
                                message="Your Steam username?").ask()
    password = questionary.password(default=pre_password,
                                    message="Your Steam password?").ask()
    if save:
        merge_to_cache({'username': username, 'password': password})
    cl = SteamClient()
    cl.set_credential_location('.')
    cl.cli_login(username=username, password=password)
    api = WebAPI(key=fetch_web_api_key(cl))
    friends = list(
        fetch_friends(cl)
    )  # we need to listify it, to be able to use it twice. TODO: Investigate how to clone generator/iterator?

    loop = True

    while loop:
        pre_selected_friends = load_from_cache('selected_friends')
        qfriends = list(
            questionize_friends(deepcopy(friends), pre_selected_friends))
        selected_friends = questionary.checkbox('Select friends to compare',
                                                choices=qfriends).ask()

        if save:
            merge_to_cache({'selected_friends': selected_friends})
예제 #14
0
    async def getSteamPartnerAPIInstance(self, guild):
        steamKey = await self.config.guild(guild).steamWebAPIKey()
        if (steamKey is None):
            return None

        return WebAPI(key=steamKey, apihost=APIHost.Partner)
예제 #15
0
def get_user_summary(api: WebAPI, steamid: str):
    return api.call(
        "ISteamUser.GetPlayerSummaries",
        steamids=steamid
    )["response"]["players"][0]
예제 #16
0
import datetime
import difflib
import re
import os
import requests
import nltk
import asyncio
from hashashin.search import SteamSearch
import locale
import random

nltk.download('punkt')

STEAM_KEY = os.environ.get("STEAM_KEY")

api = WebAPI(key=STEAM_KEY)

component = tanjun.Component()


@component.with_slash_command
@tanjun.with_str_slash_option("game", "The name of the game.")
@tanjun.as_slash_command("search", "Search for a game.")
async def command_search(ctx: tanjun.abc.SlashContext, game: str) -> None:

    results = await SteamSearch(game)

    appID = results[0]

    await _game_embed(ctx, appID)
예제 #17
0
 def __init__(self):
     self.api = WebAPI(key=config['steam_api_key'])
예제 #18
0
def call_steamapi(*args, **kwargs):
    """Perform Steam API call"""
    api = WebAPI(key=args[0])
    return api.call(args[1], **kwargs)
예제 #19
0
def steam_get(link):
    mod_id = link.split('=')[1].split('&')[0]
    z = WebAPI(key=s['key']).ISteamRemoteStorage.GetPublishedFileDetails(
        itemcount=1, publishedfileids=[mod_id])
    return ctime(z['response']['publishedfiledetails'][0]['time_updated'])
예제 #20
0
def cli(validate, username, password, config, no_update, _setup):
    # Check yaml existence
    if _setup:
        setup(config)
    elif not os.path.isfile(config):
        if click.confirm(
                'No configuration file detected, do you wish to create a new one'
        ):
            setup(config)
        else:
            config = click.prompt('Enter path to a3update.yaml',
                                  type=click.Path(exists=True,
                                                  readable=True,
                                                  resolve_path=True))

    with click.open_file(config, 'r') as file:
        global CONFIG_YAML
        CONFIG_YAML = yaml.safe_load(file)

    # Login to SteamCMD and WebAPI
    _log("Checking SteamCMD install")
    global STEAM_CMD
    STEAM_CMD = SteamCMD(CONFIG_YAML['steamcmd_dir'])
    try:
        STEAM_CMD.install()
    except SteamCMDException:
        click.echo("SteamCMD installed")
    STEAM_CMD.login(username, password)
    global STEAM_WEBAPI
    STEAM_WEBAPI = WebAPI(key=CONFIG_YAML['api_key'], https=False)

    # Load constants
    global WORKSHOP_DIR
    WORKSHOP_DIR = CONFIG_YAML['mod_dir_full']
    global INSTALL_DIR
    INSTALL_DIR = CONFIG_YAML['install_dir']
    global KEY_PATH
    KEY_PATH = os.path.join(INSTALL_DIR, 'keys')
    global EXTERNAL_ADDON_DIR
    EXTERNAL_ADDON_DIR = CONFIG_YAML['external_addon_dir']

    # Update apps (Arma 3 Dedicated Server, CDLCs)
    _log('Updating Arma 3 Server')
    if not no_update:
        beta = CONFIG_YAML['beta']
        if beta:
            STEAM_CMD.app_update(CONFIG_YAML['server_appid'], INSTALL_DIR,
                                 validate, beta)
        else:
            STEAM_CMD.app_update(CONFIG_YAML['server_appid'], INSTALL_DIR,
                                 validate)

    # Update mods
    _log('Updating mods')
    for filename in os.listdir(INSTALL_DIR):
        if filename.startswith('@'):
            shutil.rmtree(os.path.join(INSTALL_DIR, filename))

    if CONFIG_YAML['handle_keys']:
        # Delete key symlinks
        for filename in os.listdir(KEY_PATH):
            f = os.path.join(KEY_PATH, filename)
            if os.path.islink(f):
                os.unlink(f)

    mods = _workshop_ids_to_mod_array(
        _get_collection_workshop_ids(CONFIG_YAML['collections']))
    with click.progressbar(mods, label='Mod update progress') as bar:
        for mod in bar:
            _log('Updating {}'.format(mod['name']))

            # Create symbolic links to keep files lowercase without renaming
            if not no_update:
                STEAM_CMD.workshop_update(ARMA_APPID,
                                          mod['published_file_id'],
                                          CONFIG_YAML['mod_dir'],
                                          validate,
                                          n_tries=25)
            path = os.path.join(WORKSHOP_DIR, mod['published_file_id'])
            _create_mod_link(path, os.path.join(INSTALL_DIR,
                                                mod['folder_name']))

            if CONFIG_YAML['handle_keys']:
                # Create key symlinks
                if not _create_key_links(path):
                    _log('WARN: No bikeys found for: {}'.format(mod['name']),
                         e=True)

    # Handle external addons
    if os.path.isdir(EXTERNAL_ADDON_DIR):
        for filename in os.listdir(EXTERNAL_ADDON_DIR):
            out_path = os.path.join(INSTALL_DIR, _filename(filename))
            if not os.path.exists(out_path):
                _create_mod_link(os.path.join(EXTERNAL_ADDON_DIR, filename),
                                 out_path)
            else:
                _log('ERR: Conflicting external addon "{}"'.format(filename),
                     e=True)

    if CONFIG_YAML['a3sync']['active']:
        from a3update import arma3sync
        _log('Building ArmA3Sync Repo')
        arma3sync.update(mods, CONFIG_YAML)
        _log('Finished building ArmA3Sync Repo')

    if CONFIG_YAML['html_preset']['active']:
        from a3update import html_preset
        _log('Generating Arma Launcher Preset')
        html_preset.generate(mods, CONFIG_YAML)
        _log('Finished generating Arma Launcher Preset')

    if CONFIG_YAML['swifty']['active']:
        from a3update import swifty
        _log('Building Swifty Repo')
        swifty.update(mods, CONFIG_YAML)
        _log('Finished building Swifty Repo')

    _log('Finished!')
예제 #21
0
def get_webapi():
    api = getattr(g, 'webapi', None)
    if api is None:
        g.api = api = WebAPI(current_app.config['STEAM_API_KEY'])
    return api
예제 #22
0
 def setUp(self):
     self.api = WebAPI(test_api_key)
     self.api.session.headers['Accept-Encoding'] = 'identity'
예제 #23
0
from steam.webapi import WebAPI

from Core import WARN_MSG

api = WebAPI("52C026F06AD673EDB37CE692D70B6889")


class SteamError(RuntimeError):
    pass


def BeginAuthSession(session_ticket):
    result = api.ISteamUserAuth.AuthenticateUserTicket(ticket=session_ticket,
                                                       appid=869380)
    response = result['response']
    if response['params']['result'] == 'OK':
        steam_id = response['params']['steamid']
        result = api.ISteamUser.GetPlayerSummaries(steamids=steam_id)
        return steam_id, result['response']['players'][0]['personaname']
    raise SteamError(f"Invalid session ticket {session_ticket}")


# print(dir(api.ISteamUser.GetFriendList()))
# r0 = api.call('ISteamUser.ResolveVanityURL', vanityurl="valve", url_type=2)
# r1 = api.ISteamUser.ResolveVanityURL(vanityurl="valve", url_type=2)
# r2 = api.ISteamUser.ResolveVanityURL_v1(vanityurl="valve", url_type=2)
# print(r0)
# print(r1)
# print(r2)
예제 #24
0
import os
from steam.steamid import SteamID
from steam.webapi import WebAPI

api = WebAPI(os.getenv("STEAM_API_KEY"))


def resolve_steam_vanity_url(handle):
    response = api.call("ISteamUser.ResolveVanityURL",
                        vanityurl=handle,
                        url_type=1)

    if response["response"]["success"] == 1:
        return SteamID(response["response"]["steamid"]).as_32
예제 #25
0
import os
from steam.webapi import WebAPI

steam_key = os.getenv('STEAM_KEY')
api = WebAPI(key=steam_key)

PERSONA_STATES = {
    0: 'оффлайн',
    1: 'онлайн',
    2: 'занят',
    3: 'ушел',
    4: 'спит',
    5: 'готов поторговаться',
    6: 'готов поиграть'
}


def get_user_data(name: str):
    try:
        data = api.call('ISteamUser.ResolveVanityURL', vanityurl=name)
        steam_id = data['response']['steamid']
        if (steam_id):
            return get_user_data_by_id(steam_id)
    except:
        return None


def get_user_data_by_id(user_id: int):
    try:
        data = api.call('ISteamUser.GetPlayerSummaries', steamids=user_id)
        steam_user = data['response']['players'][0]
from csgo_cheater_detection.config.config import \
 data_path, public_code, api_key
from csgo_cheater_detection.utils.functions import get_player_summaries

# parameters
data_path = data_path

# loading list of steamids
with open(f'{data_path}\\steamids.txt', 'rb') as fp:
    steamids = pickle.load(fp)

# convert a set to list for iteration
steamids = list(steamids)

# access
api = WebAPI(api_key)

# initiate index list
private_public_index = []

# loops to record status index
for steamid in tqdm(steamids):
    # get player account summaries and status
    summary = get_player_summaries(api=api, steamid=steamid)
    status = summary['response']['players']

    # skip to the next steam id if the profile is empty
    # record as false to remove when collecting data
    try:
        code = status[0]['communityvisibilitystate']
    except IndexError:
예제 #27
0
from importlib import import_module
from os import path, listdir
from steam.webapi import WebAPI
from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_openid import OpenID

app = Flask('fastdl', instance_relative_config=True)
app.config.from_object('fastdl.config')
app.config['UPLOAD_DIR'] = path.join(app.instance_path, 'uploads')
app.config.from_pyfile('fastdl.cfg')
app.config['UPLOAD_DIR'] = path.abspath(app.config['UPLOAD_DIR'])

for key in ['SECRET_KEY', 'SQLALCHEMY_DATABASE_URI', 'STEAM_API_KEY']:
    if key not in app.config:
        raise ValueError('Missing configuration key: ' + key)

login_manager = LoginManager(app)
db = SQLAlchemy(app)
openid = OpenID(app, stateless=True)
steam_api = WebAPI(app.config['STEAM_API_KEY'])

models = import_module('fastdl.models')
views = import_module('fastdl.views')
cli = import_module('fastdl.cli')