Exemplo n.º 1
0
def start_message_server(address, port_number):

    import time
    import datetime

    REQUEST_QUEUE_SIZE = 5
    self_server_address = (address, port_number)
    listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listen_socket.bind(self_server_address)
    listen_socket.listen(REQUEST_QUEUE_SIZE)
    print "Spawned server on address ", self_server_address

    while True:
        client_connection, client_address = listen_socket.accept()
        request = client_connection.recv(1024)
        print "length of message received ", len(request)
        print request

        # get the current time
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts)\
                .strftime('%Y-%m-%d %H:%M:%S')
        if "died" in request:
            execute_query("UPDATE PlayerAndCars SET PlayerAndCars.car_health = {health}, PlayerAndCars.deaths = PlayerAndCars.deaths + 1 WHERE PlayerAndCars.player_id = {player_id};"\
                            .format(health = 255, player_id =
                                int(request[7])), True)
        execute_query("INSERT INTO Events VALUES ('{information}','{timestamp}');"\
                .format(information = request, \
                            timestamp = st), True)

        if "Health" in request:
            new_health = int(filter(str.isdigit, request.split("!")[1]))
            execute_query("UPDATE PlayerAndCars SET PlayerAndCars.car_health = {health} WHERE PlayerAndCars.player_id = {player_id};".\
                    format(health = new_health, player_id = int(request[7])), \
                    True)

        if "Killed" in request:
            player_who_killed = int(
                filter(str.isdigit,
                       request.split("Killed")[1]))
            execute_query("INSERT INTO Events VALUES ('{information}', '{timestamp}');".\
                    format(information = "Gave upgrade to player " + \
                    str(player_who_killed), timestamp = st), True)
            execute_query("UPDATE PlayerAndCars SET PlayerAndCars.upgrades = PlayerAndCars.upgrades + 1 WHERE PlayerAndCars.player_id = {player_id};".\
                    format(player_id = player_who_killed), True)

        client_connection.close()
Exemplo n.º 2
0
def parse_log_file(filename):
    if filename.endswith(".gz"):
        fh = gzip.open(os.path.join("/home/aovtsinn/Documents/Python/logs", filename))
    else:
        fh = open(os.path.join("/home/aovtsinn/Documents/Python/logs", filename))
    urls = {}
    user_bytes = {}

    for line in fh:
        try:
            source_timestamp, request, response, referrer, _, agent, _ = line.split("\"")
            method, path, protocol = request.split(" ")
        except ValueError:
            continue # Skip garbage
        if path == "*": continue # Skip asterisk for path
        _, status_code, content_length, _ = response.split(" ")
        content_length = int(content_length)
        path = urllib.unquote(path)
        if path.startswith("/~"):
            username = path[2:].split("/")[0]
            try:
                user_bytes[username] = user_bytes[username] + content_length
            except:
                user_bytes[username] = content_length

        try:
            urls[path] = urls[path] + 1
        except:
            urls[path] = 1
    return urls, user_bytes
Exemplo n.º 3
0
    def handle(self):
        """Example link: http://localhost:9000/test?file=foo&signature=46b4ec586117154dacd49d664e5d63fdc88efb51
        Verify that the "signature" (HMAC-SHA1) on incoming requests is valid for "file".
        """
        request = self.rfile.readline().strip().decode()
        path = request.split()[1]
        result = urlparse(path)

        if result.path == '/test':
            q = parse_qs(result.query)

            file = q['file'][0].encode('ascii')
            digest = hmac_sha1(key, file).encode()
            signature = q['signature'][0].encode()

            if insecure_equals(digest, signature):
                print(request, "\t200 OK")
                self.wfile.write(self.RESPONSE_200)

            else:
                print(request, "\t500 BAD")
                self.wfile.write(self.RESPONSE_500)

        else:
            self.wfile.write(self.RESPONSE_500)
Exemplo n.º 4
0
def index(request):
	if bool(request):

		request = request.replace("%2C", "," )
		request = request.replace("%20", " " )
		fromm, to, percent, maxmin = request.split(":")

		from_cds = [gmaps.geocode(fromm)[0]['geometry']['location']['lat'], gmaps.geocode(fromm)[0]['geometry']['location']['lng']]
		to_cds = [gmaps.geocode(to)[0]['geometry']['location']['lat'], gmaps.geocode(to)[0]['geometry']['location']['lng']]

		print (from_cds)
		print (to_cds)
		print (percent)
		print (maxmin)

		current_session = Session_data(from_cds,to_cds,float(int(percent)/100))
		
		if maxmin == 'min':
			print ("Minimum elevation route follows these co-ordinates:")
			dist, ele_gain, route = current_session.min_elevation_route()
			route_coords = current_session.route_coordinates(route)
			print (route_coords)
			
		elif maxmin == 'max':
			print ("Maximum elevation route follows these co-ordinates:")
			dist, ele_gain, route = current_session.max_elevation_route()
			route_coords = current_session.route_coordinates(route)
			print (route_coords)

	return jsonify(elevation=ele_gain, distance=dist, waypoints=route_coords)
