Created
August 18, 2021 17:01
-
-
Save dhgouveia2/5718a5950213915d318fcfb6d602e234 to your computer and use it in GitHub Desktop.
Simple Telegram Bot that notifies me when an item is sold in GW2 Trading Post
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python | |
import requests | |
import json | |
from datetime import datetime | |
GW2_API_KEY = "" # Get it from https://account.arena.net/applications with 'account', 'tradingpost' scopes | |
GW2_API_LANG = "en" # en, es, de, fr and zh: https://wiki.guildwars2.com/wiki/API:2#Localisation | |
TELEGRAM_API_KEY = "" # Get this from telegram using @BotFather | |
TELEGRAM_CHAT_ID = [""] # Search how to get the chatID of your username or use @RawDataBot | |
TELEGRAM_BOT_ID = "" # Get the Bot ID from @BotFather | |
# Get previous time of check | |
DT = datetime.utcnow() # Getting the current date and time in UTC | |
CURRENT_TIME = int(datetime.timestamp(DT)) # UTC Time | |
LAST_TIME_FILE = "last_check.log" | |
# logs | |
def _log(msg): | |
now = datetime.today().strftime('%Y-%m-%d') | |
log = "[ {} ] {}\n".format(now, msg) | |
f = open("debug.log", "a+").write(str(log)) | |
# Created the file if it doesn't exist | |
try: | |
with open(LAST_TIME_FILE, "x") as f: | |
_log("{}, File Created".format(LAST_TIME_FILE)) | |
except FileExistsError: | |
pass | |
# Read the last check time from the file | |
with open(LAST_TIME_FILE, 'r') as f: | |
LAST_TIME = f.read() | |
if LAST_TIME: | |
LAST_TIME = int(LAST_TIME) | |
# Compare the current time with the last check time | |
LAST_TIME = CURRENT_TIME if not LAST_TIME else LAST_TIME | |
# Request the API | |
def GW2API(endpoint, api_key = ''): | |
headers = { | |
'Authorization': 'Bearer {}'.format(api_key), | |
'Content-Type' : 'application/json' | |
} | |
try: | |
url = 'https://api.guildwars2.com/v2/{}'.format(endpoint) | |
resp = requests.get(url, headers=headers) | |
return resp.json() | |
except requests.exceptions.HTTPError as errh: | |
_log("Http Error: {}".format(errh)) | |
except requests.exceptions.ConnectionError as errc: | |
_log("Error Connecting: {}".format(errc)) | |
except requests.exceptions.Timeout as errt: | |
_log("Timeout Error: {}".format(errt)) | |
except requests.exceptions.RequestException as err: | |
_log("Error: {}".format(err)) | |
def priceToGold(price): | |
# Convert number to 000000 format | |
price_formated = str(price).zfill(6) | |
# Ignore the first four digits(characters) from right to left, and obtain the remaining digits(characters) | |
gold = price_formated[0:-4] | |
# Ignore the first two digits(characters) from right to left and get the two next ones | |
silver = price_formated[-4:-2] | |
# Get the first two digits from(characters) right to left and ignore the rest of digits(characters) | |
bronze = price_formated[-2:] | |
return gold, silver, bronze | |
def sendMessage(api_key, bot_id, chat_ids, text): | |
url = "https://api.telegram.org/{}:{}/sendMessage".format(bot_id, api_key) | |
for chat_id in chat_ids: | |
if chat_id: | |
payload = { | |
'chat_id': '{}'.format(chat_id), | |
'text': '{}'.format(text) | |
} | |
headers = { | |
'Content-Type': 'application/json' | |
} | |
try: | |
response = requests.request( | |
"POST", | |
url, | |
headers=headers, | |
json=payload | |
) | |
except requests.exceptions.HTTPError as errh: | |
_log("Http Error: {}".format(errh)) | |
except requests.exceptions.ConnectionError as errc: | |
_log("Error Connecting: {}".format(errc)) | |
except requests.exceptions.Timeout as errt: | |
_log("Timeout Error: {}".format(errt)) | |
except requests.exceptions.RequestException as err: | |
_log("Error: {}".format(err)) | |
# Get History sells | |
# https://wiki.guildwars2.com/wiki/API:2/commerce/transactions | |
solds = {} | |
item_ids = [] | |
resp = GW2API("/commerce/transactions/history/sells", GW2_API_KEY); | |
if resp: | |
for item in resp: | |
# Group all the sold items that were purchased | |
# after the last check time | |
item_time = int(datetime.strptime(item['purchased'], "%Y-%m-%dT%H:%M:%S%z").timestamp()) # fortunally this time is on UTC | |
if item_time >= LAST_TIME: | |
solds[(item['item_id'])] = item | |
item_ids.append(item['item_id']) | |
# Update last time of check | |
f = open(LAST_TIME_FILE, "w+").write(str(CURRENT_TIME)) | |
# Get extended items info (name, icon) | |
if len(item_ids) > 0: | |
# https://wiki.guildwars2.com/wiki/API:2/items | |
item_ids_joined = ','.join(map(str, item_ids)) | |
items_info = GW2API("/items?lang={}&ids={}".format(GW2_API_LANG,item_ids_joined)) | |
if type(item_ids_joined) is dict: | |
if items_info['text']: | |
_log("Error: {}".format(items_info['text'])) | |
exit() | |
# Build message | |
message = "" | |
for item_extended in items_info: | |
item = solds[item_extended['id']] | |
price = priceToGold(item['price']) | |
message += "\nItem: {}".format(item_extended['name']) | |
message += "\nPrice: {}".format(price) | |
message += "\nQty: {}".format(item['quantity']) | |
message += "\n{}".format(item_extended['icon']) | |
message += "\n-----------" | |
# Send Telegram message | |
if message: | |
message = "Solds: {}".format(message) | |
sendMessage(TELEGRAM_API_KEY,TELEGRAM_BOT_ID, TELEGRAM_CHAT_ID, message) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment