def application(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) d = parse_qs(env["QUERY_STRING"]) if "get_config" in d: guid = guidhelper.new_guid() return [json.dumps({ "new_guid": guidhelper.new_guid(), "client_id": settings.get_client_id(), "oauth_url": settings.get_oauth_url(), "url": settings.get_url(), "dev_url": settings.get_dev_url(), "sandbox_url": settings.get_sandbox_url(), "prod_url": settings.get_prod_url(), }).encode()] if "guid" not in d: return error("Parameter guid required") guid = d["guid"][0] if not guidhelper.validate_uuid4(guid): return error("Parameter guid must be a valid guid") code = d["code"][0] if "code" in d else "" row = db.get_row(guid) if not row: row = db.new_row(guid) if code and not row["code"]: row["code"] = code db.put_row(row) if not row.get("bearer"): if not code: return error("Parameter code required for guid without bearer") url = settings.get_token_url() + "v1/token" response = requests.post(url, params={ "grant_type": "authorization_code", "code": code, "redirect_uri": settings.get_url(), "client_id": settings.get_client_id(), "client_secret": settings.get_client_secret() }).json() if "error" in response: return [json.dumps(response).encode()] if "access_token" not in response: return [json.dumps({"error": "No access_token returned", "raw_reply": response}).encode()] row["bearer"] = response["access_token"] db.put_row(row) print("Creating thread...") t = threading.Thread(target=prefetch_session, args=(row,)) print("Starting thread...") t.start() print("Thread running.") return [json.dumps({"success": "success"}).encode()]
def add(ctx): """ Adds a quote from the content of the message to the current quotes Parameters: ctx: The context of the message Returns: str: The quote which has been added """ response = '' if ctx.author.is_mod or (settings.vip_quotes_allowed() and util.is_vip(ctx.author.badges)): # Puts provided quote into a single string, without including the '!addquote' at the start msg = ' '.join(map(str, ctx.content.split()[1:])) if msg: today = datetime.today() date = str(today.day) + '/' + str(today.month) + '/' + str( today.year) # If no stored quotes, sets first entry as quote number 1. Otherwise adds one to the last key in quotes (the last quote number) if len(quotes) == 0: number = '1' else: number = str(int(list(quotes.keys())[-1]) + 1) game = util.getGameName(ctx, settings.get_client_id(), settings.get_client_secret(), settings.get_channel()) quote = msg # Build dictionary to associate date and game with the quote raw_quote = {"date": date, "quote": quote, "game": game} quotes[number] = raw_quote save_quotes(quotes) response = f"{number}: {quotes[number]['quote']} - while streaming {quotes[number]['game']} on {quotes[number]['date']}" return response
def request_bunq_oauth(self): url = (settings.get_oauth_url() + 'auth?' + 'response_type=code&' + 'client_id=' + settings.get_client_id() + '&' + 'redirect_uri=' + settings.get_url() + 'sheet&' + 'state=' + guidhelper.new_guid()) self.start_response('302 Found', [('Location', url)]) return []
def item_detail_search(ctx): """ Returns a string containing details about the item specified by the message content Parameters: ctx: The context of the message Returns: str: Contains details about the specified item """ response = '' if util.validateNumParameters(ctx.content, 2) and util.checkGame( ctx, settings.get_client_id(), settings.get_client_secret(), settings.get_channel(), 'rimworld'): search = ctx.content.split()[1].lower() tries = 2 for i in range(tries): try: with open(item_file()) as i: items = json.load(i) break except Exception as e: print(e) destroy_the_comma() for entry in items["items"]: if entry["abr"] == search: response = 'Item ' + search + ' costs ' + str( entry["price"] ) + ' coins. Item category: ' + entry["category"] return response
def event_search(ctx): """ Searches the users Rimworld installation for events containing the message content Parameters: ctx: The context of the message Returns: str: Containins up to 500 characters of matching events """ response = '' if util.validateNumParameters(ctx.content, 2) and util.checkGame( ctx, settings.get_client_id(), settings.get_client_secret(), settings.get_channel(), 'rimworld'): search = ctx.content.split()[1].lower() with open(event_file()) as e: events = json.load(e) # Follows same logic as item search for field in events["incitems"]: if search in field["abr"]: response = response + field["abr"] + ':' + str( field["price"]) + ', ' if len(response) > 500: response = response[0:495] + ' ... ' response = response[:-2] return response
def mod_list(ctx): """ Creates response containing rimworld mods Returns: str: Mod list, as entered in settings.xml """ response = '' if util.checkGame(ctx, settings.get_client_id(), settings.get_client_secret(), settings.get_channel(), 'rimworld'): response = settings.get_rimworld_mods() return response
def get_uptime(): """ Returns a string of the current uptime Returns: str: Contains the current amount of uptime for the channel """ # Set up twitch API call and get stream info client = TwitchHelix(client_id=settings.get_client_id(), client_secret=settings.get_client_secret()) client.get_oauth() stream = client.get_streams(user_logins=settings.get_channel())._queue[0] # Get stream start time (API sends UTC time) and calculate uptime start_time = stream["started_at"] uptime = datetime.utcnow() - start_time return str(uptime).split(".")[0]
def item_search(ctx): """ Searches the users Rimworld installation for items matching the message content Parameters: ctx: The context of the message Returns: str: Contains up to 500 characters of matching items """ response = '' if util.validateNumParameters(ctx.content, 2) and util.checkGame( ctx, settings.get_client_id(), settings.get_client_secret(), settings.get_channel(), 'rimworld'): # Get item to search from message search = ctx.content.split()[1].lower() tries = 2 # Allows for a retry if the items file had to have the extraneous comma removed to fix the json formatting for _ in range(tries): try: with open(item_file()) as f: items_json = json.load(f) break except Exception as e: print(e) destroy_the_comma() # Kill it. # Find all items containing search term and append to response string for field in items_json["items"]: if search in field["abr"]: response = response + field["abr"] + ':' + str( field["price"]) + ', ' # Trim response below 500ch max if necessary if len(response) > 500: response = response[0:495] + ' ... ' # Cut trailing ', ' from response response = response[:-2] return response
def create_bunq_installation(self, code): url = settings.get_token_url() + "v1/token" response = requests.post(url, params={ "grant_type": "authorization_code", "code": code, "redirect_uri": settings.get_url() + "sheet", "client_id": settings.get_client_id(), "client_secret": settings.get_client_secret() }).json() if "error" in response: return self.error(response) if "access_token" not in response: return self.error({ "error": "No access_token returned", "raw_reply": response }) self.row = db.new_row(self.guid) self.row["bearer"] = response["access_token"] db.put_row(self.row) return self.request_google_oauth()
def event_detail_search(ctx): """ Returns a string containing details about the event specified by the message content Parameters: ctx: The context of the message Returns: str: Contains details about the specified event """ response = '' if util.validateNumParameters(ctx.content, 2) and util.checkGame( ctx, settings.get_client_id(), settings.get_client_secret(), settings.get_channel(), 'rimworld'): search = ctx.content.split()[1].lower() with open(event_file()) as e: events = json.load(e) for entry in events["incitems"]: if entry["abr"] == search: response = 'Event ' + search + ' costs ' + str( entry["price"] ) + ' coins. Karma type: ' + entry["karmatype"] return response
settings.configure_periodic_messages() chat_flag = True # Set up basic logging handler if settings.get_logging().lower() == 'debug': logLevel = logging.DEBUG else: logLevel = logging.CRITICAL logging.basicConfig(filename='FoxBot_log.txt', level=logLevel, format='%(asctime)s - %(levelname)s - %(message)s') # Initialize twitchio command bot bot = commands.Bot(irc_token=settings.get_app_token(), client_id=settings.get_client_id(), nick=settings.get_bot_account(), prefix=settings.get_prefix(), initial_channels=[settings.get_channel()]) #---------------------------------------------------# async def start_periodic_messages(): """ Sends messages to chat periodically Period (in minutes) is defined in settings Checks for recent activity in chat before sending messages (prevents filling an inactive chat) If multiple messages are configured, they are distributed evenly across the specified period If no messages are configured, periodically checks if message has been added