Exemple #1
0
async def new_chat_get_code(message, chat=None):
    lang = language(message.chat.id)
    if not chat:
        chat = int(message.text)
    if chat == message.chat.id:
        await message.reply(lang['warning_chat_with_yourself'])
        return
    existsQuery1 = "SELECT EXISTS (SELECT ID FROM users WHERE user_id=(%s))"
    existsQuery2 = "SELECT EXISTS (SELECT ID FROM chats WHERE (uid1=(%s) AND uid2=(%s) OR uid1=(%s) AND uid2=(%s)) AND active=1)"
    with DatabaseConnection() as db:
        conn, cursor = db
        cursor.execute(existsQuery1, [chat])
        result1 = cursor.fetchone()[0]
        cursor.executemany(existsQuery2, [(message.chat.id, chat, chat, message.chat.id)])
        result2 = cursor.fetchone()[0]
    if not result1:
        await message.reply(lang['warning_no_user_in_db'])
        return
    elif result2:
        await message.reply(lang['warning_chat_already_exists'])
        return
    insertQuery = "INSERT INTO chats (uid1, uid2) VALUES (%s, %s)"
    with DatabaseConnection() as db:
        conn, cursor = db
        cursor.executemany(insertQuery, [(message.chat.id, chat)])
        conn.commit()
    with InformationSchemaConnection() as db:
        conn, cursor = db
        selectQuery = "SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = (%s) AND TABLE_NAME = 'chats'"
        cursor.execute(selectQuery, [c.db])
        ID = cursor.fetchone()[0] - 1
    await message.answer(lang['chat_created'].format(ID, chat))
    lang2 = language(chat)
    await _send_message(bot.send_message, chat_id=chat, text=lang2['chat_created_2'].format(ID, message.chat.id))
Exemple #2
0
def execute_task5(request):
    l = int(request.POST.get('number_of_layers'))
    k = int(request.POST.get('number_of_hashes_per_layer'))
    lsh = LSH(k=k, l=l)
    dbconnection = DatabaseConnection()

    if read_from_pickle('all_img_features_LSH.pickle') != None:
        all_image_hog_features = read_from_pickle('all_img_features_LSH.pickle')
    else:
        all_image_hog_features = dbconnection.get_object_feature_matrix_from_db(tablename='histogram_of_gradients')
        save_to_pickle(all_image_hog_features,'all_img_features_LSH.pickle')
    #SVD on hog features
    if(read_from_pickle('svd_hog_lsh.pickle')!=None):
        svd_obj = read_from_pickle('svd_hog_lsh.pickle')
        transformed_data = svd_obj['data_matrix']
        vt = svd_obj['vt']
    else:
        svd = SingularValueDecomposition()
        transformed_data,vt = svd.get_transformed_data_copy(all_image_hog_features['data_matrix'],400)
        save_to_pickle({"data_matrix":transformed_data,"images":all_image_hog_features['images'],"vt":vt},'svd_hog_lsh.pickle')

    # index_of_query_image = (all_image_hog_features['images']).index(query_image)
    # image_vector = transformed_data[index_of_query_image]
    bit_map = lsh.generate_representation_for_all_layers(transformed_data,all_image_hog_features['images'])

    save_to_pickle(lsh, 'lsh_model')
    return render(request, 'task5a_output.html')
    def __init__(self):

        # connect to database
        self.db = DatabaseConnection()
        self.db_connect = self.db.connect_database()

        # create a Cursor() method from established database connection
        self.cur = self.db_connect.cursor()