Exemplo n.º 5
0
    def get(self, request):
        requests = request.split('X')
        moves1 = requests[0].split(seperator)
        moves2 = requests[1].split(seperator)
        round = int(requests[2])
        environment.reset()
        if (moves1):
            for m1 in moves1:
                if m1:
                    environment.step((1, int(m1)))
        if (moves2):
            for m2 in moves2:
                if m2:
                    environment.step((-1, int(m2)))
        state = environment.state['board']
        mask = environment.state['moves'][1]

        minerals = round * 500
        actions = []
        fs = 0
        while environment.state['minerals'][1] < minerals:
            if fs > 200:
                break
            q_values = np.ma.array(agent.primary_network(state.reshape(1, -1)),
                                   mask=mask)
            myaction = np.argmax(q_values)
            environment.step((1, myaction))
            actions.append(myaction)
            fs += 1
        return {'task': seperator.join(str(x) for x in actions)}, 201
Exemplo n.º 6
0
def start_message_server(address, port_number):

    import time
    import datetime

    REQUEST_QUEUE_SIZE = 5
    self_server_address = (address, port_number)
    listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listen_socket.bind(self_server_address)
    listen_socket.listen(REQUEST_QUEUE_SIZE)
    print "Spawned server on address ", self_server_address

    while True:
        client_connection, client_address = listen_socket.accept()
        request = client_connection.recv(1024)
        print "length of message received ", len(request)
        print request

        # get the current time
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts)\
                .strftime('%Y-%m-%d %H:%M:%S')
        if "died" in request:
            execute_query("UPDATE PlayerAndCars SET PlayerAndCars.car_health = {health}, PlayerAndCars.deaths = PlayerAndCars.deaths + 1 WHERE PlayerAndCars.player_id = {player_id};"\
                            .format(health = 255, player_id =
                                int(request[7])), True)
        execute_query("INSERT INTO Events VALUES ('{information}','{timestamp}');"\
                .format(information = request, \
                            timestamp = st), True)

        if "Health" in request:
            new_health = int(filter(str.isdigit, request.split("!")[1]))
            execute_query("UPDATE PlayerAndCars SET PlayerAndCars.car_health = {health} WHERE PlayerAndCars.player_id = {player_id};".\
                    format(health = new_health, player_id = int(request[7])), \
                    True)

        if "Killed" in request:
            player_who_killed = int(filter(str.isdigit, 
                request.split("Killed")[1]))
            execute_query("INSERT INTO Events VALUES ('{information}', '{timestamp}');".\
                    format(information = "Gave upgrade to player " + \
                    str(player_who_killed), timestamp = st), True)
            execute_query("UPDATE PlayerAndCars SET PlayerAndCars.upgrades = PlayerAndCars.upgrades + 1 WHERE PlayerAndCars.player_id = {player_id};".\
                    format(player_id = player_who_killed), True)

        client_connection.close()
Exemplo n.º 7
0
def to12Hour(request):
    suffix = "AM"

    hourAndMin = request.split(':', 1)
    hours = int(hourAndMin[0])
    if hours / 12 > 1:
        hours = hours % 12
        suffix = "PM"

    return str(hours) + ':' + hourAndMin[1] + suffix
