Ejemplo n.º 1
0
def try_request(request_url: str, method: str = "GET", **kwargs) -> Response:
    """Requests a response object and returns it if successful, otherwise None is returned.
    If the website is in cloudflare IUAM mode, we also return None."""
    response = None

    log(f"GET {request_url}", postfix="requests")

    try:
        response = requests.request(method, request_url, **kwargs)
    except requests.exceptions.ConnectionError:
        log_err(
            f"WARNING | ConnectionError was raised on GET \"{request_url}\"")
        return None
    except requests.exceptions.ReadTimeout:
        log_err(f"WARNING | ReadTimeout was raised on GET \"{request_url}\"")
        return None

    if "<title>Just a moment...</title>" in response.text:
        log_err("WARNING | CloudFlare IUAM is active")
        return None

    log(f"RECEIVED {response.status_code}: {response.reason}",
        postfix="requests")

    return response
Ejemplo n.º 2
0
    def retrieve_table_data(self,
                            table: str,
                            where: str = None,
                            where_values: tuple = None,
                            selection: str = "*",
                            group_by: str = None,
                            order_by: str = None,
                            limit: int = None) -> List[tuple]:
        """Returns all rows from the table where the WHERE clause applies (e.g. `where` as "type=%s AND id=%s" and 
        `where_values` as ("nominate", 5)), if specified, otherwise any data present in the table."""
        group_by = f"\nGROUP BY {group_by}" if group_by else ""
        order_by = f"\nORDER BY {order_by}" if order_by else ""
        limit = f"\nLIMIT {limit}" if limit else ""

        if where and ("ORDER BY" in where or "LIMIT" in where):
            log("WARNING | Found special in `where` variable. This should probably be in `order_by`/`limit` variables."
                )

        return self._execute(
            """
            SELECT %(selection)s FROM %(db_name)s.%(table)s
            WHERE %(where)s
            """ % InterpolationDict(selection=selection,
                                    db_name=self.db_name,
                                    table=table,
                                    where=where if where else "TRUE") +
            (group_by + order_by + limit), where_values)
Ejemplo n.º 3
0
 def __get_cursor(self):
     attempts = 0
     while (attempts < 3):
         attempts += 1
         try:
             return self.connection.cursor()
         except OperationalError as error:
             log(f"WARNING | {error}")
             self.__init__(self.db_name)
Ejemplo n.º 4
0
async def parse_events(event_list, async_event_generator, current_time, last_time, last_checked_time) -> None:
    """Parses events generated by the given function over the timeframe and appends them to the event list."""
    log(f"--- Parsing Events from {last_time} to {current_time} ---")
    async for event in async_event_generator(current_time, last_time, last_checked_time):
        progress_ratio = (current_time - event.time).total_seconds() / (current_time - last_time).total_seconds()
        progress_str = (
            fmt(" " * int(progress_ratio       * 20), colors.LOADING_FILLED) +
            fmt(" " * int((1 - progress_ratio) * 20), colors.LOADING_EMPTY )
        )
        
        log(f"{progress_str} | {format_event_log(event)}")
        event_list.append(event)
Ejemplo n.º 5
0
def insert_db(events) -> None:
    """Inserts the given event list into the database in reversed order."""
    if not events:
        return
    
    events.sort(key=lambda event: event.time)

    log(f"--- Inserting {len(events)} Events into the Database ---")
    for event in events:
        log(".", newline=False)
        database.insert_event(event)
    log()
Ejemplo n.º 6
0
 async def on_event(self, event: Event):
     if event.type in EXPECTED_TYPES and (not event.user
                                          or event.user.id != 3):
         log(event, postfix=self.reader_id)
         interface.insert_event(event)
Ejemplo n.º 7
0
 async def on_event(self, event: Event):
     log(event, postfix=self.reader_id)
     await subscriber.forward(event, self.client)
Ejemplo n.º 8
0
    async def on_ready(self) -> None:
        log(f"Ready!", postfix="bot")

        if not self.reader.running:
            await self.reader.run()
Ejemplo n.º 9
0
 async def on_connect(self) -> None:
     log(f"Connected as {self.user}!", postfix="bot")
     asyncio.create_task(activity.loop(self, self.reader))
Ejemplo n.º 10
0
def last_updated(current_time: datetime, _id: str) -> None:
    """Updates the last updated file to reflect the given time."""
    log(f"--- Last Updated [{_id}] {current_time} ---")
    timestamp.set_last(current_time, _id)
Ejemplo n.º 11
0
 async def on_event(self, event: Event):
     if event.type in EXPECTED_TYPES: #and "catch" in event.beatmapset.modes:
         logger.log(event, postfix=self.reader_id)
         interface.insert_event(event)