Exemple #4
0
async def handle_text(message: types.Message, state: FSMContext):
    await state.finish()
    auth = await authentication(message)
    with open(c.strings_file, encoding='utf-8') as f:
        strings = json.load(f)
    if not auth: return False
    selectByIdQuery = "SELECT mail, pass FROM users WHERE user_id=(%s)"
    selectByFNQuery = "SELECT mail, pass FROM users WHERE f_name=(%s) AND l_name=(%s) GROUP BY stud_id"
    if message.forward_date:
        if not message.forward_from:
            await message.reply(strings[auth[mu.ResTypes.LANG]]['user_hidden'])
            return
        user_id = message.forward_from.id
        with DatabaseConnection() as db:
            conn, cursor = db
            cursor.execute(selectByIdQuery, [user_id])
            result = cursor.fetchall()
    else:
        if not message.text:
            await message.reply(strings[auth[mu.ResTypes.LANG]]['wrong_format']
                                )
            return
        if message.text in buttons_ua_1 + buttons_ua_2 + buttons_ru_1 + buttons_ru_2:
            await message.reply(strings[auth[mu.ResTypes.LANG]]['wrong_format']
                                )
            return
        try:
            message.text.encode('utf-8')
        except UnicodeError:
            await message.reply(strings[auth[mu.ResTypes.LANG]]['wrong_format']
                                )
            return
        s = message.text.replace('`', "'").split()
        if len(s) != 2:
            await message.reply(strings[auth[mu.ResTypes.LANG]]['wrong_format']
                                )
            return
        with DatabaseConnection() as db:
            conn, cursor = db
            cursor.executemany(selectByFNQuery,
                               [(s[0].capitalize(), s[1].capitalize())])
            result = cursor.fetchall()
    if not result:
        await message.reply(strings[auth[mu.ResTypes.LANG]]['not_found'])
        return
    for res in result:
        answer = await api_request(message,
                                   email=res[0],
                                   passwd=res[1],
                                   page=1)
        if answer is None: continue
        if not answer:
            await message.reply(strings[auth[mu.ResTypes.LANG]]['not_found'])
            continue
        main_page = strings[auth[mu.ResTypes.LANG]]['page_1'].format(
            **answer[0]).replace("`", "'")
        await message.reply(main_page, parse_mode='Markdown')
        await sleep(.05)
    def get_student_information(nuid):
        student_information_query = "SELECT * FROM students WHERE nuid = '%d'" % int(nuid)

        db_connection = DatabaseConnection.initiate_database_connection()
        cursor = db_connection.cursor()
        cursor.execute(student_information_query)

        student_information_result = cursor.fetchone()
        cursor.close()
        DatabaseConnection.exit_database_connection(db_connection)

        return student_information_result
Exemple #6
0
def get_svd_image_data_from_folder(relative_folder_path, k=10):
    """
    :param relative_folder_path: here give the path with a '/' ahead e.g. '/Labelled/Set2'
    :return:
    data_matrix after applying SVD on it and also the image names present inside the relative_folder_path
    """
    image_names = get_image_names_in_a_folder(relative_folder_path)
    db_conn = DatabaseConnection()
    data_image_dict = db_conn.HOG_descriptor_from_image_ids(image_names)
    data_matrix = data_image_dict['data_matrix']
    svd_obj = SingularValueDecomposition()
    svd_image_data = svd_obj.get_transformed_data(data_matrix, k)
    return svd_image_data, data_image_dict['images']
    def __init__(self):
        """
        1) Read each image from data dir and put metadata in database table.
        2) Pass that image to each feature model to get a vector of dimension (1 * m)
        3) Pass this vector to all the dimension reduction technique to get latent semantics.
        4) Put this latent semantic of each image from each model and technique with its metadata inside database
        """
        self.root_path = str(Path(str(Path(os.getcwd()).parent))) + "/Data/"
        self.database_connection = DatabaseConnection()

        self.process_metadata()
        self.process_classification_metadata()

        self.DATABASE_IMAGES_PATH = self.root_path + "/images"
        self.CLASSIFICATION_IMAGES_PATH = self.root_path + "/phase3_sample_data"
        # feature_models = []
        # feature_models.append("histogram_of_gradients")
        # feature_models.append("sift")
        # # feature_models.append("histogram_of_gradients_30")
        #
        # processes = []
        # for i, feature in enumerate(feature_models):
        #     processes.append(Process(target=self.perform_feature_model(feature)))
        #     processes[i].start()
        #
        # for i in range(len(processes)):
        #     processes[i].join()

        # classification specific

        charas = ["Labelled", "Unlabelled"]
        # sets = ["Set1", "Set2", "Set3", "Set4"]
        sets = ["Set1", "Set2", "Set3"]
        number_of_clusters = ['250', '300']
        path = []
        feature_models = []
        for chara_ in charas:
            for set_ in sets:
                for cluster_count in number_of_clusters:
                    path.append(self.CLASSIFICATION_IMAGES_PATH + "/" + chara_ + "/" + set_)
                    # feature_models.append("histogram_of_gradients" + "_" + chara_ + "_" + set_)
                    # feature_models.append("local_binary_pattern" + "_" + chara_ + "_" + set_)
                    feature_models.append("sift" + "_" + chara_ + "_" + set_ + "_" + cluster_count)

        processes = []
        for i, feature in enumerate(feature_models):
            processes.append(Process(target=self.perform_classification_feature_model(feature, path[i],
                                                                                      cluster_count)))
            processes[i].start()
        for i in range(len(processes)):
            processes[i].join()
Exemple #8
0
def fetch_password():
    username = input("Enter username to fetch from")
    with DatabaseConnection("data.db") as connection:
        cursor = connection.cursor()
        cursor.execute('SELECT * FROM validation WHERE username=?',
                       (username, ))
        return [row for row in cursor.fetchall()]
    def create_table(self):
        with DatabaseConnection(self.categories_database) as connection:
            cursor = connection.cursor()

            cursor.execute(
                'CREATE TABLE IF NOT EXISTS categories(name text primary key, total real)'
            )
Exemple #10
0
    def quick_pay(self, name):
        with DatabaseConnection(self.bills_db) as connection:
            cursor = connection.cursor()

            try:
                cursor.execute('SELECT remaining FROM bills WHERE name=?',
                               (name, ))  # finish quick pay method
                bill_remaining = cursor.fetchone()[0]
                cursor.execute('SELECT payment FROM bills WHERE name=?',
                               (name, ))
                bill_payment = cursor.fetchone()[0]
                cursor.execute('SELECT paid FROM bills WHERE name=?', (name, ))
                bill_paid = cursor.fetchone()[0]
            except TypeError:
                print('!! Invalid Query !!')
                return
            else:
                self._write_payment_log(name, bill_payment)

            bill_remaining -= bill_payment
            if bill_remaining <= 0:
                cursor.execute('UPDATE bills SET complete=? WHERE name=?',
                               (1, name))
                self.logger.info(f'{name.title()} PAID IN FULL')
            else:
                bill_paid += bill_payment
                cursor.execute('UPDATE bills SET remaining=? WHERE name=?',
                               (bill_remaining, name))
                cursor.execute('UPDATE bills SET paid=? WHERE name=?',
                               (bill_paid, name))
    def make_payment(self, oid, amount):
        with DatabaseConnection(self.bills_db) as connection:
            cursor = connection.cursor()

            try:
                cursor.execute('SELECT remaining FROM bills WHERE oid=?',
                               (oid, ))
                expense_remaining = cursor.fetchone()[0]
                cursor.execute('SELECT paid FROM bills WHERE oid=?', (oid, ))
                expense_paid = cursor.fetchone()[0]
                cursor.execute('SELECT name FROM bills WHERE oid=?', (oid, ))
                name = cursor.fetchone()[0]
            except TypeError:
                messagebox.showerror(
                    title='Invalid Selection',
                    message=
                    'You have made an invalid selection. Please select again')
                return None
            else:
                self._write_payment_log(name, amount)

            expense_remaining -= amount
            if expense_remaining <= 0:
                cursor.execute('UPDATE bills SET complete=? WHERE oid=?',
                               (1, oid))
                self.logger.info(f'{name.title()} PAID IN FULL')
            else:
                expense_paid += amount
                cursor.execute('UPDATE bills SET remaining=? WHERE oid=?',
                               (expense_remaining, oid))
                cursor.execute('UPDATE bills SET paid=? WHERE oid=?',
                               (expense_paid, oid))
                cursor.execute('UPDATE bills SET payment=? WHERE oid=?',
                               (amount, oid))
        return 1