Exemplo n.º 8
0
    def parseLogs(self, file):
        # If the file is packed, then open it. Otherwise just open the file.
        if file.endswith(".gz"):
            fh = gzip.open(file)
        else:
            fh = open(file)
        keywords = "Windows", "Linux", "OS X", "Ubuntu", "Googlebot", "bingbot", "Android", "YandexBot", "facebookexternalhit"

        for line in fh:
            try:
                # Example line: 157.55.39.242 - - [20/Mar/2016:06:42:47 +0200] "GET /~jpoial/docs/api/index.html?java/awt/event/ContainerAdapter.html HTTP/1.1" 200 1417 "-" "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)"
                # Split line to extract data
                source, request, response, referrer, _, agent, _ = line.split("\"")
                method, path, protocol = request.split(" ")
                _, user, file = path.split("/", 3)
                _, code, traffic = response.split(" ", 2)
                ips, rfc, uid, timez, zone = source.split(" ", 4)

                # Format date to make timeline
                stamped = datetime.strptime(timez, "[%d/%b/%Y:%H:%M:%S")
                if (self.first > stamped):
                    self.first = stamped
                if (self.last < stamped):
                    self.last = stamped

                # Check for referers
                _, netloc, refpath, _, _, _ = urlparse(referrer)
                if netloc == "":
                    netloc = "direct"
                self.r[netloc] += 1

                # mark visited countrys
                if ips:
                    if self.is_valid_ipv4_address(ips):
                        self.c[self.gi.country_code_by_addr(ips).lower()] += 1
                    if self.is_valid_ipv6_address(ips):
                        self.c[self.gi6.country_code_by_addr(ips).lower()] += 1

                # mark what was requested
                self.p[path] += 1
                if (code[:1] == "5") or (code[:1]) == "4":
                    self.e[path] += 1

                # mark requested users
                if user[:1] == "~":
                    self.u[user] += 1
                    self.t[user] += int(traffic)

                # mark keyword counter
                for keyword in keywords:
                    if keyword in agent:
                        self.d[keyword] += 1
                        break
            except ValueError:
                pass
Exemplo n.º 9
0
def get_token_auth_header():
    if 'Authorization' not in request.headers:
        abort(401)
    auth_header = request.headers['Authorization']
    header_parts = request.split(' ')

    if len(header_parts) != 2:
        abort(401)
    elif header_parts[0].lower() != 'bearer':
        abort(401)
    return header_parts[1]
Exemplo n.º 10
0
    def get(self, request):
        requests = request.split('X')
        moves1 = requests[0].split(seperator)
        moves2 = requests[1].split(seperator)
        round = int(requests[2])
        time_step = example_environment.reset()
        restenv.reset()
        if (moves1):
            for m1 in moves1:
                if m1:
                    restenv.step((1, int(m1)))
        if (moves2):
            for m2 in moves2:
                if m2:
                    restenv.step((-1, int(m2)))

        minerals = round * 500
        actions = []
        fs = 0
        while restenv.state['minerals'][1] < minerals:
            if fs > 200:
                break
            # time_step[3] = tf.convert_to_tensor(np.expand_dims(restenv.state['board'], axis=0), dtype=tf.uint8)
            if restenv.state['minerals'][1] == 0:
                time_step = ts.restart(
                    tf.convert_to_tensor(np.expand_dims(restenv.state['board'],
                                                        axis=0),
                                         dtype=tf.uint8))
            else:
                time_step = ts.transition(tf.convert_to_tensor(np.expand_dims(
                    restenv.state['board'], axis=0),
                                                               dtype=tf.uint8),
                                          reward=0.0,
                                          discount=0.0)
            action_step = agent.policy.action(time_step)
            _time_step = example_environment.step(action_step)
            move = action_step.action.numpy()[0]
            restenv.step((1, move))
            actions.append(move)
            fs += 1
        return {'task': seperator.join(str(x) for x in actions)}, 201
Exemplo n.º 11
0
def dispatch(
        user,
        request,
        filters_pipeline=FILTERS_PIPELINE[FilterType.REQUEST],
        filter_method_name_callback=_get_filter_callable_name
) -> HollowmanRequest:
    """
    :type user: User
    :type request: http_wrappers.Request
    :type filters_pipeline: Dict[OperationType, Iterable[BaseFilter]]

    todo: (user, request_app, original_app) podem ser refatorados em uma classe de domínio
    """

    filtered_apps = []

    for operation in request.request.operations:
        for request_app, original_app in request.split():
            if _dispatch(request, filters_pipeline[operation],
                         filter_method_name_callback(request, operation),
                         request_app, original_app):
                filtered_apps.append((request_app, original_app))

    return request.join(filtered_apps)
