import asyncio import logging import requests import sys import time import csv from ast import literal_eval from datetime import datetime from question import QuestionHandler import networking from PyQt5.QtWidgets import QApplication from hq_gui import HQApp from quamash import QEventLoop, QThreadExecutor app = QApplication(sys.argv) loop = QEventLoop(app) asyncio.set_event_loop(loop) # Set up logging logging.basicConfig(filename="data.log", level=logging.INFO, filemode="w") # Read in bearer token and user ID with open("conn_settings.txt", "r") as conn_settings: BEARER_TOKEN = conn_settings.readline().strip().split("=")[1] USER_ID = conn_settings.readline().strip().split("=")[1] print("getting") main_url = f"https://api-quiz.hype.space/shows/now?type=hq&userId={USER_ID}" headers = {"Authorization": f"Bearer {BEARER_TOKEN}", "x-hq-client": "Android/1.6.1"} HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0", "Accept": "*/*", "Accept-Language": "en-US,en;q=0.5", "Accept-Encoding": "gzip, deflate"} # "x-hq-stk": "MQ==", # "Connection": "Keep-Alive", # "User-Agent": "okhttp/3.8.0"} q = QuestionHandler() hqApp = HQApp(q) import re import random trivia = [] with open('trivia2.csv', 'r') as csvfile: reader = csv.reader(csvfile) for row in reader: if row[1] == 'options': continue question = re.sub(r'^\d+\. ?', '', row[0].strip()) if 'which' not in question.lower(): continue answers = literal_eval(row[1]) if len(answers) != 3: continue correct = int(row[2]) trivia.append({'q': question, 'a': answers, 'c': correct}) i = 0 def getTrivia(): global i i += 1 result = requests.get('https://opentdb.com/api.php?amount=1&type=multiple').json()['results'][0] question = result['question'].replace('"', '').replace(''', "'") answers = [result['correct_answer']] + result['incorrect_answers'][:2] loop.create_task(q.answer_question(str(i), question, answers)) hqApp.button.clicked.connect(getTrivia) #hqApp.streamLive.emit('rtsp://184.72.239.149/vod/mp4:BigBuckBunny_175k.mov') #hqApp.videoFrame.raise_() #hqApp.button.hide() while True: print() try: app.processEvents() response_data = loop.run_until_complete( networking.get_json_response(main_url, timeout=1.5, headers=headers)) except Exception as e: import traceback print(traceback.format_exc()) print("Server response not JSON, retrying...") loop.run_until_complete(asyncio.sleep(1)) continue logging.info(response_data) if "broadcast" not in response_data or response_data["broadcast"] is None: if "error" in response_data and response_data["error"] == "Auth not valid": raise RuntimeError("Connection settings invalid") else: print("Show not on.") next_time = datetime.strptime(response_data["nextShowTime"], "%Y-%m-%dT%H:%M:%S.000Z") now = time.time() offset = datetime.fromtimestamp(now) - datetime.utcfromtimestamp(now) print(f"Next show time: {(next_time + offset).strftime('%Y-%m-%d %I:%M %p')}") print("Prize: " + response_data["nextShowPrize"]) hqApp.nextGameInfo.emit((next_time + offset).strftime('%Y-%m-%d %I:%M %p'), response_data['nextShowPrize']) if hqApp.streaming: hqApp.streamStop.emit() loop.run_until_complete(asyncio.sleep(5)) else: socket = response_data["broadcast"]["socketUrl"] stream = response_data["broadcast"]["streamUrl"] print(stream) print(f"Show active, connecting to socket at {socket}") if not hqApp.streaming: hqApp.streamLive.emit(stream) hqApp.videoFrame.raise_() loop.run_until_complete(networking.websocket_handler(q, socket, headers))