Exemple #12
0
async def handle_text(message: types.Message, state: FSMContext):
    await state.finish()
    if message.text == "/exit":
        await message.answer("Отменено")
        return
    try:
        test = await message.answer(message.text, parse_mode='Markdown')
    except exceptions.CantParseEntities:
        await message.answer("Неверный формат Markdown!")
        return
    await bot.delete_message(message.chat.id, test.message_id)
    selectQuery = "SELECT user_id FROM users"
    with DatabaseConnection() as db:
        conn, cursor = db
        cursor.execute(selectQuery)
        users = cursor.fetchall()
    i = 0
    j = 0
    len_users = len(users)
    progress_message = (await message.answer(f'0/{len_users}')).message_id
    for n, user in enumerate(users, 1):
        if await mu.send_message(bot.send_message,
                                 exceptions,
                                 chat_id=user[0],
                                 text=message.text,
                                 parse_mode='Markdown'):
            i += 1
        else:
            j += 1
        await bot.edit_message_text(f'{n}/{len_users}', message.chat.id,
                                    progress_message)
        await sleep(.1)
    await message.answer(f"Отправлено: {i}\nНе отправлено: {j}")
 def reset():
     try:
         with DatabaseConnection('categories.db') as connection:
             cursor = connection.cursor()
             cursor.execute('DROP TABLE categories')
     except OperationalError:
         pass
Exemple #14
0
    def create_table(self):
        with DatabaseConnection(self.bills_db) as connection:
            cursor = connection.cursor()

            cursor.execute(
                "CREATE TABLE IF NOT EXISTS bills(name text primary key, total real, payment real, "
                "remaining real, paid real, complete BIT)")
Exemple #15
0
    def make_payment(self, name, amount):
        with DatabaseConnection(self.bills_db) as connection:
            cursor = connection.cursor()

            try:
                cursor.execute('SELECT remaining FROM bills WHERE name=?',
                               (name, ))
                expense_remaining = cursor.fetchone()[0]
                cursor.execute('SELECT paid FROM bills WHERE name=?', (name, ))
                expense_paid = cursor.fetchone()[0]
            except TypeError:
                print('!! Invalid Query !!')
                return
            else:
                self._write_payment_log(name, amount)

            expense_remaining -= amount
            if expense_remaining <= 0:
                cursor.execute('UPDATE bills SET complete=? WHERE name=?',
                               (1, name))
                self.logger.info(f'{name.title()} PAID IN FULL')
            else:
                expense_paid += amount
                cursor.execute('UPDATE bills SET remaining=? WHERE name=?',
                               (expense_remaining, name))
                cursor.execute('UPDATE bills SET paid=? WHERE name=?',
                               (expense_paid, name))
                cursor.execute('UPDATE bills SET payment=? WHERE name=?',
                               (amount, name))
