Guest User

Untitled

a guest
Jan 11th, 2025
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.98 KB | None | 0 0
  1. import requests
  2. from datetime import datetime, timedelta
  3. import time
  4.  
  5. API_KEY = ENTER_API_KEY
  6. BASE_URL = "https://api.torn.com/v2/faction"
  7. NO_NUMBER = 99999 # number of days to represent time since last OC when last OC can't be found
  8.  
  9.  
  10. def fetch_data(category: str) -> dict:
  11.     """Make API call
  12.  
  13.    Parameters
  14.    ----------
  15.    category : str
  16.       the category parameter for the API call. This relates to the OCs, examples being 'available', 'completeded', etc.
  17.  
  18.    Returns
  19.    -------
  20.    dict
  21.        the json response
  22.  
  23.    Raises
  24.    ------
  25.    Exception
  26.        raises error if API doesn't respond within 20 calls (0.5s between failed call)
  27.    """
  28.     params = {"key": API_KEY, "selections": "crimes,members", "cat": category}
  29.     counter = 0
  30.     while True:
  31.         try:
  32.             response = requests.get(BASE_URL, params=params)
  33.             response.raise_for_status()
  34.             return response.json()
  35.         except requests.exceptions.RequestException as e:
  36.             print(f"Error fetching {category} data: {e}")
  37.             if counter > 20:
  38.                 break
  39.             counter += 1
  40.             time.sleep(0.5)
  41.  
  42.     raise Exception(f"API not responding, error: {response.status_code}")  # type: ignore (incorrect warning)
  43.  
  44.  
  45. def get_criminals(crimes: list[dict]) -> list[int]:
  46.     """Go through list of OCs and make a list of members currently in an OC
  47.  
  48.    Parameters
  49.    ----------
  50.    crimes : list[dict]
  51.       The list of recruiting/planning OCs
  52.  
  53.    Returns
  54.    -------
  55.    list[int]
  56.        The list of User IDs of members currently in an OC
  57.    """
  58.     our_criminals = []
  59.     for crime in crimes:
  60.         for role in crime["slots"]:
  61.             if role["user_id"]:
  62.                 our_criminals.append(role["user_id"])
  63.     return our_criminals
  64.  
  65.  
  66. def calculate_delta(slackers: dict) -> list[tuple[str, int, float]]:
  67.     """Go through the dictionary of slackers (members not in an OC) and calculate how long it's been since their last OC.
  68.    Return their names and the time as a list sorted by the time
  69.  
  70.    Parameters
  71.    ----------
  72.    slackers : dict
  73.        dictionary containing the slackers, with keys being their IDs, and values being a dictionary containing info about their name and last_finished OC time.
  74.  
  75.    Returns
  76.    -------
  77.    list[tuple[str, int, float]]
  78.        The list of slackers, stored as a tuple with their name and the time since last OC, in the format (name, days, hours)
  79.    """
  80.     results = []
  81.     current_time = datetime.now().timestamp()
  82.     for user, data in slackers.items():
  83.         if data["last_finished"]:
  84.             delta = timedelta(seconds=(current_time - data["last_finished"]))
  85.         else:
  86.             delta = timedelta(days=NO_NUMBER)
  87.         results.append((data["name"], delta.days, round(delta.seconds / 60**2, 2)))
  88.     return sorted(results, key=lambda time: (time[1], time[2]), reverse=True)
  89.  
  90.  
  91. def main():
  92.     available_crimes_data = fetch_data("available")
  93.     completed_crimes_data = fetch_data("completed")
  94.  
  95.     crimes = available_crimes_data.get("crimes", [])
  96.     members = available_crimes_data.get("members", {})
  97.  
  98.     our_criminals = get_criminals(crimes)
  99.     slackers = {
  100.         m["id"]: {"name": m["name"], "last_finished": None}
  101.         for m in members
  102.         if m["id"] not in our_criminals
  103.     }
  104.  
  105.     for c_crime in completed_crimes_data.get("crimes", []):
  106.         for slot in c_crime["slots"]:
  107.             if slot["user_id"] in slackers:
  108.                 if not slackers[slot["user_id"]]["last_finished"]:
  109.                     slackers[slot["user_id"]]["last_finished"] = c_crime["ready_at"]
  110.  
  111.     slacking = calculate_delta(slackers)
  112.     for slacker in slacking:
  113.         days, hours = slacker[1:]
  114.         if days == NO_NUMBER:
  115.             print(f"{slacker[0]} has not done any OCs!")
  116.         else:
  117.             print(
  118.                 f"{slacker[0]} last finished an OC {days} days and {hours} hours ago."
  119.             )
  120.  
  121.  
  122. if __name__ == "__main__":
  123.     main()
  124.  
Add Comment
Please, Sign In to add comment