Skip to content

Instantly share code, notes, and snippets.

@necessary129
Created April 10, 2023 12:13
Show Gist options
  • Save necessary129/64cdca7fe6315bcbe53c5fb87be79e03 to your computer and use it in GitHub Desktop.
Save necessary129/64cdca7fe6315bcbe53c5fb87be79e03 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import requests
import datetime
import pickle
import json
import os
from pathlib import Path
from bs4 import BeautifulSoup
def save_cache(messes):
today = datetime.datetime.now().date()
data = {"date": today, "messes": messes}
with (Path.home() / ".messes.pck").open(mode="wb") as f:
pickle.dump(data, f)
def load_cache():
with (Path.home() / ".messes.pck").open(mode="rb") as f:
return pickle.load(f)
def get_messes():
USERNAME = os.environ["MESS_USERNAME"]
PASSWORD = os.environ["MESS_PASSWORD"]
DESTINATION = "https://mess.iiit.ac.in/"
FINAL_DESTINATION = "https://mess.iiit.ac.in/mess/web/index.php"
session = requests.Session()
r = session.get(
"https://login.iiit.ac.in/cas/login", params={"service": DESTINATION}
)
soup = BeautifulSoup(r.text, "html.parser")
execution_val = soup.find("input", attrs={"name": "execution"})["value"]
r = session.post(
"https://login.iiit.ac.in/cas/login",
params={"service": DESTINATION},
data={
"username": USERNAME,
"password": PASSWORD,
"execution": execution_val,
"_eventId": "submit",
},
)
r = session.get(FINAL_DESTINATION)
soup = BeautifulSoup(r.text, "html.parser")
KEYS = {"breakfast", "lunch", "dinner"}
messes = {}
for row in soup.find_all("tr"):
key, *values = row.find_all("td")
if key.text.strip() in KEYS and "hrs" not in values[0].text:
messes[key.text.strip()] = values[0].text.strip()
save_cache(messes)
return messes
def get_messes_cached():
messes = dict()
try:
messes = get_messes()
except requests.ConnectionError:
data = load_cache()
if data["date"] == datetime.datetime.now().date():
messes = data["messes"]
return messes
def get_next_mess():
END_TIMINGS = {
datetime.time(hour=9, minute=30): "breakfast",
datetime.time(hour=14, minute=30): "lunch",
datetime.time(hour=23, minute=59): "dinner",
}
messes = get_messes_cached()
if not messes:
return "Unknown", "Unknown", "Unknown"
now = datetime.datetime.now()
today = now.date()
next_time = "breakfast"
for timing, time in END_TIMINGS.items():
if now < datetime.datetime.combine(today, timing, tzinfo=now.tzinfo):
next_time = time
break
next_mess = f"{next_time.capitalize()}: {messes[next_time]}"
return (
next_mess,
"\n".join((": ".join((x.capitalize(), y)) for x, y in messes.items())),
next_time,
)
def main():
out = get_next_mess()
print(
json.dumps(
{
"text": out[0],
"tooltip": out[1],
"time": out[2],
"class": "nonveg" if "Non" in out[0] else "veg",
}
)
)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment