discordalerts/app.py

157 lines
4.2 KiB
Python
Raw Normal View History

2021-06-21 02:10:02 +01:00
import discum
from typing import List
import webbrowser
import re
from bs4 import BeautifulSoup
import requests
from dotenv import load_dotenv
from os import getenv
PRICE_REGEX = re.compile(
"(?:(?P<currency>[GBP|EUR|£|€])(?P<price>[0-9]+(?:\.[0-9]{1,2})))")
MODEL_REGEX = re.compile("[Rr][Tt][Xx] ?(?P<model>30[6789]0( [Tt][Ii])?).?")
URL_REGEX = re.compile(
"(?:(?:https?|ftp):\/\/|\b(?:[a-z\d]+\.))(?:(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))?\))+(?:\((?:[^\s()<>]+|(?:\(?:[^\s()<>]+\)))?\)|[^\s`!()\[\]{};:'.,<>?«»“”‘’]))?")
2021-06-21 02:10:02 +01:00
PARTALERT_ASIN = re.compile("asin=(?P<asin>[0-9a-zA-Z]{1,10})")
PARTALERT_TLD = re.compile("tld=(?P<tld>\.(?:it|es|de|fr|co\.uk))")
MONITORED_CHANNELS = [802674527850725377, 802674601519611925, 755728127069519913,
802674384120446996, 755727814912901170, 783425011116539964,
783682409635250187, 761002102804709448, 802674800786145311,
758224323843850250, 760577787332788315, 802674552541806662,
706910639959834738, 802674584473567303, 839507735531749446,
833700313819119676, 713321461124694056, 721009876893040682]
load_dotenv()
# load env vars from .env file
token = getenv("TOKEN")
if not token:
print("Could not load environmental variables. Make sure TOKEN is set in .env")
exit(0)
bot = discum.Client(token=token, log={"console": False, "file": False})
########################################
# Callbacks
########################################
def get_soup(url: str):
2021-06-21 02:10:02 +01:00
r = requests.get(url)
return BeautifulSoup(r.text)
def get_stockinformer_url(url: str) -> str:
bs = get_soup(url)
2021-06-21 02:10:02 +01:00
for a in bs.find_all("a"):
2021-06-21 02:10:02 +01:00
if "view at" in a.text.lower():
return f"https://stockinformer.co.uk/{a.get('href')}"
return None
def get_partalert_url(url: str) -> str:
ret_url = None
bs = get_soup(url)
for a in bs.find_all("a"):
if "amazon" in a.text.lower():
amazon_url = a.get("href")
try:
asin = PARTALERT_ASIN.search(amazon_url).group('asin')
tld = PARTALERT_TLD.search(amazon_url).group('tld')
ret_url = f"https://amazon{tld}/dp/{asin}"
except Exception as e:
print(f"Exception: {e}")
return ret_url
2021-06-21 02:10:02 +01:00
def check_urls(urls: List[str]):
for url in urls:
print(f"Received {url}")
if "partalert" in url:
url = get_partalert_url(url)
2021-06-21 02:10:02 +01:00
if not url:
2021-06-21 02:10:02 +01:00
continue
elif "stockinformer" in url:
url = get_stockinformer_url(url)
if not url:
continue
webbrowser.open(url)
print(f'Opened {url}')
def check_price(message: str) -> bool:
prices = {
"3060 ti": {"gbp": 500, "eur": 600},
"3070": {"gbp": 680, "eur": 850},
"3080": {"gbp": 880, "eur": 1000},
"3090": {"gbp": 1450, "eur": 1650}
}
try:
price = float(PRICE_REGEX.search(message).group("price"))
currency = PRICE_REGEX.search(message).group("currency")
model = MODEL_REGEX.search(message).group("model").lower()
if currency == "£":
currency = "gbp"
elif currency == "":
currency = "eur"
else:
currency = currency.lower()
if model == "3060":
return False
print(f"Model: {model}, Price: {currency}{price:0.2f}")
if price <= prices[model][currency]:
return True
except Exception as e:
return False
return False
@bot.gateway.command
def on_message(resp):
urls = []
2021-06-21 02:10:02 +01:00
if resp.event.ready_supplemental:
bot.gateway.subscribeToGuildEvents(wait=1)
if resp.event.message:
m = resp.parsed.auto()
channel_id = int(m['channel_id'])
2021-06-21 02:10:02 +01:00
content = m['content']
embeds = m['embeds']
2021-06-21 02:10:02 +01:00
if channel_id in MONITORED_CHANNELS:
# search for urls in message text
urls.append(URL_REGEX.findall(content))
# search for urls in embeds
for e in embeds:
urls.append(URL_REGEX.findall(e['value']))
2021-06-21 02:10:02 +01:00
if (urls):
check_urls(urls)
print("Initialized.")
bot.gateway.run(auto_reconnect=True)