Exemple #16
0
async def message_handler(message: types.Message, state: FSMContext):
    await state.finish()
    if message.text == Buttons.back:
        await message.answer("Canceled", reply_markup=moderator_keyboard())
        return
    code: str = message.text.lower()

    selectChatQuery = "SELECT ID FROM chats WHERE code=(%s)"
    selectMediaQuery = "SELECT type, file_id FROM media_messages WHERE chat=(%s)"
    selectTextQuery = "SELECT user, time, text FROM text_messages WHERE chat=(%s)"
    text, media = None, None
    with DatabaseConnection() as db:
        conn, cursor = db
        cursor.execute(selectChatQuery, [code])
        chat_id = cursor.fetchone()
        if chat_id:
            cursor.execute(selectMediaQuery, [chat_id[0]])
            media = cursor.fetchall()
            cursor.execute(selectTextQuery, [chat_id[0]])
            text = cursor.fetchall()

    if not chat_id:
        await message.answer("Chat does not exist!",
                             reply_markup=moderator_keyboard())
        return
    if not text:
        await message.answer("There are no text messages")
    else:
        buffer = ''
        for t in text:
            user, time, text = t[0], t[1], t[2]
            buffer += f'{datetime.datetime.strftime(time, "%d.%m / %H:%M")} - {user}:\n{text}\n\n'
        with open(code, 'wt', encoding='utf-8') as f:
            f.write(buffer)
        del buffer
        await bot.send_document(
            message.chat.id, types.InputFile(code,
                                             f'{code} text messages.txt'))
        try:
            os.remove(code)
        except Exception as e:
            print(e)

    if not media:
        await message.answer("There are no media messages")
    else:
        for m in media:
            filetype, fileid = m[0], m[1]
            try:
                if filetype == c.PHOTO:
                    await bot.send_photo(message.chat.id, fileid)
                elif filetype == c.VIDEO:
                    await bot.send_video(message.chat.id, fileid)
                elif filetype == c.DOCUMENT:
                    await bot.send_document(message.chat.id, fileid)
            except Exception as e:
                await message.answer(str(e))
            await sleep(.05)
    await message.answer("Sending finished", reply_markup=moderator_keyboard())
    def add_student_information(nuid):
        first_name = input("Enter your first name: ")
        last_name = input("Enter your last name: ")
        level_study = input("Enter the level of study: ")
        department = input("Enter what department you are in: ")

        add_student_query = "INSERT INTO students " \
                            "(studentAccount_nuid, firstName, lastName, level, department)" \
                            "VALUES (%s, %s, %s, %s, %s)"

        data_student = (nuid, first_name, last_name, level_study, department)

        db_connection = DatabaseConnection.initiate_database_connection()
        cursor = db_connection.cursor()
        cursor.execute(add_student_query, data_student)
        cursor.close()
        DatabaseConnection.exit_database_connection(db_connection)
Exemple #18
0
def save_data(chat: int,
              name: str,
              text: str = None,
              data_type: str = None,
              data: str = None):
    insertTextQuery = "INSERT INTO text_messages (chat, user, text) VALUES (%s, %s, %s)"
    insertMediaQuery = "INSERT INTO media_messages (chat, type, file_id) VALUES (%s, %s, %s)"
    if text:
        with DatabaseConnection() as db:
            conn, cursor = db
            cursor.executemany(insertTextQuery, [(chat, name, text)])
            conn.commit()
    if data:
        with DatabaseConnection() as db:
            conn, cursor = db
            cursor.executemany(insertMediaQuery, [(chat, data_type, data)])
            conn.commit()
Exemple #19
0
 def __db_is_item_available(self, id):
     with DatabaseConnection() as db:
         inv, _ = db.get_table("available_items")
         q = db.query().\
             add_columns(inv).\
             filter(inv.c.id == id)
         db.execute(q)
         return len([r for r in db.fetchall()]) > 0
Exemple #20
0
 def __db_approve(self, id, approver):
     with DatabaseConnection() as db:
         co, _ = db.get_table("checked_out")
         q = co.update().\
             where(co.c.id == id).\
             values(approved_by=approver)
         db.execute(q)
         return
    def get_PPR_based_feedback(self, q, rel_items, irl_items, obj_feature_matrix, m):
        q_new = self.compute_new_query_vector(q_old=q, relevant_items=rel_items, irrel_items=irl_items)
        topology_images = read_from_pickle('test_dataset.pickle')
        image_names = get_image_names_from_tuples(topology_images)
        db_conn = DatabaseConnection()
        data_image_dict = db_conn.HOG_descriptor_from_image_ids(image_names)
        data_matrix = data_image_dict['data_matrix']
        image_names = data_image_dict['images']
        svd_obj = SingularValueDecomposition()
        svd_image_data = svd_obj.get_transformed_data(data_matrix, 8)  # change this for 11K images

        pg_obj = PageRank()
        image_similarity_matrix = pg_obj.get_image_similarity_matrix_for_top_k_images(6, svd_image_data)
        seed_vector = pg_obj.get_seed_vector(rel_items, image_names, irl_items)
        pie = pg_obj.get_page_rank_eigen_vector(image_similarity_matrix, seed_vector)
        new_rank_list = pg_obj.get_top_K_images_based_on_scores(pie, image_names, m)

        return new_rank_list
