Git Product home page Git Product logo

steampy's Introduction

Steam Trade Offers Client for Python

PayPal Donate Button

Donate bitcoin: 3PRzESHsTVkCFK7osjwFGQLZjSf7qXP1Ta

steampy is a library for Python, inspired by node-steam-tradeoffers, node-steam and other libraries for Node.js. It was designed as a simple lightweight library, combining features of many steam libraries from Node.js into a single python module. steampy is capable of logging into steam, fetching trade offers and handling them in simple manner, using steam user credentials and SteamGuard file, or by passing sessionID and webCookie cookies. 'steampy' is also capable of using proxies. steampy is developed with Python 3 using type hints and many other features its supported for Windows, Linux and MacOs.

Table of Content

Installation

Requires python 3.8 at least

pip install steampy

Usage

Obtaining API Key

Obtaining SteamGuard from mobile device

Obtaining SteamGuard using Android emulation

** init(self, api_key: str, username: str = None, password: str = None, steam_guard: str = None, login_cookies: dict = None, proxies: dict = None) -> None:**

SteamClient needs at least api_key to provide some functionalities. User can also provide username, password and SteamGuard file to be able to log in and use more methods. Proxies are also supported.

from steampy.client import SteamClient

steam_client = SteamClient('MY_API_KEY')
steam_client.login('MY_USERNAME', 'MY_PASSWORD', 'PATH_TO_STEAMGUARD_FILE')

User can also provide login_cookies from browser to log in by cookies.

from steampy.client import SteamClient

login_cookies = {} # provide dict with cookies
steam_client = SteamClient('MY_API_KEY',username='MY_USERNAME',login_cookies=login_cookies)
assert steam_client.was_login_executed

proxies dict can be provided for using proxy for internal SteamClient session.

from steampy.client import SteamClient

proxies =  {
    "http": "http://login:password@host:port", 
    "https": "http://login:password@host:port"
}

steam_client = SteamClient('MY_API_KEY', proxies=proxies)

If you have steamid, shared_secret and identity_secret you can place it in file Steamguard.txt instead of fetching SteamGuard file from device.

{
    "steamid": "YOUR_STEAM_ID_64",
    "shared_secret": "YOUR_SHARED_SECRET",
    "identity_secret": "YOUR_IDENTITY_SECRET"
}

Examples

You'll need to obtain your API key and SteamGuard file in order to run the examples, and then fill login and password in storehose.py file. The storehouse.py file contains an example of handling incoming trade offers.

python storehouse.py

If you want to generate authentication codes and use steampy as steam desktop authenticator then fill required secrets in desktop_authenticator.py file. The desktop_authenticator.py file contains examples of generating such one time codes/

python desktop_authenticator.py

SteamClient methods

Unless specified in documentation, the method does not require login to work(it uses API Key from constructor instead)

def set_proxy(self, proxy: dict) -> dict

Set proxy for steampy session, example:

from steampy.client import SteamClient

steam_client = SteamClient('MY_API_KEY')
proxies =  {
    "http": "http://login:password@host:port", 
    "https": "http://login:password@host:port"
}
steam_client.set_proxies(proxies)

def set_login_cookies(self, cookies: dict) -> None

Set login cookies, can be used instead of normal login method.

from steampy.client import SteamClient

login_cookies = {} # provide dict with cookies
steam_client = SteamClient('MY_API_KEY',username='MY_USERNAME',login_cookies=login_cookies)
assert steam_client.was_login_executed

login(username: str, password: str, steam_guard: str) -> requests.Response

Log into the steam account. Allows to accept trade offers and some other methods.

from steampy.client import SteamClient

steam_client = SteamClient('MY_API_KEY')
steam_client.login('MY_USERNAME', 'MY_PASSWORD', 'PATH_TO_STEAMGUARD_FILE')

You can also use with statement to automatically login and logout.

from steampy.client import SteamClient

with SteamClient('MY_API_KEY', 'MY_USERNAME', 'MY_PASSWORD', 'PATH_TO_STEAMGUARD_FILE') as client:
    client.some_method1(...)
    client.some_method2(...)
    ...

logout() -> None

Using SteamClient.login method is required before usage Logout from steam.

from steampy.client import SteamClient

steam_client = SteamClient('MY_API_KEY')
steam_client.login('MY_USERNAME', 'MY_PASSWORD', 'PATH_TO_STEAMGUARD_FILE')
steam_client.logout()

You can also use with statement to automatically login and logout.

from steampy.client import SteamClient

with SteamClient('MY_API_KEY', 'MY_USERNAME', 'MY_PASSWORD', 'PATH_TO_STEAMGUARD_FILE') as client:
    client.some_method1(...)
    client.some_method2(...)
    ...

is_session_alive() -> None

Using SteamClient.login method is required before usage Check if session is alive. This method fetches main page and check if user name is there. Thanks for vasia123 for this solution.

from steampy.client import SteamClient

steam_client = SteamClient('MY_API_KEY')
steam_client.login('MY_USERNAME', 'MY_PASSWORD', 'PATH_TO_STEAMGUARD_FILE')
is_session_alive = steam_client.is_session_alive()