Exemplo n.º 12
0
def main_menu(message):

    bot.send_chat_action(message.chat.id, "typing")

    user = core.User(message.chat)
    user_name = user.get_full_name()
    request = message.text

    core.log(message.chat, '> {}'.format(message.text))

    if user_name:

        def is_date_request_or_other():

            if re.search(r'^(\d{1,2})\.(\d{1,2})$', request) or \
               re.search(r'^(\d{1,2})\.(\d{1,2})-(\d{1,2})\.(\d{1,2})$', request) or \
               re.search(r'^(\d{1,2})\.(\d{1,2})\.(\d{2,4})$', request) or \
               re.search(r'^(\d{1,2})\.(\d{1,2})\.(\d{2,4})-(\d{1,2})\.(\d{1,2})\.(\d{2,4})$', request):

                return 'FOR_A_DATE'

            return 'OTHER'

        # Reversed keys and values in dictionary
        request_code = {v: k
                        for k, v in KEYBOARD.items()
                        }.get(request, is_date_request_or_other())
        core.MetricsManager.track(user.get_id(), request_code, user_name)

        if request == KEYBOARD['TODAY']:

            today = datetime.date.today().strftime('%d.%m.%Y')

            timetable_data = get_timetable(teacher=user_name,
                                           user_id=user.get_id(),
                                           sdate=today,
                                           edate=today)

            if timetable_data:
                timetable_for_today = render_day_timetable(timetable_data[0])
            elif isinstance(timetable_data, list) and not len(timetable_data):
                timetable_for_today = "На сьогодні пар не знайдено."
            else:
                return

            bot.send_message(user.get_id(),
                             timetable_for_today,
                             parse_mode='HTML',
                             reply_markup=keyboard)

        elif request == KEYBOARD['TOMORROW']:  # Tomorrow

            tomorrow = datetime.date.today() + datetime.timedelta(days=1)
            tom_day = tomorrow.strftime('%d.%m.%Y')

            timetable_data = get_timetable(teacher=user_name,
                                           sdate=tom_day,
                                           edate=tom_day,
                                           user_id=user.get_id())

            if timetable_data:
                timetable_for_tomorrow = render_day_timetable(
                    timetable_data[0])
            elif isinstance(timetable_data, list) and not len(timetable_data):
                timetable_for_tomorrow = "На завтра пар не знайдено."
            else:
                return

            bot.send_message(user.get_id(),
                             timetable_for_tomorrow,
                             parse_mode='HTML',
                             reply_markup=keyboard)

        elif request == KEYBOARD['FOR_A_WEEK']:  # For a week

            if datetime.date.today().isoweekday() in (5, 6, 7):  # пт, сб, нд

                timetable_for_week = ''
                today = datetime.date.today()
                current_week_day_number = today.isoweekday()
                diff_between_saturday_and_today = 6 - current_week_day_number
                next_week_first_day = today + datetime.timedelta(
                    days=diff_between_saturday_and_today + 2)
                next_week_last_day = today + datetime.timedelta(
                    days=diff_between_saturday_and_today + 7)

                timetable_data = get_timetable(
                    teacher=user_name,
                    sdate=next_week_first_day.strftime('%d.%m.%Y'),
                    edate=next_week_last_day.strftime('%d.%m.%Y'),
                    user_id=user.get_id())

                if timetable_data:
                    for timetable_day in timetable_data:
                        timetable_for_week += render_day_timetable(
                            timetable_day)

                elif isinstance(timetable_data,
                                list) and not len(timetable_data):
                    timetable_for_week = "На тиждень, з {} по {} пар не знайдено.".format(
                        next_week_first_day.strftime('%d.%m'),
                        next_week_last_day.strftime('%d.%m'))

                bot.send_message(text=timetable_for_week[:4090],
                                 chat_id=user.get_id(),
                                 reply_markup=keyboard,
                                 parse_mode="HTML")

                return

            week_type_keyboard = telebot.types.InlineKeyboardMarkup()
            week_type_keyboard.row(*[
                telebot.types.InlineKeyboardButton(text=name,
                                                   callback_data=name)
                for name in ["Поточний", "Наступний"]
            ])

            bot.send_message(user.get_id(),
                             'На який тиждень?',
                             reply_markup=week_type_keyboard)

        elif request == KEYBOARD['TIMETABLE']:

            t = ''
            t += '{} - 8:00 - 9:20\n'.format(emoji_numbers[1])
            t += '{} - 9:30 - 10:50\n'.format(emoji_numbers[2])
            t += '{} - 11:10 - 12:30\n'.format(emoji_numbers[3])
            t += '{} - 12:40 - 14:00\n'.format(emoji_numbers[4])
            t += '{} - 14:10 - 15:30 \n'.format(emoji_numbers[5])

            bot.send_message(user.get_id(), t, reply_markup=keyboard)

        elif request == KEYBOARD['CHANGE_NAME']:

            user_group = user.get_full_name()

            cancel_kb = telebot.types.ReplyKeyboardMarkup(
                resize_keyboard=True, one_time_keyboard=True)
            cancel_kb.row('Відміна')

            msg = 'Збережене ім\'я: {}\nЩоб змінити, введіть нове прізвище'.format(
                user_group)

            sent = bot.send_message(message.chat.id,
                                    msg,
                                    parse_mode='HTML',
                                    reply_markup=cancel_kb)
            bot.register_next_step_handler(sent, set_name)

        elif request == KEYBOARD['HELP']:

            msg = "Для пошуку по датам : <b>15.05</b>, <b>15.05-22.05</b>, <b>1.1.18-10.1.18</b>\n\n" \
                  "<b>Ім`я:</b> <code> {}</code>\n\n" \
                  "<b>Канал:</b> @********\n" \
                  "<b>Новини коледжу:</b> @*********\n" \
                  "<b>Розробник:</b> @***_CBA_Bot\n"

            kb = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True,
                                                   one_time_keyboard=True)
            kb.row(KEYBOARD['MAIN_MENU'])
            kb.row(KEYBOARD['CHANGE_NAME'])

            bot.send_message(message.chat.id,
                             msg.format(user.get_full_name()),
                             reply_markup=kb,
                             parse_mode='HTML')

        elif request == KEYBOARD['FOR_A_GROUP']:
            sent = bot.send_message(
                message.chat.id,
                'Для того щоб подивитись розклад будь якої групи на тиждень введіть її назву (Приклад: 029-18-1)'
            )
            bot.register_next_step_handler(sent, show_other_group)

        elif request == KEYBOARD['IN_AUDIENCE']:

            now_time = datetime.datetime.now().time()

            lessons_time = (
                {
                    'start_time': (8, 0),
                    'end_time': (9, 20)
                },
                {
                    'start_time': (9, 30),
                    'end_time': (10, 50)
                },
                {
                    'start_time': (11, 10),
                    'end_time': (12, 30)
                },
                {
                    'start_time': (12, 40),
                    'end_time': (14, 0)
                },
                {
                    'start_time': (14, 10),
                    'end_time': (15, 30)
                },
            )

            breaks_time = (
                {
                    'start_time': (7, 50),
                    'end_time': (8, 0)
                },
                {
                    'start_time': (9, 20),
                    'end_time': (9, 30)
                },
                {
                    'start_time': (10, 50),
                    'end_time': (11, 10)
                },
                {
                    'start_time': (12, 30),
                    'end_time': (12, 40)
                },
                {
                    'start_time': (14, 00),
                    'end_time': (15, 10)
                },
            )

            current_lesson = 0
            current_break = -1

            for i, lesson in enumerate(lessons_time):
                if datetime.time(
                        *lesson['start_time']) <= now_time <= datetime.time(
                            *lesson['end_time']):
                    current_lesson = i + 1
                    break

            else:
                for i, _break in enumerate(breaks_time):
                    if datetime.time(*_break['start_time']
                                     ) <= now_time <= datetime.time(
                                         *_break['end_time']):
                        current_break = i
                        break
                else:
                    bot.send_message(message.chat.id,
                                     'Час відпочивати.',
                                     parse_mode='HTML',
                                     reply_markup=keyboard)
                    return

            msg = ''
            show_for_lesson = 0

            if current_lesson:
                msg = '\U0001F550 Зараз {} пара.'.format(current_lesson)
                show_for_lesson = current_lesson
            elif current_break >= 0:
                msg = '\U0001F6B6 Зараз перерва, далі {} пара'.format(
                    current_break + 1)
                show_for_lesson = current_break + 1

            msg += '\n\n'

            for audience in (319, 320, 321, 323, 324, 325, 326, 327, 328):
                lesson = core.get_lesson_in_audience(audience, show_for_lesson)

                if lesson:
                    msg += '\U0001F4BB <b>{}</b>\n'.format(audience)
                    msg += '<b>{}</b> ({}) > {} ({})\n\n'.format(
                        lesson['group'], lesson['teacher'], lesson['title'],
                        lesson['type'])

            bot.send_message(message.chat.id,
                             msg,
                             parse_mode='HTML',
                             reply_markup=keyboard)

        elif request == KEYBOARD['FOR_A_TEACHER']:

            sent = bot.send_message(
                message.chat.id,
                'Для того щоб подивитись розклад викладача на поточний тиждень - '
                'введіть його прізвище.')
            bot.register_next_step_handler(sent, select_teachers)

        elif request == KEYBOARD['FOR_A_AUDIENCE']:

            msg = 'Для того щоб подивитись розклад у аудиторії - виберіть потрібну із списку:'

            kb = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True,
                                                   one_time_keyboard=True)

            kb.row(KEYBOARD['MAIN_MENU'], '113', 'Всі')
            kb.row('319', '320', '321')
            kb.row('323', '324', '325')
            kb.row('326', '327', '328')

            sent = bot.send_message(message.chat.id, msg, reply_markup=kb)
            bot.register_next_step_handler(sent, show_in_audience)

        elif re.search(r'^(\d{1,2})\.(\d{1,2})$', request):

            date = request + '.' + str(datetime.date.today().year)
            timetable_data = get_timetable(teacher=user_name,
                                           edate=date,
                                           sdate=date,
                                           user_id=user.get_id())

            if timetable_data:
                timetable_for_date = render_day_timetable(timetable_data[0])
            elif isinstance(timetable_data, list) and not len(timetable_data):
                msg = 'Щоб подивитися розклад на конкретний день, введіть дату в такому форматі:' \
                      '\n<b>05.03</b> або <b>5.3</b>\nПо кільком дням: \n<b>5.03-15.03</b>\n' \
                      '\nДата вводиться без пробілів (день.місяць)<b> рік вводити не обов\'язково</b> ' \

                timetable_for_date = 'На <b>{}</b>, для <b>{}</b> пар не знайдено.\n\n{}'.format(
                    date, user_name, msg)
            else:
                return

            bot.send_message(message.chat.id,
                             timetable_for_date,
                             parse_mode='HTML',
                             reply_markup=keyboard)

        elif re.search(r'^(\d{1,2})\.(\d{1,2})-(\d{1,2})\.(\d{1,2})$',
                       request):

            s_date = message.text.split('-')[0] + '.' + str(
                datetime.date.today().year)
            e_date = message.text.split('-')[1] + '.' + str(
                datetime.date.today().year)
            timetable_for_days = ''
            timetable_data = get_timetable(teacher=user_name,
                                           sdate=s_date,
                                           edate=e_date,
                                           user_id=user.get_id())

            if timetable_data:
                for timetable_day in timetable_data:
                    timetable_for_days += render_day_timetable(timetable_day)

            elif isinstance(timetable_data, list) and not len(timetable_data):
                msg = 'Щоб подивитися розклад на конкретний день, введіть дату в такому форматі:' \
                      '\n<b>05.03</b> або <b>5.3</b>\nПо кільком дням: \n<b>5.03-15.03</b>\n' \
                      '\nДата вводиться без пробілів (день.місяць)<b> рік вводити не обов\'язково</b> '
                timetable_for_days = 'На <b>{} - {}</b>, для <b>{}</b> пар не знайдено.\n\n{}'.format(
                    s_date, e_date, user_name, msg)
            else:
                return

            bot.send_message(user.get_id(),
                             timetable_for_days[:4090],
                             parse_mode='HTML',
                             reply_markup=keyboard)

        elif re.search(r'^(\d{1,2})\.(\d{1,2})\.(\d{2,4})$', request):

            date = request
            timetable_data = get_timetable(teacher=user_name,
                                           edate=date,
                                           sdate=date,
                                           user_id=user.get_id())

            if timetable_data:
                timetable_for_date = render_day_timetable(timetable_data[0])
            elif isinstance(timetable_data, list) and not len(timetable_data):
                msg = 'Щоб подивитися розклад на конкретний день, введіть дату в такому форматі:' \
                      '\n<b>05.03</b> або <b>5.3</b>\nПо кільком дням: \n<b>5.03-15.03</b>\n' \
                      '\nДата вводиться без пробілів (день.місяць)<b> рік вводити не обо\'язково</b> ' \

                timetable_for_date = 'На <b>{}</b>, для <b>{}</b> пар не знайдено.\n\n{}'.format(
                    date, user_name, msg)
            else:
                return

            bot.send_message(message.chat.id,
                             timetable_for_date,
                             parse_mode='HTML',
                             reply_markup=keyboard)

        elif re.search(
                r'^(\d{1,2})\.(\d{1,2})\.(\d{2,4})-(\d{1,2})\.(\d{1,2})\.(\d{2,4})$',
                request):

            s_date = request.split('-')[0]
            e_date = request.split('-')[1]
            timetable_for_days = ''
            timetable_data = get_timetable(teacher=user_name,
                                           sdate=s_date,
                                           edate=e_date,
                                           user_id=user.get_id())

            if timetable_data:
                for timetable_day in timetable_data:
                    timetable_for_days += render_day_timetable(timetable_day)

            elif isinstance(timetable_data, list) and not len(timetable_data):
                msg = 'Щоб подивитися розклад на конкретний день, введіть дату в такому форматі:' \
                      '\n<b>05.03</b> або <b>5.3</b>\nПо кільком дням: \n<b>5.03-15.03</b>\n' \
                      '\nДата вводиться без пробілів (день.місяць)<b> рік вводити не обов`язково</b> '
                timetable_for_days = 'На <b>{} - {}</b>, для <b>{}</b> пар не знайдено.\n\n{}'.format(
                    s_date, e_date, user_name, msg)
            else:
                return

            bot.send_message(user.get_id(),
                             timetable_for_days,
                             parse_mode='HTML',
                             reply_markup=keyboard)

        elif request == KEYBOARD['MAIN_MENU']:
            bot.send_message(user.get_id(),
                             'Меню так меню',
                             reply_markup=keyboard)

        else:
            answers = [
                'м?', 'хм.. \U0001F914', 'не розумію(',
                'виберіть потрібне в меню'
            ]
            bot.send_message(user.get_id(),
                             random.choice(answers),
                             reply_markup=keyboard)

    else:
        bot.send_message(user.get_id(), 'Для початку роботи введіть /start')