Exemple #22
0
 def __db_insert_competition(self, data):
     with DatabaseConnection() as db:
         comps, _ = db.get_table("competition")
         q = comps.insert().\
             values(
                 id=data['id'],
                 documentation=data['documentation'],
                 location=data['location'])
         db.execute(q)
Exemple #23
0
def add_username_password():
    hashed_password = bcrypt.hashpw(
        input("Enter your password").encode("utf-8"), bcrypt.gensalt())
    username = input("Enter your username")
    print(hashed_password)
    with DatabaseConnection("data.db") as connection:
        cursor = connection.cursor()
        cursor.execute('INSERT INTO validation VALUES(?,?)',
                       (username, hashed_password))
Exemple #24
0
 def __db_insert_meeting(self, data):
     with DatabaseConnection() as db:
         mts, _ = db.get_table("meeting")
         q = mts.insert().\
             values(
                 id=data['id'],
                 minutes=data['minutes'],
                 required=data['required'])
         db.execute(q)
Exemple #25
0
def service():
    #Note: Add the path to the settings file
    database_file_path = os.path.join(current_directory,
                                      "../DBScript/CMD2WEB.sqlite")
    database_object = DatabaseConnection(database_file_path)

    service = request.args.get('service')

    if not service:
        logger.error("No service specified.")
        return cmd2web.Server.error('No service specified')

    if not server.has_service(service):
        logger.error("Unknown service.")
        return cmd2web.Server.error('Unknown service')

    if not server.services[service].args_match(request.args):
        logger.error('Argument mismatch')
        return cmd2web.Server.error('Argument mismatch')

    service_instance = server.services[service].copy()
    sys.stderr.write(
        "\n\n\nService Instance: {0}\n\n\n".format(service_instance))
    if (hasattr(service_instance, 'group')):
        restricted = database_object.get_restricted_access(
            service_instance.group)
        if (restricted == True):
            #Check if token is present in parameter
            token = request.args.get('token')
            if not token:
                logger.error("Access restricted without token.")
                return cmd2web.Server.error('Access restricted without token.')
            token_access = database_object.check_token_access(
                service_instance.group, token)
            if (token_access == True):
                return process_service(service_instance, request.args)
            else:
                logger.error("Wrong or expired token. Access Denied.")
                return cmd2web.Server.error(
                    'Wrong or expired token. Access Denied')
        else:
            return process_service(service_instance, request.args)
    else:
        return process_service(service_instance, request.args)
Exemple #26
0
 def __db_get_inventory(self):
     with DatabaseConnection() as db:
         inv, _ = db.get_table("inventory")
         q = db.query().\
             add_columns(
                 inv.c.id, inv.c.description, inv.c.serial_number, inv.c.make,
                 inv.c.model, inv.c.manufacturer, inv.c.location,
                 inv.c.other_notes)
         db.execute(q)
         return [self.encode_id(dict(row), 'inventory_id') for row in db.fetchall()]
Exemple #27
0
 def __db_insert_request(self, data):
     with DatabaseConnection() as db:
         co, _ = db.get_table("checked_out")
         q = co.insert().\
             values(
                 item_id=data['item_id'],
                 requested_by=data['person_id'],
                 start_date=data['start_date'],
                 expected_return_date=data['end_date'])
         db.execute(q)
Exemple #28
0
 def __db_get_positions(self):
     with DatabaseConnection() as db:
         positions, _ = db.get_table("position")
         q = db.query().\
             add_columns(
                 positions.c.pos_id, positions.c.person_id, positions.c.title,
                 positions.c.start_date, positions.c.end_date)
         db.execute(q)
         positions = [ self.encode_id(dict(row), 'position_id') for row in db.fetchall() ]
         return positions[::-1]