api_call(request_method: str, interface: str, api_method: str, version: str, params: dict = None) -> requests.Response

Directly call api method from the steam api services.

Official steam api site

Unofficial but more elegant

from steampy.client import SteamClient

steam_client = SteamClient('MY_API_KEY')
params = {'key': 'MY_API_KEY'}
summaries =  steam_client.api_call('GET', 'IEconService', 'GetTradeOffersSummary', 'v1', params).json()

get_trade_offers_summary() -> dict

get_trade_offers(merge: bool = True) -> dict

Fetching trade offers from steam using an API call. Method is fetching offers with descriptions that satisfy conditions:

* Are sent by us or others
* Are active (means they have `trade_offer_state` set to 2 (Active))
* Are not historical
* No time limitation

If merge is set True then offer items are merged from items data and items description into dict where items id is key and descriptions merged with data are value.

get_trade_offer(trade_offer_id: str, merge: bool = True) -> dict

get_trade_receipt(trade_id: str) -> list

Using SteamClient.login method is required before usage Getting the receipt for a trade with all item information after the items has been traded. Do NOT store any item ids before you got the receipt since the ids may change. "trade_id" can be found in trade offers: offer['response']['offer']['tradeid']. Do not use ´tradeofferid´.

make_offer(items_from_me: List[Asset], items_from_them: List[Asset], partner_steam_id: str, message:str ='') -> dict

Using SteamClient.login method is required before usage Asset is class defined in client.py, you can obtain asset_id from SteamClient.get_my_inventory method. This method also uses identity secret from SteamGuard file to confirm the trade offer. No need to manually confirm it on mobile app or email. This method works when partner is your friend or steam. In returned dict there will be trade offer id by the key tradeofferid.

from steampy.client import SteamClient, Asset
from steampy.utils import GameOptions

steam_client = SteamClient('MY_API_KEY')
steam_client.login('MY_USERNAME', 'MY_PASSWORD', 'PATH_TO_STEAMGUARD_FILE')
partner_id = 'PARTNER_ID'
game = GameOptions.CS
my_items = steam_client.get_my_inventory(game)
partner_items = steam_client.get_partner_inventory(partner_id, game)
my_first_item = next(iter(my_items.values()))
partner_first_item = next(iter(partner_items.values()))
my_asset = Asset(my_first_item['id'], game)
partner_asset = Asset(partner_first_item['id'], game)
steam_client.make_offer([my_asset], [partner_asset], partner_id, 'Test offer')

make_offer_with_url(items_from_me: List[Asset], items_from_them: List[Asset], trade_offer_url: str, message: str = '', case_sensitive: bool = True) -> dict

Using SteamClient.login method is required before usage This method is similar to SteamClient.make_offer, but it takes trade url instead of friend account id. It works even when partner isn't your steam friend In returned dict there will be trade offer id by the key tradeofferid. If case_sensitive is False, then url params with be parsed with case insensitive params keys.

get_escrow_duration(trade_offer_url: str) -> int

Using SteamClient.login method is required before usage

Check the escrow duration for trade between you and partner(given partner trade offer url)

accept_trade_offer(trade_offer_id: str) -> dict

Using SteamClient.login method is required before usage This method also uses identity secret from SteamGuard file to confirm the trade offer. No need to manually confirm it on mobile app or email.

decline_trade_offer(trade_offer_id: str) -> dict

Decline trade offer that other user sent to us.

cancel_trade_offer(trade_offer_id: str) -> dict

Cancel trade offer that we sent to other user.

get_my_inventory(game: GameOptions, merge: bool = True, count: int = 5000) -> dict

Using SteamClient.login method is required before usage

If merge is set True then inventory items are merged from items data and items description into dict where items id is key and descriptions merged with data are value.

Count parameter is default max number of items, that can be fetched.

Inventory entries looks like this:

inventory_entry = {'7146788981': {'actions': [{
                                      'link': 'steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S%owner_steamid%A%assetid%D316070896107169653',
                                      'name': 'Inspect in Game...'}],
                      'amount': '1',
                      'appid': '730',
                      'background_color': '',
                      'classid': '1304827205',
                      'commodity': 0,
                      'contextid': '2',
                      'descriptions': [{'type': 'html',
                                        'value': 'Exterior: Field-Tested'},
                                       {'type': 'html', 'value': ' '},
                                       {'type': 'html',
                                        'value': 'Powerful and reliable, the AK-47 '
                                                 'is one of the most popular assault '
                                                 'rifles in the world. It is most '
                                                 'deadly in short, controlled bursts '
                                                 'of fire. It has been painted using '
                                                 'a carbon fiber hydrographic and a '
                                                 'dry-transfer decal of a red '
                                                 'pinstripe.\n'
                                                 '\n'
                                                 '<i>Never be afraid to push it to '
                                                 'the limit</i>'},
                                       {'type': 'html', 'value': ' '},
                                       {'app_data': {'def_index': '65535',
                                                     'is_itemset_name': 1},
                                        'color': '9da1a9',
                                        'type': 'html',
                                        'value': 'The Phoenix Collection'},
                                       {'type': 'html', 'value': ' '},
                                       {'app_data': {'def_index': '65535'},
                                        'type': 'html',
                                        'value': '<br><div id="sticker_info" '
                                                 'name="sticker_info" title="Sticker '
                                                 'Details" style="border: 2px solid '
                                                 'rgb(102, 102, 102); border-radius: '
                                                 '6px; width=100; margin:4px; '
                                                 'padding:8px;"><center><img '
                                                 'width=64 height=48 '
                                                 'src="https://steamcdn-a.akamaihd.net/apps/730/icons/econ/stickers/eslkatowice2015/pentasports.a6b0ddffefb5507453456c0d2c35b6a57821c171.png"><img '
                                                 'width=64 height=48 '
                                                 'src="https://steamcdn-a.akamaihd.net/apps/730/icons/econ/stickers/eslkatowice2015/pentasports.a6b0ddffefb5507453456c0d2c35b6a57821c171.png"><img '
                                                 'width=64 height=48 '
                                                 'src="https://steamcdn-a.akamaihd.net/apps/730/icons/econ/stickers/eslkatowice2015/pentasports.a6b0ddffefb5507453456c0d2c35b6a57821c171.png"><img '
                                                 'width=64 height=48 '
                                                 'src="https://steamcdn-a.akamaihd.net/apps/730/icons/econ/stickers/cologne2015/mousesports.3e75da497d9f75fa56f463c22db25f29992561ce.png"><br>Sticker: '
                                                 'PENTA Sports  | Katowice 2015, '
                                                 'PENTA Sports  | Katowice 2015, '
                                                 'PENTA Sports  | Katowice 2015, '
                                                 'mousesports | Cologne '
                                                 '2015</center></div>'}],
                      'icon_drag_url': '',
                      'icon_url': '-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpot7HxfDhjxszJemkV09-5lpKKqPrxN7LEmyVQ7MEpiLuSrYmnjQO3-UdsZGHyd4_Bd1RvNQ7T_FDrw-_ng5Pu75iY1zI97bhLsvQz',
                      'icon_url_large': '-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpot7HxfDhjxszJemkV09-5lpKKqPrxN7LEm1Rd6dd2j6eQ9N2t2wK3-ENsZ23wcIKRdQE2NwyD_FK_kLq9gJDu7p_KyyRr7nNw-z-DyIFJbNUz',
                      'id': '7146788981',
                      'instanceid': '480085569',
                      'market_actions': [{
                                             'link': 'steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D316070896107169653',
                                             'name': 'Inspect in Game...'}],
                      'market_hash_name': 'AK-47 | Redline (Field-Tested)',
                      'market_name': 'AK-47 | Redline (Field-Tested)',
                      'market_tradable_restriction': '7',
                      'marketable': 1,
                      'name': 'AK-47 | Redline',
                      'name_color': 'D2D2D2',
                      'owner_descriptions': '',
                      'tags': [{'category': 'Type',
                                'category_name': 'Type',
                                'internal_name': 'CSGO_Type_Rifle',
                                'name': 'Rifle'},
                               {'category': 'Weapon',
                                'category_name': 'Weapon',
                                'internal_name': 'weapon_ak47',
                                'name': 'AK-47'},
                               {'category': 'ItemSet',
                                'category_name': 'Collection',
                                'internal_name': 'set_community_2',
                                'name': 'The Phoenix Collection'},
                               {'category': 'Quality',
                                'category_name': 'Category',
                                'internal_name': 'normal',
                                'name': 'Normal'},
                               {'category': 'Rarity',
                                'category_name': 'Quality',
                                'color': 'd32ce6',
                                'internal_name': 'Rarity_Legendary_Weapon',
                                'name': 'Classified'},
                               {'category': 'Exterior',
                                'category_name': 'Exterior',
                                'internal_name': 'WearCategory2',
                                'name': 'Field-Tested'},
                               {'category': 'Tournament',
                                'category_name': 'Tournament',
                                'internal_name': 'Tournament6',
                                'name': '2015 ESL One Katowice'},
                               {'category': 'Tournament',
                                'category_name': 'Tournament',
                                'internal_name': 'Tournament7',
                                'name': '2015 ESL One Cologne'},
                               {'category': 'TournamentTeam',
                                'category_name': 'Team',
                                'internal_name': 'Team39',
                                'name': 'PENTA Sports'},
                               {'category': 'TournamentTeam',
                                'category_name': 'Team',
                                'internal_name': 'Team29',
                                'name': 'mousesports'}],
                      'tradable': 1,
                      'type': 'Classified Rifle'}}

get_partner_inventory(partner_steam_id: str, game: GameOptions, merge: bool = True, count: int = 5000) -> dict

Using SteamClient.login method is required before usage

Inventory items can be merged like in SteamClient.get_my_inventory method

Count parameter is default max number of items, that can be fetched.

get_wallet_balance(convert_to_decimal: bool = True, on_hold: bool = False) -> Union[str, float]

Check account balance of steam acccount. It converts money string to Decimal if convert_to_decimal is set to True, otherwise, it will return the value string without a decimal point. If the on_hold parameter is set to True, it will return the current on-hold balance value.

