Skip to content

Commit

Permalink
Merge pull request #9 from offish/v1.2.6
Browse files Browse the repository at this point in the history
v1.2.6
  • Loading branch information
offish authored Jan 12, 2021
2 parents 663e2bd + 252fd88 commit f4e7981
Show file tree
Hide file tree
Showing 14 changed files with 241 additions and 230 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
# tf2-express
[![License](https://img.shields.io/github/license/offish/tf2-express.svg)](https://github.com/offish/tf2-express/blob/master/LICENSE)
[![Stars](https://img.shields.io/github/stars/offish/tf2-express.svg)](https://github.com/offish/tf2-express/stargazers)
[![Issues](https://img.shields.io/github/issues/offish/tf2-express.svg)](https://github.com/offish/tf2-express/issues)
[![Size](https://img.shields.io/github/repo-size/offish/tf2-express.svg)](https://github.com/offish/tf2-express)
[![Discord](https://img.shields.io/discord/467040686982692865?color=7289da&label=Discord&logo=discord)](https://discord.gg/t8nHSvA)
[![Code style](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

[![Donate Steam](https://img.shields.io/badge/donate-steam-green.svg)](https://steamcommunity.com/tradeoffer/new/?partner=293059984&token=0-l_idZR)
[![Donate PayPal](https://img.shields.io/badge/donate-paypal-blue.svg)](https://www.paypal.me/0ffish)

Automated trading bot for Team Fortress 2 using prices provided by [Prices.TF](https://prices.tf).

## Features
Expand Down
10 changes: 4 additions & 6 deletions express/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@

__title__ = 'tf2-express'
__author__ = 'offish'
__license__ = 'MIT'
__version__ = '1.2.5'

__title__ = "tf2-express"
__author__ = "offish"
__license__ = "MIT"
__version__ = "1.2.6"
51 changes: 31 additions & 20 deletions express/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,43 +5,54 @@
from steampy.client import SteamClient
from steampy.exceptions import InvalidCredentials


class Client:
def __init__(self, bot: dict):
self.log = Log(bot['name'])
self.username = bot['username']
self.password = bot['password']
self.secrets = bot['secrets']
self.client = SteamClient(bot['api_key'])
self.log = Log(bot["name"])
self.username = bot["username"]
self.password = bot["password"]
self.secrets = bot["secrets"]
self.client = SteamClient(bot["api_key"])

def login(self):
def login(self) -> None:
try:
self.client.login(self.username, self.password, dumps(self.secrets))

if self.client.was_login_executed:
self.log.info(f'Logged into Steam as {f.GREEN + self.username}')
self.log.info(f"Logged into Steam as {f.GREEN + self.username}")
else:
self.log.error('Login was not executed')
self.log.error("Login was not executed")

except InvalidCredentials as e:
self.log.error(e)

def logout(self):
self.log.info('Logging out...')
def logout(self) -> None:
self.log.info("Logging out...")
self.client.logout()

def get_offers(self):
return self.client.get_trade_offers(merge=True)['response']['trade_offers_received']
def get_offers(self) -> dict:
try:
return self.client.get_trade_offers(merge=True)["response"][
"trade_offers_received"
]
except KeyError:
return {}

def get_offer(self, offer_id: str):
return self.client.get_trade_offer(offer_id, merge=True)['response']['offer']
def get_offer(self, offer_id: str) -> dict:
try:
return self.client.get_trade_offer(offer_id, merge=True)["response"][
"offer"
]
except KeyError:
return {}

def get_receipt(self, trade_id: str):
def get_receipt(self, trade_id: str) -> dict:
return self.client.get_trade_receipt(trade_id)

def accept(self, offer_id: str):
self.log.trade('Trying to accept offer', offer_id)
def accept(self, offer_id: str) -> None:
self.log.trade("Trying to accept offer", offer_id)
self.client.accept_trade_offer(offer_id)

def decline(self, offer_id: str):
self.log.trade('Trying to decline offer', offer_id)
def decline(self, offer_id: str) -> None:
self.log.trade("Trying to decline offer", offer_id)
self.client.decline_trade_offer(offer_id)
40 changes: 20 additions & 20 deletions express/config.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
bots = [
{
'name': 'bot1',
'username': 'username',
'password': 'password',
'api_key': '111AA1111AAAA11A1A11AA1AA1AAA111',
'secrets': {
'steamid': '76511111111111111',
'shared_secret': 'Aa11aA1+1aa1aAa1a=',
'identity_secret': 'aA11aaaa/aa11a/aAAa1a1='
}
"name": "bot1",
"username": "username",
"password": "password",
"api_key": "111AA1111AAAA11A1A11AA1AA1AAA111",
"secrets": {
"steamid": "76511111111111111",
"shared_secret": "Aa11aA1+1aa1aAa1a=",
"identity_secret": "aA11aaaa/aa11a/aAAa1a1=",
},
},
{
'name': 'bot2',
'username': 'username',
'password': 'password',
'api_key': '111AA1111AAAA11A1A11AA1AA1AAA111',
'secrets': {
'steamid': '76511111111111111',
'shared_secret': 'Aa11aA1+1aa1aAa1a=',
'identity_secret': 'aA11aaaa/aa11a/aAAa1a1='
}
}
"name": "bot2",
"username": "username",
"password": "password",
"api_key": "111AA1111AAAA11A1A11AA1AA1AAA111",
"secrets": {
"steamid": "76511111111111111",
"shared_secret": "Aa11aA1+1aa1aAa1a=",
"identity_secret": "aA11aaaa/aa11a/aAAa1a1=",
},
},
]

owners = ['76511111111111111']
owners = ["76511111111111111"]
timeout = 30
36 changes: 14 additions & 22 deletions express/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,58 +3,50 @@
from pymongo import MongoClient


client = MongoClient('localhost', 27017)
database = client['express']
client = MongoClient("localhost", 27017)
database = client["express"]

trades = database['trades']
prices = database['prices']
trades = database["trades"]
prices = database["prices"]

log = Log()


def add_trade(data: dict) -> None:
trades.insert(data)
log.info(f'Offer was added to the database')
log.info(f"Offer was added to the database")


def get_trades() -> dict:
return trades.find()


def get_items() -> list:
return [item['name'] for item in prices.find()]
return [item["name"] for item in prices.find()]


def get_item(name: str) -> dict:
return prices.find_one({'name': name})
return prices.find_one({"name": name})


def _get_price(name: str) -> dict:
return prices.find_one({'name': name})
return prices.find_one({"name": name})


def _get_pricelist() -> dict:
return prices.find()


def add_price(name: str) -> None:
prices.insert({
'name': name,
'buy': None,
'sell': None
})
log.info(f'Added {name} to the database')
prices.insert({"name": name, "buy": None, "sell": None})
log.info(f"Added {name} to the database")


def update_price(name: str, buy: dict, sell: dict) -> None:
prices.replace_one({'name': name}, {
'name': name,
'buy': buy,
'sell': sell
})
log.info(f'Updated price for {name}')
prices.replace_one({"name": name}, {"name": name, "buy": buy, "sell": sell})
log.info(f"Updated price for {name}")


def remove_price(name: str) -> None:
prices.delete_one({'name': name})
log.info(f'Removed {name} from the database')
prices.delete_one({"name": name})
log.info(f"Removed {name} from the database")
26 changes: 13 additions & 13 deletions express/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,25 @@
init()


def log(color: int, sort: str, bot: str, text: str, offer_id: str = ''):
name = f' {f.GREEN}[{bot}]' if bot else ''
text = f'({f.YELLOW}{offer_id}{f.WHITE}) {text}' \
if offer_id else text
time = datetime.now().time().strftime('%H:%M:%S')
print(f'{f.GREEN}tf2-express | {f.WHITE}{time} - {color + sort}{name}{f.WHITE}: {text}{f.WHITE}')
def log(color: int, sort: str, bot: str, text: str, offer_id: str = ""):
name = f" {f.GREEN}[{bot}]" if bot else ""
text = f"({f.YELLOW}{offer_id}{f.WHITE}) {text}" if offer_id else text
time = datetime.now().time().strftime("%H:%M:%S")
print(
f"{f.GREEN}tf2-express | {f.WHITE}{time} - {color + sort}{name}{f.WHITE}: {text}{f.WHITE}"
)


class Log:
def __init__(self, bot: str = '', offer_id: str = ''):
def __init__(self, bot: str = "", offer_id: str = ""):
self.bot = bot
self.offer_id = offer_id

def info(self, text: str):
log(f.GREEN, 'info', self.bot, text)
log(f.GREEN, "info", self.bot, text)

def error(self, text: str):
log(f.RED, 'error', self.bot, text)

def trade(self, text: str, offer_id: str = ''):
log(f.MAGENTA, 'trade', self.bot, text, self.offer_id or offer_id)
log(f.RED, "error", self.bot, text)

def trade(self, text: str, offer_id: str = ""):
log(f.MAGENTA, "trade", self.bot, text, self.offer_id or offer_id)
10 changes: 3 additions & 7 deletions express/methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,13 @@
import requests


FAILURE = {'success': False}
FAILURE = {"success": False}


def request(url: str, payload: dict = {}, headers: dict = {}) -> dict:
r = requests.get(url, params=payload, headers=headers)

try:
return loads(r.text)
except ValueError:
return {
**FAILURE,
'status_code': r.status_code,
'text': r.text
}
return {**FAILURE, "status_code": r.status_code, "text": r.text}
43 changes: 23 additions & 20 deletions express/offer.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

def valuate(items: dict, intent: str, item_list: list) -> int:
total = 0
high = float(10**5)
high = float(10 ** 5)

for i in items:
item = Item(items[i])
Expand All @@ -20,7 +20,7 @@ def valuate(items: dict, intent: str, item_list: list) -> int:

if item.is_pure():
value = item.get_pure()

elif item.is_key():
value = get_key_price()

Expand All @@ -30,16 +30,16 @@ def valuate(items: dict, intent: str, item_list: list) -> int:
value = get_price(name, intent)

elif item.is_craft_hat():
value = get_price('Random Craft Hat', intent)
value = get_price("Random Craft Hat", intent)

elif not item.is_craftable():
name = 'Non-Craftable ' + name
name = "Non-Craftable " + name

if name in item_list:
value = get_price(name, intent)

if not value:
value = high if intent == 'sell' else 0.00
value = high if intent == "sell" else 0.00

total += to_scrap(value)

Expand All @@ -49,7 +49,7 @@ def valuate(items: dict, intent: str, item_list: list) -> int:
class Offer:
def __init__(self, offer: dict):
self.offer = offer
self.state = offer['trade_offer_state']
self.state = offer["trade_offer_state"]

def get_state(self) -> str:
return TradeOfferState(self.state).name
Expand All @@ -67,29 +67,32 @@ def is_declined(self) -> bool:
return self.has_state(7)

def has_escrow(self) -> bool:
return self.offer['escrow_end_date'] == 0
return self.offer["escrow_end_date"] == 0

def is_our_offer(self) -> bool:
return self.offer['is_our_offer']
return self.offer["is_our_offer"]

def is_gift(self) -> bool:
return self.offer.get('items_to_receive') \
and not self.offer.get('items_to_give')
return self.offer.get("items_to_receive") and not self.offer.get(
"items_to_give"
)

def is_scam(self) -> bool:
return self.offer.get('items_to_give') \
and not self.offer.get('items_to_receive')
return self.offer.get("items_to_give") and not self.offer.get(
"items_to_receive"
)

def is_valid(self) -> bool:
return True \
if self.offer.get('items_to_receive') \
and self.offer.get('items_to_give') \
and (self.has_escrow() \
or self.has_escrow() == decline_trade_hold) \
return (
True
if self.offer.get("items_to_receive")
and self.offer.get("items_to_give")
and (self.has_escrow() or self.has_escrow() == decline_trade_hold)
else False
)

def get_partner(self) -> str:
return account_id_to_steam_id(self.offer['accountid_other'])
return account_id_to_steam_id(self.offer["accountid_other"])

def is_from_owner(self) -> bool:
return self.get_partner() in owners
Loading

0 comments on commit f4e7981

Please sign in to comment.