def test_new_list_command(self):
        ''' Check that '/new' command create list and sends it as a message '''

        engine = create_engine('sqlite:///:memory:')
        Session = sessionmaker(bind=engine)
        session = Session()

        # add first one
        request = self.get_new_command('Room')
        expected = {
            'method': 'sendMessage',
            'chat_id': 1,
            'text': 'Room',
            'reply_markup': {
                'inline_keyboard': [[
                    {
                        'text': 'add',
                        'switch_inline_query_current_chat': '/add '
                    },
                ]]
            }
        }
        self.assertEqual(
            handle_request(request, self.tg_settings, session, engine),
            expected)

        first_list = session.query(data_model.List).first()
        self.assertEqual(first_list.name, 'Room')
        self.assertEqual(first_list.tg_chat_id, 1)
        self.assertEqual(first_list.is_current, True)
        self.assertEqual(first_list.last_tg_msg_id, None)

        # second
        request = self.get_new_command('Комната')
        expected = {
            'method': 'sendMessage',
            'chat_id': 1,
            'text': 'Комната',
            'reply_markup': {
                'inline_keyboard': [[
                    {
                        'text': 'add',
                        'switch_inline_query_current_chat': '/add '
                    },
                ]]
            }
        }
        self.assertEqual(
            handle_request(request, self.tg_settings, session, engine),
            expected)

        second_list = session.query(
            data_model.List).filter_by(name='Комната').one()
        self.assertEqual(second_list.name, 'Комната')
        self.assertEqual(second_list.tg_chat_id, 1)
        self.assertEqual(second_list.is_current, True)
        self.assertEqual(second_list.last_tg_msg_id, None)

        # ensure that first list become is_current == False
        self.assertFalse(first_list.is_current)
    def test_add_item_command(self):
        ''' Check that '/add' command add items to the current list '''
        engine = create_engine('sqlite:///:memory:')
        Session = sessionmaker(bind=engine)
        session = Session()
        data_model.Base.metadata.create_all(engine)

        clist = data_model.List(name='Room 1', tg_chat_id=1, is_current=True)
        session.add(clist)
        session.commit()

        request = {
            'message': {
                'chat': {
                    'id': 1
                },
                'from': {
                    'username': '******'
                },
                'text': '/add Lisa',
                'entities': [{
                    'type': 'bot_command',
                    'offset': 0,
                    'length': 4
                }]
            }
        }
        # expected = {
        #     'method': 'sendMessage',
        #     'chat_id': 1,
        #     'text': 'Room 1',
        #     'reply_markup': {
        #         'inline_keyboard': [
        #             [
        #                 {
        #                     'text': 'Lisa',
        #                     'callback_data': 'check 1'
        #                 },
        #                 {
        #                     'text': '✗',
        #                     'callback_data': 'remove 1'
        #                 },
        #             ],
        #             [
        #                 {
        #                     'text': 'add',
        #                     'switch_inline_query_current_chat': '/add '
        #                 },
        #             ]
        #         ]
        #     }
        # }
        # self.assertEqual(handle_request(request, self.tg_settings, session, engine), expected)
        handle_request(request, self.tg_settings, session, engine)

        item = session.query(data_model.Item).filter_by(list_id=clist.id,
                                                        name='Lisa').one()
        self.assertEqual(item.checked, False)
    def test_start_list_command(self):
        ''' Check that '/start' command send correct intro message '''

        engine = create_engine('sqlite:///:memory:')
        Session = sessionmaker(bind=engine)
        session = Session()

        request = {
            'message': {
                'chat': {
                    'id': 1
                },
                'from': {
                    'username': '******'
                },
                'text': '/start@a',
                'entities': [{
                    'type': 'bot_command',
                    'offset': 0,
                    'length': 8
                }]
            }
        }
        expected = {
            'method': 'sendMessage',
            'chat_id': 1,
            'text': 'Oh hi Mark!\nCreate first list using /new'
        }
        self.assertEqual(
            handle_request(request, self.tg_settings, session, engine),
            expected)
