Beispiel #1
0
def _toggle_notification(bot, game, context, use_channel=False):
    """Adds the user or channel to the notifications list."""
    if use_channel:
        destination = 'c{}'.format(context.channel.id)
        destination_text = "This channel"
    else:
        destination = 'u{}'.format(context.author.id)
        destination_text = "You"
    key = game['key']
    game_text = '{} ({})'.format(game['game'], game['type'])
    pending_notification = utilities.get_schedule_entries(
        bot, __name__, search=key, destination=destination)
    if pending_notification:  # Remove from schedule
        utilities.remove_schedule_entries(bot,
                                          __name__,
                                          search=key,
                                          destination=destination)
        return "{} will no longer be notified when {} is about to be streamed.".format(
            destination_text, game_text)
    else:  # Add to schedule
        stream_url = configurations.get(bot, __name__, 'stream_url')
        current_time = datetime.datetime.utcnow()
        start_time, end_time = game['scheduled'], game['end']
        setup_delta = datetime.timedelta(seconds=game['setup_seconds'])

        if current_time < start_time:
            scheduled_seconds = start_time.replace(
                tzinfo=datetime.timezone.utc).timestamp()
            delta = utilities.get_time_string(scheduled_seconds - time.time(),
                                              text=True)
            info = 'GDQ game notification: {}'.format(game_text)
            payload = {
                'text': game_text,
                'end': scheduled_seconds + game['seconds']
            }
            utilities.schedule(bot,
                               __name__,
                               scheduled_seconds,
                               _notify,
                               payload=payload,
                               search=key,
                               destination=destination,
                               info=info)
            return ("{} will be notified when {} is about to be streamed!\n"
                    "(In approximately {})".format(destination_text, game_text,
                                                   delta))

        elif current_time < start_time + setup_delta:
            return "The game is scheduled to start soon!\nWatch it at {}".format(
                stream_url)
        elif current_time < end_time:
            return "The game has already started!\nWatch it at {}".format(
                stream_url)
        else:
            return "Sorry, this game has already been finished."
Beispiel #2
0
def create_txyz_tables(bot):
    data.db_create_table(bot,
                         'txyz_thoughts',
                         template='txyz_thoughts_template')
    data.db_create_table(bot, 'txyz_footers', template='txyz_footers_template')
    if not utilities.get_schedule_entries(bot, __name__, search='txyz_cycler'):
        utilities.schedule(bot,
                           __name__,
                           time.time(),
                           _cycle_timer,
                           search='txyz_cycler')
Beispiel #3
0
def _toggle_notification(bot, game, context, use_channel=False):
    """Adds the user or channel to the notifications list."""
    if use_channel:
        destination = 'c{}'.format(context.channel.id)
        destination_text = "This channel"
    else:
        destination = 'u{}'.format(context.author.id)
        destination_text = "You"
    key = game['key']
    game_text = '{} ({})'.format(game['game'], game['type'])
    pending_notification = utilities.get_schedule_entries(
        bot, __name__, search=key, destination=destination)
    if pending_notification:  # Remove from schedule
        utilities.remove_schedule_entries(bot, __name__, search=key, destination=destination)
        return "{} will no longer be notified when {} is about to be streamed.".format(
            destination_text, game_text)
    else:  # Add to schedule
        stream_url = configurations.get(bot, __name__, 'stream_url')
        current_time = datetime.datetime.utcnow()
        start_time, end_time = game['scheduled'], game['end']
        setup_delta = datetime.timedelta(seconds=game['setup_seconds'])

        if current_time < start_time:
            scheduled_seconds = start_time.replace(tzinfo=datetime.timezone.utc).timestamp()
            delta = utilities.get_time_string(scheduled_seconds - time.time(), text=True)
            info = 'GDQ game notification: {}'.format(game_text)
            payload = {
                'text': game_text,
                'end': scheduled_seconds + game['seconds']}
            utilities.schedule(
                bot, __name__, scheduled_seconds, _notify, payload=payload,
                search=key, destination=destination, info=info)
            return (
                "{} will be notified when {} is about to be streamed!\n"
                "(In approximately {})".format(destination_text, game_text, delta))

        elif current_time < start_time + setup_delta:
            return "The game is scheduled to start soon!\nWatch it at {}".format(stream_url)
        elif current_time < end_time:
            return "The game has already started!\nWatch it at {}".format(stream_url)
        else:
            return "Sorry, this game has already been finished."
