Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import requests
- from datetime import datetime, timedelta
- import time
- API_KEY = ENTER_API_KEY
- BASE_URL = "https://api.torn.com/v2/faction"
- NO_NUMBER = 99999 # number of days to represent time since last OC when last OC can't be found
- def fetch_data(category: str) -> dict:
- """Make API call
- Parameters
- ----------
- category : str
- the category parameter for the API call. This relates to the OCs, examples being 'available', 'completeded', etc.
- Returns
- -------
- dict
- the json response
- Raises
- ------
- Exception
- raises error if API doesn't respond within 20 calls (0.5s between failed call)
- """
- params = {"key": API_KEY, "selections": "crimes,members", "cat": category}
- counter = 0
- while True:
- try:
- response = requests.get(BASE_URL, params=params)
- response.raise_for_status()
- return response.json()
- except requests.exceptions.RequestException as e:
- print(f"Error fetching {category} data: {e}")
- if counter > 20:
- break
- counter += 1
- time.sleep(0.5)
- raise Exception(f"API not responding, error: {response.status_code}") # type: ignore (incorrect warning)
- def get_criminals(crimes: list[dict]) -> list[int]:
- """Go through list of OCs and make a list of members currently in an OC
- Parameters
- ----------
- crimes : list[dict]
- The list of recruiting/planning OCs
- Returns
- -------
- list[int]
- The list of User IDs of members currently in an OC
- """
- our_criminals = []
- for crime in crimes:
- for role in crime["slots"]:
- if role["user_id"]:
- our_criminals.append(role["user_id"])
- return our_criminals
- def calculate_delta(slackers: dict) -> list[tuple[str, int, float]]:
- """Go through the dictionary of slackers (members not in an OC) and calculate how long it's been since their last OC.
- Return their names and the time as a list sorted by the time
- Parameters
- ----------
- slackers : dict
- dictionary containing the slackers, with keys being their IDs, and values being a dictionary containing info about their name and last_finished OC time.
- Returns
- -------
- list[tuple[str, int, float]]
- The list of slackers, stored as a tuple with their name and the time since last OC, in the format (name, days, hours)
- """
- results = []
- current_time = datetime.now().timestamp()
- for user, data in slackers.items():
- if data["last_finished"]:
- delta = timedelta(seconds=(current_time - data["last_finished"]))
- else:
- delta = timedelta(days=NO_NUMBER)
- results.append((data["name"], delta.days, round(delta.seconds / 60**2, 2)))
- return sorted(results, key=lambda time: (time[1], time[2]), reverse=True)
- def main():
- available_crimes_data = fetch_data("available")
- completed_crimes_data = fetch_data("completed")
- crimes = available_crimes_data.get("crimes", [])
- members = available_crimes_data.get("members", {})
- our_criminals = get_criminals(crimes)
- slackers = {
- m["id"]: {"name": m["name"], "last_finished": None}
- for m in members
- if m["id"] not in our_criminals
- }
- for c_crime in completed_crimes_data.get("crimes", []):
- for slot in c_crime["slots"]:
- if slot["user_id"] in slackers:
- if not slackers[slot["user_id"]]["last_finished"]:
- slackers[slot["user_id"]]["last_finished"] = c_crime["ready_at"]
- slacking = calculate_delta(slackers)
- for slacker in slacking:
- days, hours = slacker[1:]
- if days == NO_NUMBER:
- print(f"{slacker[0]} has not done any OCs!")
- else:
- print(
- f"{slacker[0]} last finished an OC {days} days and {hours} hours ago."
- )
- if __name__ == "__main__":
- main()
Add Comment
Please, Sign In to add comment