From 660fa7a7a92b65b05dbca17ee4753acd2065e615 Mon Sep 17 00:00:00 2001 From: Lertsenem Date: Tue, 7 Jul 2020 00:48:14 +0200 Subject: [PATCH] Add basic smash.gg request function --- lokrez/smashgg.py | 83 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 lokrez/smashgg.py diff --git a/lokrez/smashgg.py b/lokrez/smashgg.py new file mode 100644 index 0000000..a9d1bd8 --- /dev/null +++ b/lokrez/smashgg.py @@ -0,0 +1,83 @@ +# ============================================================================= +API_HOST = "api.smash.gg" +API_ENDPOINT = "gql/alpha" +API_SCHEME = "https" +API_URL = "{scheme}://{host}/{endpoint}".format( + scheme = API_SCHEME, + host = API_HOST, + endpoint = API_ENDPOINT, + ) + +# ============================================================================= +def run_query( + query_name, + variables = {}, + query_dir = "queries", + query_extension = "gql", + api_url = API_URL, + log = None, + ): + + # Load query + query_path = os.path.join( + query_dir, + "{}.{}".format( + query_name, + query_extension, + ) + ) + query = "" + + with open(query_path, 'r') as query_file: + query = query_file.read() + + # Build payload + payload = { + "query": query, + "variables": json.dumps(variables), + } + + # Build headers + headers = { + "Authorization": "Bearer {token}".format(token = args.token), + "Accept": "application/json", + "Content-Type": "application/json" + } + + # Send the query + try: + log.debug("Sending query '{}' with variables:".format(query_name)) + log.debug(json.dumps(variables)) + except AttributeError: + pass + + rv = requests.post( + API_URL, + json.dumps(payload).encode("utf-8"), + headers = headers, + proxies = {"http": args.proxy, "https": args.proxy}, + ) + + try: + rv_json = rv.json() + except Exception as e: + log.error("HTTP request failed") + log.error(e) + log.debug(e, exc_info=True) + log.debug(rv) + + # Try to return the data, or log the error and return None + try: + log.debug("query complexity : {}" \ + .format( + rv_json["extensions"]["queryComplexity"], + )) + return rv_json["data"] + except KeyError: + try: + log.error("GraphQL error") + log.error(rv_json) + except AttributeError: + pass + return None +