Exemple #29
0
 def __db_get_item(self, id):
     with DatabaseConnection() as db:
         inv, _ = db.get_table("inventory")
         q = db.query().add_columns(inv).filter(inv.c.id == id)
         db.execute(q)
         rows = [self.encode_id(dict(row), 'inventory_id')
                 for row in db.fetchall()]
         if len(rows) != 1:
             return None
         return rows[0]
Exemple #30
0
    def _add_expense(self, name, amount):
        bill = self._get_bill(name)
        bill_remaining = bill['remaining']
        bill_remaining += amount

        with DatabaseConnection(self.bills_db) as connection:
            cursor = connection.cursor()

            cursor.execute('UPDATE bills SET remaining=? WHERE name=?',
                           (bill_remaining, name))
 def check_connection(self):
     try:
         self.database.database.isolation_level
     except OperationalError:
         print("Database connection reestablished at {} time", str(time.time()))
         configs = get_configurations("./config.ini", "Default Settings")
         host = (configs["host"], "host")
         dbname = (configs["dbname"], "dbname")
         username = (configs["username"], "username")
         password = (configs["password"], "password")
         self.database = DatabaseConnection(host[0], dbname[0], username[0], password[0])
    def __init__(self, token, host, dbname, user, password):
        super().__init__(token)
        self.bot = telepot.Bot(token)
        self.database = DatabaseConnection(host, dbname, user, password)
        self.bot.notifyOnMessage(self.handle)
        self.birthdays = {}
        self.count = 0
        self.timer = time.time()

        self.token = token
        self.host = host
        self.dbname = dbname
        self.user = user
        self.password = password
