def update_purchase(): customer_num_ids = utils.count_rows("customer") product_num_ids = utils.count_rows("product") purchase_customer_id = utils.get_random_number(1, customer_num_ids) purchase_product_id = utils.get_random_number(1, product_num_ids) utils.execute( """update purchase set customer_id = {PURCHASE_CUSTOMER_ID} where product_id = {PURCHASE_PRODUCT_ID};""" .format(PURCHASE_CUSTOMER_ID=purchase_customer_id, PURCHASE_PRODUCT_ID=purchase_product_id)) advance_time()
def update_category(): rand_id = utils.get_random_number(1, utils.count_rows("category")) rand_name = utils.get_random_string() utils.execute( """update category set name = '{RAND_NAME}' where id = {RAND_ID};""". format(RAND_NAME=rand_name, RAND_ID=rand_id)) advance_time()
def update_customer(): rand_id = utils.get_random_number(1, utils.count_rows("customer")) customer_active = utils.get_random_boolean() utils.execute( """update customer set active = '{CUSTOMER_ACTIVE}' where id = {RAND_ID};""" .format(CUSTOMER_ACTIVE=customer_active, RAND_ID=rand_id)) advance_time()
def delete_category_product(): ## Delete some pair found_good_pair = False while not found_good_pair: category_num_ids = utils.count_rows("category") _category_id = utils.get_random_number(1, category_num_ids) product_num_ids = utils.count_rows("product") _product_id = utils.get_random_number(1, product_num_ids) pair = (_category_id, _product_id) if pair in _category_product_pairs: #_category_product_pairs.remove(pair) found_good_pair = True break if not found_good_pair: return category_product_category_id = pair[0] category_product_product_id = pair[1] _category_product_pairs.remove(pair) #utils.execute("""update category_product set category_id = {CATEGORY_PRODUCT_CATEGORY_ID} where product_id = {CATEGORY_PRODUCT_PRODUCT_ID};""".format( # CATEGORY_PRODUCT_CATEGORY_ID=category_product_category_id, CATEGORY_PRODUCT_PRODUCT_ID=category_product_product_id)) utils.execute( """delete from category_product where category_id = {CATEGORY_PRODUCT_CATEGORY_ID} and product_id = {CATEGORY_PRODUCT_PRODUCT_ID};""" .format(CATEGORY_PRODUCT_CATEGORY_ID=category_product_category_id, CATEGORY_PRODUCT_PRODUCT_ID=category_product_product_id)) ## Insert modification of the deleted key found_new_pair = False while not found_new_pair: product_num_ids = utils.count_rows("product") _product_id = utils.get_random_number(1, product_num_ids) new_pair = (category_product_category_id, _product_id) if new_pair not in _category_product_pairs: #_category_product_pairs.remove(pair) found_new_pair = True break if not found_new_pair: return new_category_product_product_id = new_pair[1] _category_product_pairs.append(new_pair) utils.execute( """INSERT INTO category_product (category_id, product_id) VALUES ({CATEGORY_PRODUCT_CATEGORY_ID}, {CATEGORY_PRODUCT_PRODUCT_ID});""" .format(CATEGORY_PRODUCT_CATEGORY_ID=category_product_category_id, CATEGORY_PRODUCT_PRODUCT_ID=new_category_product_product_id)) advance_time()
def update_product(): rand_id = utils.get_random_number(1, utils.count_rows("product")) product_cost = utils.get_random_number(0, 1000) product_amount = utils.get_random_number(0, 10000) utils.execute( """update product set cost = {PRODUCT_COST} where id = {RAND_ID};""". format(PRODUCT_COST=product_cost, RAND_ID=rand_id)) advance_time()
def get_answer(message): db_worker = sqlighter(config.database_name) row = db_worker.select_single(random.randint(1, utils.count_rows())) match = re.search(reg, message.text) try: if match: time.sleep(random.randint(15, 30)) bot.reply_to(message, row[0].format(message.text)) elif message.reply_to_message.from_user.id == bot.get_me().id: time.sleep(random.randint(15, 30)) bot.reply_to(message, row[0].format(message.text)) except: time.sleep(10) # except: # time.sleep(10) db_worker.close()
markup = utils.generate_markup(row[2],row[3]) # Отправляем аудиофайл с вариантами ответа bot.send_voice(message.chat.id, row[1], reply_markup=markup) # Включаем "игровой режим" utils.set_user_game(message.chat.id, row[2]) # Отсоединяемся от БД db_worker.close() @bot.message_handler(func=lambda message:True, content_types=['text']) def check_answer(message): # Если функция возвращает None -> Человек не в игре answer = utils.get_answer_for_user(message.chat.id) # Как вы помните, answer может быть либо текстом, либо None # Если None: if not answer: bot.send_message(message.chat.id, 'Чтобы начать игру, выберите команду /game') else: # Уберем клавиатуру с вариантами ответа. keyboard_hider = telebot.types.ReplyKeyboardRemove() # Если ответ правильный/неправильный if message.text == answer: bot.send_message(message.chat.id, 'Верно!', reply_markup=keyboard_hider) else: bot.send_message(message.chat.id, 'Увы, Вы не угадали. Попробуйте ещё раз!', reply_markup=keyboard_hider) # Удаляем юзера из хранилища (игра закончена) utils.finish_user_game(message.chat.id) if __name__ == '__main__': utils.count_rows() random.seed() bot.polling(none_stop=True)
import telebot import config import os import time import utils from SQLighter import SQLighter import random from telebot import types bot = telebot.TeleBot(config.token) @bot.message_handler(commands=['test']) def find_file_ids(message): for file in os.listdir('/Users/beibarysbakytzhan/Desktop/Nd/'): if file.split('.')[-1] == 'ogg': f = open('/Users/beibarysbakytzhan/Desktop/Nd/' + file, 'rb') msg = bot.send_voice(message.chat.id, f, None) # А теперь отправим вслед за файлом его file_id bot.send_message(message.chat.id, msg.voice.file_id, reply_to_message_id=msg.message_id) time.sleep(3) @bot.message_handler(commands=['game']) def game(message): # Подключаемся к БД db_worker = SQLighter(config.database_name) # Получаем случайную строку из БД row = db_worker.select_single(random.randint(1, utils.get_rows_count())) # Формируем разметку markup = utils.generate_markup(row[2], row[3])
def _get_pair_customer_product(): customer_num_ids = utils.count_rows("customer") product_num_ids = utils.count_rows("product") purchase_customer_id = utils.get_random_number(1, customer_num_ids) purchase_product_id = utils.get_random_number(1, product_num_ids) return (purchase_customer_id, purchase_product_id)
def _get_pair_category_product(): category_num_ids = utils.count_rows("category") product_num_ids = utils.count_rows("product") category_product_category_id = utils.get_random_number(1, category_num_ids) category_product_product_id = utils.get_random_number(1, product_num_ids) return (category_product_category_id, category_product_product_id)
# Как Вы помните, answer может быть либо текст, либо None # Если None: if not answer: bot.send_message(message.chat.id, 'Чтобы начать игру, выберите команду /game') else: # Уберем клавиатуру с вариантами ответа. keyboard_hider = types.ReplyKeyboardHide() # Если ответ правильный/неправильный if message.text == answer: bot.send_message(message.chat.id, 'Верно!', reply_markup=keyboard_hider) else: bot.send_message(message.chat.id, 'Увы, Вы не угадали. Попробуйте ещё раз!', reply_markup=keyboard_hider) # Удаляем юзера из хранилища (игра закончена) utils.finish_user_game(message.chat.id) @bot.message_handler(commands=['test']) def find_file_ids(message): for file in os.listdir('music/'): if file.split('.')[-1] == 'ogg': f = open(file, 'rb') res = bot.send_voice(message.chat.id, f, None) print(res) time.sleep(3) if __name__ == '__main__': utils.count_rows() random.seed() bot.polling(none_stop=True)
import utils from SQLighter import SQLighter import config import random random.seed() #Функция для дебага, если дебаг включен, то для каждого вопроса генерируется один вариант def for_count_r(j): if config.debug == 1: return 2 else: return utils.get_rows_count(j) utils.count_rows() #подсчет строк в таблицах базы данных db_worker = SQLighter(os.getcwd() + config.database_name) #Подключение к базе данных start = 0 #Переменная блокирующая создание множества файлов при указании записи в один #Генератор GIFT для заданий 1-6 for j in range(1, 7): #Устанвока в один файл, или несколько if config.one_file == 1 and start == 0: f = open(os.getcwd() + "/testAll.txt", "w") start = 1 if config.one_file == 0: f = open(os.getcwd() + "/test" + str(j) + ".txt", "w") #Создание записи о категории f.write("\n") f.write("$CATEGORY: $cat$/top/ОГЭ Информатика/" + config.category[j - 1]) f.write("\n")