Exemplo n.º 13
0
def reply_to_request(request):
    phrases = ("please", "plz", "pls", "plox", "plx")
    negative = (
        "no", "no.", "NO",
        "No.", "No", "no no", "no, no, no!",
        "no no no", "yes?", "yeah nah"
    )
    try_hard = (
        "Okay now you're just a try-hard",
        "Trrryyy Haaarrrdd",
        "Have you tried, tring harder?",
        "Try harder?",
        "Try harder!",
        "Where are *you* going in life?",
        "Seriously...",
        "Hey stop it!",
        "Hehe, it tickles",
        "Uhm...",
        "Despair",
        "This gets worse and worse, until you give up or die",
        ":)",
        "",
    )

    if not request:
        return ""

    if request.isupper():
        return "WHY ARE YOU SHOUTING AT ME?!"
    else:
        request = request.lower()

    if request.endswith("?"):
        if any(
            phrase in request
            for phrase in ("please", "plz", "pls", "plox", "pl0x")
        ):
            return "yes"
        else:
            return "Where's your manners?!"
    else:
        request = request.translate(str.maketrans("","",string.punctuation))

    with open("lyrics.txt") as lyrics_file:
        lines = [
            line.strip().lower().translate(str.maketrans("","",string.punctuation))
            for line in lyrics_file
        ]
        next_line = dict(zip(lines, lines[1:]))

    if request in next_line:
        return next_line[request] + " 🎶"

    if multi_count(request, phrases) == 2:
        return "Wow you're such a pushover"

    if 3 <= multi_count(request, phrases) < 100:
        return "Gee wish I could say please a hundred times and get whatever I wanted"

    if multi_count(request, phrases) >= 100:
        return "Okay now you just went too far..."

    if any(
        phrase in request
        for phrase in phrases
    ):
        return "I'll think about it"

    if request == " ":
        return "🌌"

    if "f**k" in request or "evan" in request:
        return "Listen here you little shit"

    if "gimmie" in request:
        return "What are you? Illiterate?"

    if "hey gimme that" in " ".join(request.split()):
        return "What are you? The Loot Hoarder?"

    if "hey" in request:
        return "Aren't you meant to be getting a flag or something?"

    if "i need it" in " ".join(request.split()):
        return "You definitely don't need it"

    if "flag" in request:
        return "This one 🇸🇪?"

    if "man" in request:
        return "Okay here, the best dressed man I could find 🕴"

    if "help" in request or "halp" in request:
        return "Don't ask me for help! You're meant to be helping Agnetha!"

    if "hint" in request:
        return "You want a hint already? -.-\" I'll give you one later... maybe..."

    count = request.count("gimme")
    if count == 1:
        return random.choice(negative)

    if count == 2:
        return "I said no!"

    if count == 3:
        return "okay, maybe..."

    if 3 < count < 10:
        return "maybe..."

    if count == 10:
        return "What on earth are you doing?"

    if count == 11:
        return "No, like staph"

    if count == 12:
        return "Seriously..."

    if count == 12:
        return "Okay whatever then"

    if 12 < count < 23:
        return random.choice(negative)

    if count == 23:
        return "I said maybe..."

    if count == 24:
        return "...you're gonna be the one that saves me..."

    if count == 25:
        return "You know, there is logic to this madness"

    if 25 < count < 29:
        return random.choice(negative)

    if count == 29:
        return "That number of gimmes is too damn high"

    if count == 30:
        return "DO YOU THINK SHE STUTTERED?!?!"
        return 'What part of "after midnight" did you not understand?'

    if count == 31:
        return "Thirty one"

    if (count & (count - 1)) == 0 and count:
        return "Indeed that is a power of 2"

    if 97 <= count <= 99:
        return (
            f"{count} containers of flags on the wall, "
            f"{count} containers of flags. "
             "Take one down and pass it around, "
            f"{count - 1} containers of flags on the wall...."
        )

    if count == 100:
        return "You probably won't reach that age"

    if count > 32:
        return random.choice(try_hard)

    return random.choice(negative)

    return (
        "Wow... Look at you... You managed to find an edge case after like 35"
        "different if statements... Go buy a lottery ticket..."
    )