Beispiel #4
0
async def _update_schedule(bot):
    """Reads the GDQ schedule and updates the information in the database."""
    schedule_url = configurations.get(bot, __name__, 'schedule_url')
    html_data = (await utilities.future(requests.get, schedule_url)).text
    soup = BeautifulSoup(html_data, 'html.parser')
    run_table = soup.find('table', {'id': 'runTable'})
    schedule_data = []
    game_list = []

    if run_table is None:
        raise CBException('Run table not found!')

    debug_weeks = data.get(bot, __name__, 'debug_weeks', default=0, volatile=True)
    current_data = {}
    for entry in run_table.find_all('tr'):
        entry_class = entry.get('class', [''])[0]

        if entry_class == 'day-split':
            continue

        subentries = [subentry.text for subentry in entry.find_all('td')]
        if subentries[0].startswith(' '):  # Second column
            subentries = subentries[:2]
        if entry_class == 'second-row':  # Extra data for the last game
            estimation, run_type = subentries
            split_estimate = estimation.split(':')
            estimation_seconds = (int(split_estimate[0])*3600 +
                                  int(split_estimate[1])*60 +
                                  int(split_estimate[2]))
            end_time = (
                current_data['scheduled'] + datetime.timedelta(
                    seconds=(estimation_seconds + current_data['setup_seconds'])))
            key_name = utilities.get_cleaned_filename(
                current_data['game'] + run_type, cleaner=True)
            current_data.update({
                'estimation': estimation.strip(),
                'seconds': estimation_seconds,
                'type': run_type,
                'end': end_time,
                'key': key_name
            })
            game_list.append(key_name)
            schedule_data.append(current_data)

        else:  # Happens first
            while len(subentries) < 4:
                subentries.append('')
            start_time_string, game, runners, setup_time = subentries
            start_time = datetime.datetime.strptime(start_time_string, '%Y-%m-%dT%H:%M:%SZ')
            setup_time = setup_time.strip()
            split_setup = setup_time.split(':')
            if len(split_setup) > 1:
                setup_seconds = (int(split_setup[0])*3600 +
                                 int(split_setup[1])*60 +
                                 int(split_setup[2]))
            else:
                setup_seconds = 0
            current_data = {
                'scheduled': start_time - datetime.timedelta(weeks=debug_weeks),
                'game': game,
                'runners': runners,
                'setup': setup_time,
                'setup_seconds': setup_seconds
            }

    # Add finale entry
    run_type = 'Party%'
    end_time = current_data['scheduled'] + datetime.timedelta(minutes=30)
    key_name = utilities.get_cleaned_filename(current_data['game'] + run_type, cleaner=True)
    current_data.update({
        'estimation': '0:30:00',
        'seconds': 60*30,
        'end': end_time,
        'type': run_type,
        'key': key_name
    })
    game_list.append(key_name)
    schedule_data.append(current_data)

    # Update scheduled notifications
    entries = utilities.get_schedule_entries(bot, __name__)
    for entry in entries:
        payload, key = entry[3:5]
        if key not in game_list:  # Not found error
            error_message = (
                ":warning: Warning: The game {} has been removed, renamed, or "
                "recategorized. You have been removed from the notification list "
                "for this game. Please check the schedule at {}.".format(
                    payload['text'], configurations.get(bot, __name__, 'schedule_url')))
            utilities.update_schedule_entries(
                bot, __name__, search=key, payload={'error': error_message}, new_time=time.time())
        else:
            game = schedule_data[game_list.index(key)]
            start_time, end_time = game['scheduled'], game['end']
            setup_delta = datetime.timedelta(seconds=game['setup_seconds'])
            scheduled = start_time.replace(tzinfo=datetime.timezone.utc).timestamp()
            current_time = datetime.datetime.utcnow()
            if start_time + setup_delta < current_time < end_time:
                stream_url = configurations.get(bot, __name__, 'stream_url')
                payload = {'error': (
                        "Uh oh. The schedule shifted drastically and I didn't notice "
                        "fast enough - sorry! {} is live right now at {}").format(
                            payload['text'], stream_url)}
            else:
                payload.update({'end': scheduled + game['seconds']})
            utilities.update_schedule_entries(
                bot, __name__, search=key, payload=payload, new_time=scheduled)

    # Save data
    data.add(bot, __name__, 'schedule', schedule_data, volatile=True)
    try:
        _update_current_game(bot)
    except:
        pass
Beispiel #5
0
def create_txyz_tables(bot):
    data.db_create_table(bot, 'txyz_thoughts', template='txyz_thoughts_template')
    data.db_create_table(bot, 'txyz_footers', template='txyz_footers_template')
    if not utilities.get_schedule_entries(bot, __name__, search='txyz_cycler'):
        utilities.schedule(bot, __name__, time.time(), _cycle_timer, search='txyz_cycler')