Example:

from steampy.client import SteamClient
from decimal import Decimal 
with SteamClient('MY_API_KEY', 'MY_USERNAME', 'MY_PASSWORD', 'PATH_TO_STEAMGUARD_FILE') as client:
            wallet_balance = client.get_wallet_balance()
            on_hold_wallet_balance = client.get_wallet_balance(on_hold = True)
            assert type(wallet_balance) == Decimal
            assert type(on_hold_wallet_balance) == Decimal

market methods

fetch_price(item_hash_name: str, game: GameOptions, currency: str = Currency.USD) -> dict

Some games are predefined in GameOptions class, such as GameOptions.DOTA2, GameOptions.CS and GameOptions.TF2, but GameOptions` object can be constructed with custom parameters.

Currencies are defined in Currency class, currently

Default currency is USD

May rise TooManyRequests exception if used more than 20 times in 60 seconds.

from steampy.client import SteamClient
from steampy.models import GameOptions

steam_client = SteamClient('API_KEY')
item = 'M4A1-S | Cyrex (Factory New)'
price = steam_client.market.fetch_price(item, game=GameOptions.CS)
# price == {'volume': '208', 'lowest_price': '$11.30 USD', 'median_price': '$11.33 USD', 'success': True}

fetch_price_history(item_hash_name: str, game: GameOptions) -> dict

Using SteamClient.login method is required before usage

Returns list of price history of and item.

from steampy.client import SteamClient
from steampy.models import GameOptions

with SteamClient('MY_API_KEY', 'MY_USERNAME', 'MY_PASSWORD', 'PATH_TO_STEAMGUARD_FILE') as client:
    item = 'M4A1-S | Cyrex (Factory New)'
    response = client.market.fetch_price_history(item, GameOptions.CS)
    response['prices'][0]
    ['Jul 02 2014 01: +0', 417.777, '40']

Each entry in response['prices'] is a list, with first entry being date, second entry price, and third entry a volume.

get_my_market_listings() -> dict

Using SteamClient.login method is required before usage

Returns market listings posted by user

from steampy.client import SteamClient

with SteamClient('MY_API_KEY', 'MY_USERNAME', 'MY_PASSWORD', 'PATH_TO_STEAMGUARD_FILE') as client:
    listings = client.market.get_my_market_listings()

create_sell_order(assetid: str, game: GameOptions, money_to_receive: str) -> dict

Using SteamClient.login method is required before usage

Create sell order of the asset on the steam market.

from steampy.client import SteamClient
from steampy.models import GameOptions

with SteamClient('MY_API_KEY', 'MY_USERNAME', 'MY_PASSWORD', 'PATH_TO_STEAMGUARD_FILE') as client:
    asset_id_to_sell = 'some_asset_id'
    game = GameOptions.DOTA2
    sell_response = client.market.create_sell_order(asset_id_to_sell, game, "10000")

⚠️ money_to_receive has to be in cents, so "100.00" should be passed has "10000"

create_buy_order(market_name: str, price_single_item: str, quantity: int, game: GameOptions, currency: Currency = Currency.USD) -> dict

Using SteamClient.login method is required before usage

Create buy order of the assets on the steam market.

from steampy.client import SteamClient
from steampy.models import GameOptions, Currency

with SteamClient('MY_API_KEY', 'MY_USERNAME', 'MY_PASSWORD', 'PATH_TO_STEAMGUARD_FILE') as client:
    response = client.market.create_buy_order("AK-47 | Redline (Field-Tested)", "1034", 2, GameOptions.CS, Currency.EURO)
    buy_order_id = response["buy_orderid"]

⚠️ price_single_item has to be in cents, so "10.34" should be passed has "1034"

buy_item(market_name: str, market_id: str, price: int, fee: int, game: GameOptions, currency: Currency = Currency.USD) -> dict

Using SteamClient.login method is required before usage

Buy a certain item from market listing.

from steampy.client import SteamClient
from steampy.models import Currency, GameOptions

with SteamClient('MY_API_KEY', 'MY_USERNAME', 'MY_PASSWORD', 'PATH_TO_STEAMGUARD_FILE') as client:
    response = client.market.buy_item('AK-47 | Redline (Field-Tested)', '1942659007774983251', 81, 10,
                                        GameOptions.CS, Currency.RUB)
    wallet_balance = response["wallet_info"]["wallet_balance"]

cancel_sell_order(sell_listing_id: str) -> None

Using SteamClient.login method is required before usage

Cancel previously requested sell order on steam market.

from steampy.client import SteamClient

with SteamClient('MY_API_KEY', 'MY_USERNAME', 'MY_PASSWORD', 'PATH_TO_STEAMGUARD_FILE') as client:
    sell_order_id = "some_sell_order_id"
    response = client.market.cancel_sell_order(sell_order_id)

cancel_buy_order(buy_order_id) -> dict

Using SteamClient.login method is required before usage

Cancel previously requested buy order on steam market.

from steampy.client import SteamClient

with SteamClient('MY_API_KEY', 'MY_USERNAME', 'MY_PASSWORD', 'PATH_TO_STEAMGUARD_FILE') as client:
    buy_order_id = "some_buy_order_id"
    response = client.market.cancel_buy_order(buy_order_id)

Currencies

Currency class Description
Currency.USD United States Dollar
Currency.GBP United Kingdom Pound
Currency.EURO European Union Euro
Currency.CHF Swiss Francs
Currency.RUB Russian Rouble
Currency.PLN Polish Złoty
Currency.BRL Brazilian Reals
Currency.JPY Japanese Yen
Currency.NOK Norwegian Krone
Currency.IDR Indonesian Rupiah
Currency.MYR Malaysian Ringgit
Currency.PHP Philippine Peso
Currency.SGD Singapore Dollar
Currency.THB Thai Baht
Currency.VND Vietnamese Dong
Currency.KRW South Korean Won
Currency.TRY Turkish Lira
Currency.UAH Ukrainian Hryvnia
Currency.MXN Mexican Peso
Currency.CAD Canadian Dollars
Currency.AUD Australian Dollars
Currency.NZD New Zealand Dollar
Currency.CNY Chinese Renminbi (yuan)
Currency.INR Indian Rupee
Currency.CLP Chilean Peso
Currency.PEN Peruvian Sol
Currency.COP Colombian Peso
Currency.ZAR South African Rand
Currency.HKD Hong Kong Dollar
Currency.TWD New Taiwan Dollar
Currency.SAR Saudi Riyal
Currency.AED United Arab Emirates Dirham
Currency.SEK Swedish Krona
Currency.ARS Argentine Peso
Currency.ILS Israeli New Shekel
Currency.BYN Belarusian Ruble
Currency.KZT Kazakhstani Tenge
Currency.KWD Kuwaiti Dinar
Currency.QAR Qatari Riyal
Currency.CRC Costa Rican Colón
Currency.UYU Uruguayan Peso
Currency.BGN Bulgarian Lev
Currency.HRK Croatian Kuna
Currency.CZK Czech Koruna
Currency.DKK Danish Krone
Currency.HUF Hungarian Forint
Currency.RON Romanian Leu

guard module functions

load_steam_guard(steam_guard: str) -> dict

If steam_guard is file name then load and parse it, else just parse steam_guard as json string.

generate_one_time_code(shared_secret: str, timestamp: int = None) -> str

Generate one time code for logging into Steam using shared_secret from SteamGuard file. If none timestamp provided, timestamp will be set to current time.

generate_confirmation_key(identity_secret: str, tag: str, timestamp: int = int(time.time())) -> bytes

Generate mobile device confirmation key for accepting trade offer. Default timestamp is current time.

Utils methods

calculate_gross_price(price_net: Decimal, publisher_fee: Decimal, steam_fee: Decimal = Decimal('0.05')) -> Decimal:

Calculate the price including the publisher's fee and the Steam fee. Most publishers have a 10% fee with a minimum fee of $0.01. The Steam fee is currently 5% (with a minimum fee of $0.01) and may be increased or decreased by Steam in the future.

Returns the amount that the buyer pays during a market transaction:

from decimal import Decimal
from steampy.utils import calculate_gross_price

publisher_fee = Decimal('0.1')  # 10%

calculate_gross_price(Decimal('100'), publisher_fee)     # returns Decimal('115')

calculate_net_price(price_gross: Decimal, publisher_fee: Decimal, steam_fee: Decimal = Decimal('0.05')) -> Decimal:

Calculate the price without the publisher's fee and the Steam fee. Most publishers have a 10% fee with a minimum fee of $0.01. The Steam fee is currently 5% (with a minimum fee of $0.01) and may be increased or decreased by Steam in the future.

Returns the amount that the seller receives after a market transaction:

from decimal import Decimal
from steampy.utils import calculate_net_price

publisher_fee = Decimal('0.1')  # 10%

calculate_net_price(Decimal('115'), publisher_fee)     # returns Decimal('100')

Test

All public methods are documented and tested. guard module has unit tests, client uses an acceptance test. For the acceptance test you have to put credentials.pwd and Steamguard file into test directory

Example credentials.pwd file:

account1 password1 api_key1
account2 password2 api_key2

In some tests you also have to obtain transaction_id. You can do it by SteamClient.get_trade_offers or by logging manually into steam account in browser and get it from url

In some tests you also have to obtain partner steam id. You can do it by logging manually into steam account in browser and get it from url

License

MIT License

Copyright (c) 2016 Michał Bukowski

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

steampy's People

Contributors

alexkharaba avatar bilousvladyslav avatar borisenko09 avatar bukson avatar d0p1er avatar emanuelesarte avatar iamdlm avatar jiajiaxd avatar johntanas avatar justin-ys avatar justkappaman avatar krisztian-toth avatar kudisoldier avatar ldapuser avatar leoramme avatar mactep avatar makarworld avatar maxtwen avatar mninc avatar nas- avatar sap2me avatar sebabu avatar secord0 avatar secretmission4 avatar timwoocker avatar vgrabov avatar vvild avatar wolfovik avatar yakivgluck avatar zwork101 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

steampy's Issues

Masters degree

Hi.

I am finishing my masters degree and have not so much time for steampy. It will change soon, now I will try to answert support questions, but development and code review will be done after 2 weeks.

Sorry for inconvinience.

I will close this issue when i finish my masters degree program

Relogin problem...

I have 24/7 bot with your greate lib. From time to time session die and iht's bot can't send/accept trades. If bot relogin in cycle, login failed. When i off program and run again login true, how to relogin without stopping program?

steam_client instead of client in readme.md

from steampy.client import SteamClient, Asset
from steampy.utils import GameOptions

steam_client = SteamClient('MY_API_KEY')
steam_client.login('MY_USERNAME', 'MY_PASSWORD', 'PATH_TO_STEAMGUARD_FILE')
partner_id = 'PARTNER_ID'
game = GameOptions.CS
my_items = client.get_my_inventory(game)
partner_items = client.get_partner_inventory(partner_id, game)
my_first_item = next(iter(my_items.values()))
partner_first_item = next(iter(partner_items.values()))
my_asset = Asset(my_first_item['id'], game)
partner_asset = Asset(partner_first_item['id'], game)
client.make_offer([my_asset], [partner_asset], partner_id, 'Test offer') 

I think in this block everywhere should be steam_client instead of client.

Login returns False

When i try to login, i got this:
{'requires_twofactor': True, 'message': '', 'success': False}

Make offer don't work

Make offer return 401 status and None response when i do make_offer or make_offer_with_trade_url

[Help] Cannot run storehouse.py

I cant run it. Using my own script and doing bot.login() also does not work. It constantly gives this error:

This is the donation bot accepting items for free.
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python3.5/dist-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "/usr/local/lib/python3.5/dist-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/home/jensen/Desktop/storehouse.py", line 47, in
main()
File "/home/jensen/Desktop/storehouse.py", line 21, in main
client.login(username, password, steamguard_path)
File "/usr/local/lib/python3.5/dist-packages/steampy/client.py", line 76, in login
LoginExecutor(username, password, self.steam_guard['shared_secret'], self._session).login()
File "/usr/local/lib/python3.5/dist-packages/steampy/login.py", line 26, in login
self._perform_redirects(login_response.json())
File "/usr/local/lib/python3.5/dist-packages/steampy/login.py", line 81, in _perform_redirects
parameters = response_dict['transfer_parameters']
KeyError: 'transfer_parameters'

Error with sha1.new

After accepting the trade, and even receiving the item It traded for, the program exited the loop due to sha1 not having the attribute .new()

hexed_steam_id = sha1.new(steam_id.encode('ascii')).hexdigest()
AttributeError: 'builtin_function_or_method' object has no attribute 'new'

So even though it completes the trade, this error still occurs.

[Question/Bug] Is it not possible to use steam and steampy in the same execution?

So, I want to send a trade when the bot gets a certain message, so I'm using the steam modual and steampy for trading, however, I got past the first bug, where you need to add

import gevent.monkey
gevent.monkey.patch_socket()
gevent.monkey.patch_ssl()

before importing it, so the login goes smoothly. However, after the steam login, it states invalid credentials, whilst even though I used the same ones to log into steam, I can't log into steampy with them? Is there some sort of issue with connecting to steam with 2 different programs? If I have steampy and steam running in separate files, it runs fine, but if it's in the same, theirs issues. Does anyone know why this is happening?

Refactor tests

Delete some hard coded ids, and make some utility methods for fetching first item of me and partner

accepting offer with giving items

Can`t accept offer where i giving some items to another person. Problem is _get_confirmations method, when it`s try to _fetch_confirmations_page it gets steam page with alert instead of valid confirmation page

Error with make_offer

make offer response return error 15

asset_partn = Asset(item['id'],game)
response = steam_client.make_offer([],[asset_partn],partnerid,"Please))")
print(response)

Hi I am getting an error

Hi the title says it all
My error:

Unhandled exception in thread started by <function processingOrder at 0x04AEDDB0>
Traceback (most recent call last):
  File "C:\Users\edast\Desktop\steam python\Bot\KeyToGamesP2.py", line 150, in processingOrder
    print partner_items[item]["type"]
TypeError: 'bool' object has no attribute '__getitem__'

And code:

    partner_id = msg.body.steamid_from
    partner_items = steam_client.get_partner_inventory(partner_id, game)
    hasKey = False
    keysToOrder = False
    for item in partner_items:
        print(item)
        if not item == "success" or not item == "rgInventory":
            print partner_items[item]["type"]
            if partner_items[item]["type"] == "Base Grade Container":
                print("Went thru")
                if partner_items[item]["tradable"] == 1 and partner_items[item]["marketable"] == 1:
                    print("Ma klic. Posilam offer...")
                    if len(klice) >= keyCount:
                        keysToOrder = True
                        break
                    else:
                        klice.append(item)
                        hasKey = True

Make offer except

Partner_id is Steam64 or AccountID? When i use this method with AccID and Stean64 i get error KeyError: 'rgInventory'

SyntaxError

Well when I want to start my program this error pops up

Traceback (most recent call last):
  File "C:/Users/edast/Desktop/steam python/fetching_inv.py", line 1, in <module>
    from steampy.client import SteamClient
  File "C:\Python27\lib\site-packages\steampy\client.py", line 23
    def __init__(self, asset_id: str, game: GameOptions, amount: int = 1) -> None:
                               ^
SyntaxError: invalid syntax

My code

from steampy.client import SteamClient
from steampy.utils import GameOptions
from getpass import getpass

userName = raw_input("Steam name: ")
password = getpass("Password: ")
authCode = raw_input("Steam 2FA Code: ")

steam_client = SteamClient("Api key")
steam_client.login(userName, password, authCode)
partner_id = "FriendsId"
game = GameOptions.CS
partner_items = steam_client.get_partner_inventory(partner_id, game)
print(partner_items)
steam_client.logout()

Problem with installation

After trying to download steampy through pip, but received this error, even after installing the C++ interpreter.

  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Isrc/ -Isrc/inc-msvc/ -Ic:\users\zwork101\appdata\local\programs\python\python36-32\include -Ic:\users\zwork101\appdata\local\programs\python\python36-32\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\8.1\include\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\winrt" /Tcsrc/winrand.c /Fobuild\temp.win32-3.6\Release\src/winrand.obj
    winrand.c
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(26): error C2061: syntax error: identifier 'intmax_t'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(27): error C2061: syntax error: identifier 'rem'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(27): error C2059: syntax error: ';'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(28): error C2059: syntax error: '}'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(30): error C2061: syntax error: identifier 'imaxdiv_t'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(30): error C2059: syntax error: ';'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(40): error C2143: syntax error: missing '{' before '__cdecl'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(41): error C2146: syntax error: missing ')' before identifier '_Number'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(41): error C2061: syntax error: identifier '_Number'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(41): error C2059: syntax error: ';'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(42): error C2059: syntax error: ')'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(45): error C2143: syntax error: missing '{' before '__cdecl'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(46): error C2146: syntax error: missing ')' before identifier '_Numerator'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(46): error C2061: syntax error: identifier '_Numerator'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(46): error C2059: syntax error: ';'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(46): error C2059: syntax error: ','
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(48): error C2059: syntax error: ')'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(50): error C2143: syntax error: missing '{' before '__cdecl'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(56): error C2143: syntax error: missing '{' before '__cdecl'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(63): error C2143: syntax error: missing '{' before '__cdecl'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(69): error C2143: syntax error: missing '{' before '__cdecl'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(76): error C2143: syntax error: missing '{' before '__cdecl'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(82): error C2143: syntax error: missing '{' before '__cdecl'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(89): error C2143: syntax error: missing '{' before '__cdecl'
    C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(95): error C2143: syntax error: missing '{' before '__cdecl'
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2

Does any one know Why? or How I can fix it?

Change GameOptions enum to normal class

So, I'm trying to get my steam backpack. It's one of those sub-inventory backpacks, so I have the context_id = '6'

>>>GameOptions('753','6')

But I get the error:

Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    steam = GameOptions('753','6')
  File "C:\Users\Zwork101\AppData\Local\Programs\Python\Python36-32\lib\enum.py", line 293, in __call__
    return cls._create_(value, names, module=module, qualname=qualname, type=type, start=start)
  File "C:\Users\Zwork101\AppData\Local\Programs\Python\Python36-32\lib\enum.py", line 378, in _create_
    _, first_enum = cls._get_mixins_(bases)
  File "C:\Users\Zwork101\AppData\Local\Programs\Python\Python36-32\lib\enum.py", line 436, in _get_mixins_
    raise TypeError("Cannot extend enumerations")
TypeError: Cannot extend enumerations

I don't see what i'm doing wrong, help?

InvalidCredentials with empty message while logging

In response to two-factor authorization, I get an error with a mixed message. Here's the log:

2017.05.15 16:15:48 [app.DEBUG][26745 140737041318848] Response for steam auth: 
{"success":false,"requires_twofactor":true,"message":""} (login.py:28)
2017.05.15 16:15:50 [app.DEBUG][26745 140737041318848] Response for steam two-factor auth: 
{"success":false,"requires_twofactor":true,"message":""} (login.py:31)

What am I doing wrong?

way to send message

hi I want to know if there a function with this api to send messge to a friend in steam by his steamid ??

Windows Support

Cool library!

Still there is an issue for Windows users which i noticed today with someone in the discord chat of r/steambot. PyCrypto is not installable in an easy way on Windows so i propose to remove the dependency on the packages and implement a native approach. As reference you could take the C# class from here.

Its just a suggestion and would make a lot of things easier for the Windows folks (i am using ubuntu/windows and .net core, so not likely a python guy).

How to get a certain amount of an item?

So, I want to send a trade offer with 300 steam gems in it. But when I use Asset, it only wants the id of the item. How am I supposed to get a certain amount of that item?

login problem

use SDA as from it to get files, try maFaile does not work

New version 0.40!

This versions add Ermans implementation of steam market api.

It is still a bit experimental so use it carefully. please inform me about issues/bugs that can occur.

This change brakes backawards compatibility, i am aware that this is young library and i can happen, To version 1.0 it can happen some times, I will try to avoid it if possible.

Insert auth code manually

Hey mate, nice work.
I was playing with the module and can't get the code working without the steamguard file, I ran into some errors. I don't have much experience in python and don't know how to do this.

[Request] Log in a site using "Sign in through Steam"

Is it possible to add the possibility to login in a site through the green button "Sign in through Steam" and keep the session? Because I need to log in a site that uses SteamIDs.

Some example:
backpack.tf
dota2lounge.com
lootmarket.com

I really want to make some requests to these sites but I need a session but don't know how to do it.

[Discussion] About the Steam Market

(talking to bukson the author of this library)
I have made for myself some function to handle the Steam Market.
I'm talking about creating a buy order or a sell listing and removing them (confirmation with steamguard included).

Is it your plan to have them in this library?

I can make a pull request if you agree, I just need to make the functions more general because now are crafted right for my code and to make some tests.

Shared_secret file

Is there some way to not use the file with secrets but type in steam guard authentication code every time when I want to login?

Bug - Expected Trade confirmation

After adding the updated version of steampy, the bot accepted the trade, but stopped the loop due to an expected trade confirmation:

raise ConfirmationExpected
steampy.confirmation.ConfirmationExpected

The items, like last time, went through successfully, however still created this error

Is make offer working?

So, I have the following code to send and offer:

print(itemList)
print([gems])
print(str(friend.steam_id))
steam_client.make_offer(itemList,[gems],str(friend.steam_id))
friend.send_message("Alrighty! Sending your trade right now!")
print("sent trade offer!")

And it returns this:

[<steampy.client.Asset object at 0x039B7AB0>, <steampy.client.Asset object at 0x03A2D590>, <steampy.client.Asset object at 0x04868E50>, <steampy.client.Asset object at 0x0489A310>, <steampy.client.Asset object at 0x0489A130>, <steampy.client.Asset object at 0x0489A1B0>, <steampy.client.Asset object at 0x0489A350>, <steampy.client.Asset object at 0x0489A1D0>, <steampy.client.Asset object at 0x05AE3930>, <steampy.client.Asset object at 0x0489A330>, <steampy.client.Asset object at 0x05AE3B90>, <steampy.client.Asset object at 0x05AE39D0>, <steampy.client.Asset object at 0x05AE3710>, <steampy.client.Asset object at 0x05AE3BB0>, <steampy.client.Asset object at 0x05AE32F0>, <steampy.client.Asset object at 0x05AE3050>, <steampy.client.Asset object at 0x05AE3810>, <steampy.client.Asset object at 0x05AE3C70>, <steampy.client.Asset object at 0x05AE3910>, <steampy.client.Asset object at 0x05AE3A90>, <steampy.client.Asset object at 0x05AE3AB0>]
[<steampy.client.Asset object at 0x04868FB0>]
76561198269569899
sent trade offer!

However, it does not, infact, end up sending the offer, and raises no errors. Is this something that is known, or have I done something incorrect?

Login method not handle steam errors.

I got an error:

Traceback (most recent call last):
  File "C:\YandexDisk\my_python_progs\csgo\new\tests\test_main.py", line 15, in <module>
    import libs.helpers as helpers
  File "C:\YandexDisk\my_python_progs\csgo\new\libs\helpers.py", line 456, in <module>
    steam_client = login_steam(steam_login, steam_pass, steam_guard, steam_api_key)
  File "C:\YandexDisk\my_python_progs\csgo\new\libs\helpers.py", line 319, in login_steam
    steam_client.login(steam_login, steam_pass, steam_guard)
  File "C:\Users\vasis\AppData\Local\Programs\Python\Python35\lib\site-packages\steampy\client.py", line 76, in login
    LoginExecutor(username, password, self.steam_guard['shared_secret'], self._session).login()
  File "C:\Users\vasis\AppData\Local\Programs\Python\Python35\lib\site-packages\steampy\login.py", line 26, in login
    self._perform_redirects(login_response.json())
  File "C:\Users\vasis\AppData\Local\Programs\Python\Python35\lib\site-packages\steampy\login.py", line 82, in _perform_redirects
    parameters = response_dict['transfer_parameters']
KeyError: 'transfer_parameters'

I put print in _perform_redirects method, and get response_dict content in moment of error:

{'success': False, 'requires_twofactor': False, 'message': 'There have been too many login failures from your network in a short time period. Please wait and try again later.', 'captcha_gid': -1, 'captcha_needed': False}

Can you improve login method to handle this errors?

Bad practice with generate_one_time_code

Not so long ago, I came across the fact that with two-factor authentication comes empty response (#53). It turned out that if you authorize the client several times without restarting application, the same one-time code will be generated. It's a bad idea to pass a variable like time.time() to the default value:

def generate_one_time_code(shared_secret: str, timestamp: int = int(time.time())) -> str:
    # generating one-time code

Probably, it should look like this:

def generate_one_time_code(shared_secret: str, timestamp: int = 0) -> str:
    if not timestamp:
        timestamp = int(time.time())
    # generating one-time code

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.