Exemplo n.º 14
0
def reply_to_request(request):
    phrases = ("please", "plz", "pls", "plox", "plx")
    negative = ("no", "no.", "NO", "No.", "No", "no no", "no, no, no!",
                "no no no", "yes?", "yeah nah")
    try_hard = (
        "Okay now you're just a try-hard",
        "Trrryyy Haaarrrdd",
        "Have you tried, tring harder?",
        "Try harder?",
        "Try harder!",
        "Where are *you* going in life?",
        "Seriously...",
        "Hey stop it!",
        "Hehe, it tickles",
        "Uhm...",
        "Despair",
        "This gets worse and worse, until you give up or die",
        ":)",
        "",
    )

    if not request:
        return ""

    if request.isupper():
        return "WHY ARE YOU SHOUTING AT ME?!"
    else:
        request = request.lower()

    if request.endswith("?"):
        if any(phrase in request
               for phrase in ("please", "plz", "pls", "plox", "pl0x")):
            return "yes"
        else:
            return "Where's your manners?!"
    else:
        request = request.translate(str.maketrans("", "", string.punctuation))

    with open("lyrics.txt") as lyrics_file:
        lines = [
            line.strip().lower().translate(
                str.maketrans("", "", string.punctuation))
            for line in lyrics_file
        ]
        next_line = dict(zip(lines, lines[1:]))

    if request in next_line:
        return next_line[request] + " 🎶"

    if multi_count(request, phrases) == 2:
        return "Wow you're such a pushover"

    if 3 <= multi_count(request, phrases) < 100:
        return "Gee wish I could say please a hundred times and get whatever I wanted"

    if multi_count(request, phrases) >= 100:
        return "Okay now you just went too far..."

    if any(phrase in request for phrase in phrases):
        return "I'll think about it"

    if request == " ":
        return "🌌"

    if "f**k" in request or "evan" in request:
        return "Listen here you little shit"

    if "gimmie" in request:
        return "What are you? Illiterate?"

    if "hey gimme that" in " ".join(request.split()):
        return "What are you? The Loot Hoarder?"

    if "hey" in request:
        return "Aren't you meant to be getting a flag or something?"

    if "i need it" in " ".join(request.split()):
        return "You definitely don't need it"

    if "flag" in request:
        return "This one 🇸🇪?"

    if "man" in request:
        return "Okay here, the best dressed man I could find 🕴"

    if "help" in request or "halp" in request:
        return "Don't ask me for help! You're meant to be helping Agnetha!"

    if "hint" in request:
        return "You want a hint already? -.-\" I'll give you one later... maybe..."

    count = request.count("gimme")
    if count == 1:
        return random.choice(negative)

    if count == 2:
        return "I said no!"

    if count == 3:
        return "okay, maybe..."

    if 3 < count < 10:
        return "maybe..."

    if count == 10:
        return "What on earth are you doing?"

    if count == 11:
        return "No, like staph"

    if count == 12:
        return "Seriously..."

    if count == 12:
        return "Okay whatever then"

    if 12 < count < 23:
        return random.choice(negative)

    if count == 23:
        return "I said maybe..."

    if count == 24:
        return "...you're gonna be the one that saves me..."

    if count == 25:
        return "You know, there is logic to this madness"

    if 25 < count < 29:
        return random.choice(negative)

    if count == 29:
        return "That number of gimmes is too damn high"

    if count == 30:
        return "DO YOU THINK SHE STUTTERED?!?!"
        return 'What part of "after midnight" did you not understand?'

    if count == 31:
        return "Thirty one"

    if (count & (count - 1)) == 0 and count:
        return "Indeed that is a power of 2"

    if 97 <= count <= 99:
        return (f"{count} containers of flags on the wall, "
                f"{count} containers of flags. "
                "Take one down and pass it around, "
                f"{count - 1} containers of flags on the wall....")

    if count == 100:
        return "You probably won't reach that age"

    if count > 32:
        return random.choice(try_hard)

    return random.choice(negative)

    return (
        "Wow... Look at you... You managed to find an edge case after like 35"
        "different if statements... Go buy a lottery ticket...")