Beispiel #6
0
async def _update_schedule(bot):
    """Reads the GDQ schedule and updates the information in the database."""
    schedule_url = configurations.get(bot, __name__, 'schedule_url')
    html_data = (await utilities.future(requests.get, schedule_url)).text
    soup = BeautifulSoup(html_data, 'html.parser')
    run_table = soup.find('table', {'id': 'runTable'})
    schedule_data = []
    game_list = []

    if run_table is None:
        raise CBException('Run table not found!')

    debug_weeks = data.get(bot,
                           __name__,
                           'debug_weeks',
                           default=0,
                           volatile=True)
    current_data = {}
    for entry in run_table.find_all('tr'):
        entry_class = entry.get('class', [''])[0]

        if entry_class == 'day-split':
            continue

        subentries = [subentry.text for subentry in entry.find_all('td')]
        if entry_class == 'second-row':  # Extra data for the last game
            estimation, run_type = subentries
            split_estimate = estimation.split(':')
            estimation_seconds = (int(split_estimate[0]) * 3600 +
                                  int(split_estimate[1]) * 60 +
                                  int(split_estimate[2]))
            end_time = (current_data['scheduled'] + datetime.timedelta(
                seconds=(estimation_seconds + current_data['setup_seconds'])))
            key_name = utilities.get_cleaned_filename(current_data['game'] +
                                                      run_type,
                                                      cleaner=True)
            current_data.update({
                'estimation': estimation.strip(),
                'seconds': estimation_seconds,
                'type': run_type,
                'end': end_time,
                'key': key_name
            })
            game_list.append(key_name)
            schedule_data.append(current_data)

        else:  # Happens first
            while len(subentries) < 4:
                subentries.append('')
            start_time_string, game, runners, setup_time = subentries
            start_time = datetime.datetime.strptime(start_time_string,
                                                    '%Y-%m-%dT%H:%M:%SZ')
            setup_time = setup_time.strip()
            split_setup = setup_time.split(':')
            if len(split_setup) > 1:
                setup_seconds = (int(split_setup[0]) * 3600 +
                                 int(split_setup[1]) * 60 +
                                 int(split_setup[2]))
            else:
                setup_seconds = 0
            current_data = {
                'scheduled':
                start_time - datetime.timedelta(weeks=debug_weeks),
                'game': game,
                'runners': runners,
                'setup': setup_time,
                'setup_seconds': setup_seconds
            }

    # Add finale entry
    run_type = 'Party%'
    end_time = current_data['scheduled'] + datetime.timedelta(minutes=30)
    key_name = utilities.get_cleaned_filename(current_data['game'] + run_type,
                                              cleaner=True)
    current_data.update({
        'estimation': '0:30:00',
        'seconds': 60 * 30,
        'end': end_time,
        'type': run_type,
        'key': key_name
    })
    game_list.append(key_name)
    schedule_data.append(current_data)

    # Update scheduled notifications
    entries = utilities.get_schedule_entries(bot, __name__)
    for entry in entries:
        payload, key = entry[3:5]
        if key not in game_list:  # Not found error
            error_message = (
                ":warning: Warning: The game {} has been removed, renamed, or "
                "recategorized. You have been removed from the notification list "
                "for this game. Please check the schedule at {}.".format(
                    payload['text'],
                    configurations.get(bot, __name__, 'schedule_url')))
            utilities.update_schedule_entries(bot,
                                              __name__,
                                              search=key,
                                              payload={'error': error_message},
                                              time=time.time())
        else:
            game = schedule_data[game_list.index(key)]
            start_time, end_time = game['scheduled'], game['end']
            setup_delta = datetime.timedelta(seconds=game['setup_seconds'])
            scheduled = start_time.replace(
                tzinfo=datetime.timezone.utc).timestamp()
            current_time = datetime.datetime.utcnow()
            if start_time + setup_delta < current_time < end_time:
                stream_url = configurations.get(bot, __name__, 'stream_url')
                payload = {
                    'error':
                    ("Uh oh. The schedule shifted drastically and I didn't notice "
                     "fast enough - sorry! {} is live right now at {}").format(
                         payload['text'], stream_url)
                }
            else:
                payload.update({'end': scheduled + game['seconds']})
            utilities.update_schedule_entries(bot,
                                              __name__,
                                              search=key,
                                              payload=payload,
                                              time=scheduled)

    # Save data
    data.add(bot, __name__, 'schedule', schedule_data, volatile=True)
    try:
        _update_current_game(bot)
    except:
        pass