class RelAgeBot(telepot.Bot):
    def __init__(self, token, host, dbname, user, password):
        super().__init__(token)
        self.bot = telepot.Bot(token)
        self.database = DatabaseConnection(host, dbname, user, password)
        self.bot.notifyOnMessage(self.handle)
        self.birthdays = {}
        self.count = 0
        self.timer = time.time()

        self.token = token
        self.host = host
        self.dbname = dbname
        self.user = user
        self.password = password

    def birth(self, chat_id, msg):
        tokens = msg["text"].split()
        if len(tokens) > 1:
            full_name = msg["text"].replace("/birth ", "")
            unidecode_name = unidecode.unidecode(full_name).lower().replace(' ', '')
            result = self.database.execute_query(QueryBuilder.add_query(chat_id, unidecode_name, 0, 0, False))
            if result == "23505":
                self.bot.sendMessage(chat_id, full_name + " already exists in some sort of way or shape")
            elif result == "25P02":
                self.bot.sendMessage(chat_id, "Something went terribly wrong, please contact your shizadmin")
            else:
                self.bot.sendMessage(chat_id, full_name + " is born")
        else:
            self.bot.sendMessage(chat_id, "usage: /birth <name of person>")

    def age(self, chat_id, msg):
        tokens = msg["text"].split()
        if len(tokens) > 1:
            full_name = msg["text"].replace("/age ", "")
            unidecode_name = unidecode.unidecode(full_name).lower().replace(' ', '')
            result_query = self.database.execute_query(QueryBuilder.get_query(chat_id, unidecode_name))
            if len(result_query) == 1:
                age = result_query[0][2]
                self.bot.sendMessage(chat_id, full_name + " is " + str(age) + " years old")
            elif len(result_query) > 1:
                message = full_name + " is ambigious\n you could have meant:"
                for row in result_query:
                    message += "\t" + row[2] + "\n"
                self.bot.sendMessage(chat_id, message)
            else:
                self.bot.sendMessage(chat_id,
                                     full_name + " does not exist yet \nUse /birth for " + full_name + " to exists")
        else:
            self.bot.sendMessage(chat_id, "usage /age <name of person>")

    def kill(self, chat_id, msg):
        tokens = msg["text"].split()
        if len(tokens) > 1:
            full_name = msg["text"].replace("/kill ", "")
            unidecode_name = unidecode.unidecode(full_name).lower().replace(' ', '')
            result_query = self.database.execute_query(QueryBuilder.remove_query(chat_id, unidecode_name))

            if len(result_query) == 1:
                age = result_query[0][2]
                self.bot.sendMessage(chat_id, full_name + " was " + str(age) + " years old when last seen")
            elif len(result_query) > 1:
                message = full_name + " is ambigious\n you could have meant:"
                for row in result_query:
                    message += "\t" + row[2] + "\n"
                self.bot.sendMessage(chat_id, message)
            else:
                self.bot.sendMessage(chat_id,
                                     full_name + " does not exist yet \nUse /birth for " + full_name + " to exists")
        else:
            self.bot.sendMessage(chat_id, "usage: /kill <name of person>")

    def birthday(self, chat_id, msg):
        tokens = msg["text"].split()
        if len(tokens) > 1:
            full_name = msg["text"].replace("/birthday ", "")
            unidecode_name = unidecode.unidecode(full_name).lower().replace(' ', '')

            result_query = self.database.execute_query(QueryBuilder.get_query(chat_id, unidecode_name))
            if len(result_query) == 1:
                if time.time() - result_query[0][3] < 60 and result_query[0][3] is not 0:
                    if not result_query[0][4]:
                        self.bot.sendMessage(chat_id, "You already asked, try again in one minute")
                        self.database.execute_query(QueryBuilder.update_already_asked(chat_id, unidecode_name, True))
                    return
            elif len(result_query) > 1:
                message = full_name + " is ambigious\n you could have meant:"
                for row in result_query:
                    message += "\t" + row[2] + "\n"
                self.bot.sendMessage(chat_id, message)
                return
            else:
                self.bot.sendMessage(chat_id,
                                     full_name + " does not exist yet \nUse /birth for " + full_name + " to exist")
                return
            self.database.execute_query(QueryBuilder.update_already_asked(chat_id, unidecode_name, False))
            self.database.execute_query(QueryBuilder.update_last_modified(chat_id, unidecode_name, int(time.time())))
            result_query = self.database.execute_query(QueryBuilder.update_age(chat_id, unidecode_name, 1))

            if len(result_query) == 1:
                age = result_query[0][2]
                birthday_msg = "Whoooohoooooo! Happy birthday! " + full_name + " is now " + str(age) + " years old"
                self.bot.sendMessage(chat_id, birthday_msg)

            elif len(result_query) > 1:
                message = full_name + " is ambigious\n you could have meant:"
                for row in result_query:
                    message += "\t" + row[2] + "\n"
                self.bot.sendMessage(chat_id, message)
            else:
                self.bot.sendMessage(chat_id,
                                     full_name + " does not exist yet \nUse /birth for " + full_name + " to exist")
        else:
            self.bot.sendMessage(chat_id, "usage /birthday <name of person>")

    def check_connection(self):
        try:
            self.database.database.isolation_level
        except OperationalError:
            print("Database connection reestablished at {} time", str(time.time()))
            configs = get_configurations("./config.ini", "Default Settings")
            host = (configs["host"], "host")
            dbname = (configs["dbname"], "dbname")
            username = (configs["username"], "username")
            password = (configs["password"], "password")
            self.database = DatabaseConnection(host[0], dbname[0], username[0], password[0])

    def handle(self, msg):
        chat_id = msg['chat']['id']
        command = msg['text']

        print(msg)

        if time.time() - self.timer > 0.9:
            self.timer = time.time()
            self.count = 0
        elif self.count < 39:
            self.count += 1
        else:
            self.bot.sendMessage(chat_id, "You killed me with message ID: " + msg["message_id"])
            exit()

        self.check_connection()

        if '/birthday' in command:
            self.birthday(chat_id, msg)
        elif '/birth' in command:
            self.birth(chat_id, msg)
        elif '/kill' in command:
            self.kill(chat_id, msg)
        elif '/age' in command:
            self.age(chat_id, msg)
 def __init__(self, host='localhost', port=6379, database=0):
     DatabaseConnection.__init__(self)
     self.__host = host
     self.__port = port
     self.__database = database
     self.__connection = None