Exemplo n.º 4
0
    def handle(self) -> None:
        print(f"Address: {self.client_address}")

        data = self.request.recv(4096).strip()  # strip() - Delete spaces
        request = Request(data)
        response = handle_request(request)
        self.request.send(response)
def application(environ, start_response):

    try:
        with open(os.path.join(os.getcwd(), 'secrets.json'),
                  'r') as secrets_file:
            secrets = json.load(secrets_file)

        encoded_passord = urllib.parse.quote(secrets['db_password'])
        engine = create_engine(
            'mysql+mysqldb://zaripov_shls_bot:{password}@localhost/zaripov_shls_bot?charset=utf8'
            .format(password=encoded_passord))
        Session = sessionmaker(bind=engine)
        session = Session()

        try:
            content_length = int(environ.get('CONTENT_LENGTH', 0))
        except (ValueError):
            content_length = 0
        if content_length != 0:
            body = environ['wsgi.input'].read(content_length)
        else:
            body = b''

        request = json.loads(body)
        response = handle_request(
            request, settings.TelegramApi(secrets['telegram_token']), session,
            engine)
        session.commit()

        start_response('200 OK',
                       [('Content-Type', 'application/json;charset=utf-8')])
        return [bytes(json.dumps(response), 'utf-8')]

    except Exception as e:
        logging.exception('exception while handling request')
Exemplo n.º 6
0
    def do_POST(self):

        # Parse request
        route = handler.parser(self.path)

        # Handle request
        if route == '':
            print('Invalid request')
            request_is_valid = False
        else:
            content_length = int(
                self.headers['Content-Length'])  # <--- Gets the size of data
            post_data = self.rfile.read(
                content_length)  # <--- Gets the data itself
            data = json.loads(post_data.decode('utf-8'))
            request_is_valid, resp = handler.handle_request(
                route, data, FUNDING_TYPES)

        # Send response
        if request_is_valid:
            print('response: ', resp)
            self._set_response(200)
            self.wfile.write(resp.encode())
        else:
            # Create response
            print('Invalid request, error in handle_request')
            self._set_response(404)
            self.wfile.write(json.dumps({'Error': 'Invalid request'}).encode())
def client_thread(connection, client_address):
    while True:
        data = connection.recv(1024)
        decoded_data = data.decode('utf-8')
        if not data:
            break

        response = handle_request(decoded_data, bank)
        connection.send(response.encode('ascii'))

    Logger.log_info("Client on " + str(client_address) + " disconnected.")

    global n_clients_connected
    n_clients_connected -= 1
    Logger.log_info("Number of clients currently connected: {}.".format(
        n_clients_connected))

    connection.close()
 def test_hello(self):
     request = {
         'message': {
             'chat': {
                 'id': 1
             },
             'from': {
                 'username': '******'
             },
             'text': 'Hi'
         }
     }
     expected = {
         'method': 'sendMessage',
         'chat_id': 1,
         'text': 'Oh hi Mark!'
     }
     engine = create_engine('sqlite:///:memory:')
     Session = sessionmaker(bind=engine)
     session = Session()
     self.assertEqual(
         handle_request(request, self.tg_settings, session, engine),
         expected)
    def test_item_callbacks(self):
        ''' Check that 'check' and 'remove' callbacks works as expected '''
        engine = create_engine('sqlite:///:memory:')
        Session = sessionmaker(bind=engine)
        session = Session()
        data_model.Base.metadata.create_all(engine)

        clist = data_model.List(name='Room 1', tg_chat_id=1, is_current=True)
        session.add(clist)
        session.commit()
        lisa = data_model.Item(name='Lisa', list_id=clist.id, checked=False)
        johnny = data_model.Item(name='Johnny',
                                 list_id=clist.id,
                                 checked=False)
        session.add_all([lisa, johnny])
        session.commit()

        # check
        request = {
            'callback_query': {
                'data': 'check ' + str(lisa.id),
                'message': {
                    'message_id': 1,
                    'chat': {
                        'id': 1
                    },
                    'from': {
                        'username': '******'
                    },
                },
            }
        }
        expected = {
            'method': 'editMessageReplyMarkup',
            'chat_id': 1,
            'message_id': 1,
            'reply_markup': {
                'inline_keyboard': [[
                    {
                        'text': '✓ Lisa',
                        'callback_data': 'check ' + str(lisa.id),
                    },
                    {
                        'text': '✗',
                        'callback_data': 'remove ' + str(lisa.id),
                    },
                ],
                                    [
                                        {
                                            'text':
                                            'Johnny',
                                            'callback_data':
                                            'check ' + str(johnny.id),
                                        },
                                        {
                                            'text':
                                            '✗',
                                            'callback_data':
                                            'remove ' + str(johnny.id),
                                        },
                                    ],
                                    [
                                        {
                                            'text':
                                            'add',
                                            'switch_inline_query_current_chat':
                                            '/add '
                                        },
                                    ]]
            }
        }

        self.assertEqual(
            handle_request(request, self.tg_settings, session, engine),
            expected)
        self.assertEqual(lisa.checked, True)
        self.assertEqual(johnny.checked, False)

        # remove
        request = {
            'callback_query': {
                'data': 'remove ' + str(johnny.id),
                'message': {
                    'message_id': 1,
                    'chat': {
                        'id': 1
                    },
                    'from': {
                        'username': '******'
                    },
                },
            }
        }
        expected = {
            'method': 'editMessageReplyMarkup',
            'chat_id': 1,
            'message_id': 1,
            'reply_markup': {
                'inline_keyboard': [[
                    {
                        'text': '✓ Lisa',
                        'callback_data': 'check ' + str(lisa.id),
                    },
                    {
                        'text': '✗',
                        'callback_data': 'remove ' + str(lisa.id),
                    },
                ],
                                    [
                                        {
                                            'text':
                                            'add',
                                            'switch_inline_query_current_chat':
                                            '/add '
                                        },
                                    ]]
            }
        }

        self.assertEqual(
            handle_request(request, self.tg_settings, session, engine),
            expected)
        self.assertEqual(session.query(data_model.Item).count(), 1)
    def test_list_callbacks(self):
        ''' Check that 'select_list' and 'remove_list' callbacks works as expected '''

        engine = create_engine('sqlite:///:memory:')
        Session = sessionmaker(bind=engine)
        session = Session()

        data_model.Base.metadata.create_all(engine)

        list1 = data_model.List(name='Room 1', tg_chat_id=1, is_current=True)
        list2 = data_model.List(name='Room 2', tg_chat_id=1, is_current=False)
        session.add_all([list1, list2])
        session.commit()

        lisa = data_model.Item(name='Lisa', list_id=list2.id, checked=False)
        session.add(lisa)
        session.commit()

        # select
        request = {
            'callback_query': {
                'message': {
                    'message_id': 1,
                    'chat': {
                        'id': 1
                    },
                    'from': {
                        'username': '******'
                    },
                },
                'data': 'select_list ' + str(list2.id),
            }
        }
        expected = {
            'method': 'editMessageReplyMarkup',
            'chat_id': 1,
            'message_id': 1,
            'reply_markup': {
                'inline_keyboard': [[
                    {
                        'text': 'Room 1',
                        'callback_data': 'select_list ' + str(list1.id)
                    },
                    {
                        'text': '✗',
                        'callback_data': 'remove_list ' + str(list1.id)
                    },
                ],
                                    [
                                        {
                                            'text':
                                            '- Room 2',
                                            'callback_data':
                                            'select_list ' + str(list2.id)
                                        },
                                        {
                                            'text':
                                            '✗',
                                            'callback_data':
                                            'remove_list ' + str(list2.id)
                                        },
                                    ],
                                    [
                                        {
                                            'text':
                                            'new',
                                            'switch_inline_query_current_chat':
                                            '/new '
                                        },
                                    ]]
            }
        }
        self.assertEqual(
            handle_request(request, self.tg_settings, session, engine),
            expected)

        self.assertEqual(list1.is_current, False)
        self.assertEqual(list2.is_current, True)

        # remove
        request = {
            'callback_query': {
                'message': {
                    'message_id': 1,
                    'chat': {
                        'id': 1
                    },
                    'from': {
                        'username': '******'
                    },
                },
                'data': 'remove_list ' + str(list2.id),
            }
        }
        expected = {
            'method': 'editMessageReplyMarkup',
            'chat_id': 1,
            'message_id': 1,
            'reply_markup': {
                'inline_keyboard': [[
                    {
                        'text': '- Room 1',
                        'callback_data': 'select_list ' + str(list1.id)
                    },
                    {
                        'text': '✗',
                        'callback_data': 'remove_list ' + str(list1.id)
                    },
                ],
                                    [
                                        {
                                            'text':
                                            'new',
                                            'switch_inline_query_current_chat':
                                            '/new '
                                        },
                                    ]]
            }
        }
        self.assertEqual(
            handle_request(request, self.tg_settings, session, engine),
            expected)
        self.assertFalse(inspect(list1).deleted)
        self.assertTrue(list1.is_current)
        self.assertTrue(inspect(list2).deleted)

        #delete 2
        request = {
            'callback_query': {
                'message': {
                    'message_id': 1,
                    'chat': {
                        'id': 1
                    },
                    'from': {
                        'username': '******'
                    },
                },
                'data': 'remove_list ' + str(list1.id),
            }
        }
        expected = {
            'method': 'editMessageReplyMarkup',
            'chat_id': 1,
            'message_id': 1,
            'reply_markup': {
                'inline_keyboard': [[
                    {
                        'text': 'new',
                        'switch_inline_query_current_chat': '/new '
                    },
                ]]
            }
        }
        self.assertEqual(
            handle_request(request, self.tg_settings, session, engine),
            expected)
        self.assertTrue(inspect(list1).deleted)
        self.assertTrue(inspect(list2).deleted)
    def test_list_command(self):
        ''' Check that '/list' command send list of lists) '''

        engine = create_engine('sqlite:///:memory:')
        Session = sessionmaker(bind=engine)
        session = Session()

        data_model.Base.metadata.create_all(engine)

        list1 = data_model.List(name='Room 1', tg_chat_id=1, is_current=True)
        list2 = data_model.List(name='Room 2', tg_chat_id=1, is_current=False)
        session.add_all([list1, list2])
        session.commit()

        request = {
            'message': {
                'chat': {
                    'id': 1
                },
                'from': {
                    'username': '******'
                },
                'text': '/list',
                'entities': [{
                    'type': 'bot_command',
                    'offset': 0,
                    'length': 5
                }]
            }
        }
        expected = {
            'method': 'sendMessage',
            'chat_id': 1,
            'text': 'Lists',
            'reply_markup': {
                'inline_keyboard': [[
                    {
                        'text': '- Room 1',
                        'callback_data': 'select_list ' + str(list1.id)
                    },
                    {
                        'text': '✗',
                        'callback_data': 'remove_list ' + str(list1.id)
                    },
                ],
                                    [
                                        {
                                            'text':
                                            'Room 2',
                                            'callback_data':
                                            'select_list ' + str(list2.id)
                                        },
                                        {
                                            'text':
                                            '✗',
                                            'callback_data':
                                            'remove_list ' + str(list2.id)
                                        },
                                    ],
                                    [
                                        {
                                            'text':
                                            'new',
                                            'switch_inline_query_current_chat':
                                            '/new '
                                        },
                                    ]]
            }
        }
        self.assertEqual(
            handle_request(request, self.tg_settings, session, engine),
            expected)
Exemplo n.º 12
0
import get_attributes, request_handler
import xml.etree.ElementTree as et
registry_numbers = []
planes = []
tree = et.parse('data.xml')
root = tree.getroot()
product_table = root[2][0]
planes = get_attributes.get_planes(product_table, registry_numbers, planes)
request = input('Do you want to "add" or "change" or "delete": ')
print(
    request_handler.handle_request(request, registry_numbers, planes, tree,
                                   product_table))