From 10df69242df3f59af3ed039f08f3c1bb2ee13100 Mon Sep 17 00:00:00 2001 From: RakVhalate Date: Sun, 21 Jan 2024 17:00:25 +1000 Subject: [PATCH] Some refactor --- DBChat/user_operations.py | 18 ++++ TopMsg/topdicks.py | 64 ++++++++++++ dicktxt/change_words.py | 34 ++++++ dicktxt/dick_sinonims.txt | 5 +- handlers/pipisa.py | 213 ++++++++++++-------------------------- handlers/time_new_year.py | 2 +- 6 files changed, 187 insertions(+), 149 deletions(-) create mode 100644 DBChat/user_operations.py create mode 100644 TopMsg/topdicks.py create mode 100644 dicktxt/change_words.py diff --git a/DBChat/user_operations.py b/DBChat/user_operations.py new file mode 100644 index 0000000..729e857 --- /dev/null +++ b/DBChat/user_operations.py @@ -0,0 +1,18 @@ +import datetime + +def UserCreate(DBName, message, result, replyId): #create new user + + new_user = { #описание класса пользователя + 'user_id': message.from_user.id, #уникальный идентификатор пользователя + 'user_fullname': message.from_user.full_name, #никнэйм + 'dick_size': result, #размер пиписы + 'datetimes': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), #время прокрута + 'attempts': 1, #общее количество попыток прокрутки + 'chat_id': message.chat.id, #уникальный идентификатор конфы, в которой этот пользователь крутит + 'reply_id': replyId.id #идентификатор последнего ответа для этого пользователя + } + try: + metadata = DBName.insert(new_user, overwrite_mode='update') + except Exception as add_err: + print('ошибка в добавлении нового пользователя') + print(add_err) \ No newline at end of file diff --git a/TopMsg/topdicks.py b/TopMsg/topdicks.py new file mode 100644 index 0000000..2dd72d8 --- /dev/null +++ b/TopMsg/topdicks.py @@ -0,0 +1,64 @@ +async def topdicks_conf(chatId): # тело метода лучших результатов отдельной конфы + arango_client = ArangoClient(hosts='https://arango.guaranteedstruggle.host') + pipisa_db = arango_client.db('pipisa', username='root', password='stolendick527') + dicks_collection = pipisa_db.collection('dicks') + + try: + dicks = dicks_collection.find({'chat_id': chatId}, skip=0, limit=1100) + dicks = [d for d in dicks] + except Exception as e: + print('ошибка DB в /topdick') + print(e) + + top_dicks = sorted(dicks, key=lambda dick: dick['dick_size'], reverse=True) + + dick_limit = min(len(top_dicks), 10) + top_dicks = top_dicks[:dick_limit] + + conf_top = '' + emo = ['🏆','🚀','🍆','🍌','🐍','🐎','🌭','🌶','👌','💩'] + + if len(top_dicks) == 0: + await bot.send_message(message.chat.id, '🍆 Никто ничего не нарастил! 🍌') + else: + for i in range(len(top_dicks)): + conf_top += f' {emo[i]} {i+1}. {top_dicks[i]["user_fullname"]}: {top_dicks[i]["dick_size"]}см\n' + i += 1 + + + return conf_top + + + +async def topdicks_global(chatId): #тело метода глобальных лучших результатов + arango_client = ArangoClient(hosts='https://arango.guaranteedstruggle.host') + pipisa_db = arango_client.db('pipisa', username='root', password='stolendick527') + dicks_collection = pipisa_db.collection('dicks') + + try: + dicks = dicks_collection.all( ) + dicks = [d for d in dicks if d['user_id'] != d['chat_id']] + except Exception as e: + print('ошибка DB в /glovaldick') + print(e) + + top_dicks = sorted(dicks, key=lambda dick: dick['dick_size'], reverse=True) + + + dick_limit = min(len(top_dicks), 10) + top_dicks = top_dicks[:dick_limit] + + global_top = '' + emo = ['🏆','🚀','💫','🍆','🍌','🐍','🐎','🌭','🌶','👌'] + + if len(top_dicks) == 0: + await bot.send_message(chatId, '🍆 Никто ничего не нарастил! 🍌') + else: + for i in range(len(top_dicks)): + global_top += f' {emo[i]} {i+1}. {top_dicks[i]["user_fullname"]}: {top_dicks[i]["dick_size"]}см\n' + i += 1 + + return global_top + + + \ No newline at end of file diff --git a/dicktxt/change_words.py b/dicktxt/change_words.py new file mode 100644 index 0000000..db5f0a5 --- /dev/null +++ b/dicktxt/change_words.py @@ -0,0 +1,34 @@ +import random + +def ChangeWord(result): #выбирает рандомное слово для изменения размера пиписы + + if result > 0: + size_change = random.choice(dick_inc) + '🚀' + elif result == 0: + size_change = random.choice(dick_static) + '🤨' + else: + size_change = random.choice(dick_decr) + '✂' + + + dick_inc = ( + 'вырос', + 'подрос', + 'привстал', + 'увеличился', + 'преисполнился' + ) + dick_static = ( + 'продвинулся', + 'наноуменьшился', + 'познал стабильность', + 'зафиксировал прибыль' + ) + dick_decr = ( + 'неудачно потусил на сходке', + 'уменьшился', + 'откусила злая гадюка', + 'продали евреи, он стал дешевле', + 'схуднул' + 'отрицательно вырос' + ) + return size_change \ No newline at end of file diff --git a/dicktxt/dick_sinonims.txt b/dicktxt/dick_sinonims.txt index d24bed0..2ed35c2 100644 --- a/dicktxt/dick_sinonims.txt +++ b/dicktxt/dick_sinonims.txt @@ -1,4 +1,4 @@ -Кожаный бабах +кожаный бабах пистон дуршлаг елдак @@ -92,4 +92,5 @@ маленький жиголо венерический суккуб боец невидимого фронта -сморчок \ No newline at end of file +сморчок +джечник \ No newline at end of file diff --git a/handlers/pipisa.py b/handlers/pipisa.py index 1c9082b..d75c6f7 100644 --- a/handlers/pipisa.py +++ b/handlers/pipisa.py @@ -1,12 +1,13 @@ from aiogram import types, Dispatcher -#from sqlalchemy.orm.session import close_all_sessions from create_bot import bot, dp -#from sqdb import user, session import random from random import randint import datetime from dicktxt import ForReadDict +from dicktxt import change_words from pipisa_functions import pipisa_time +from DBChat import user_operations +from TopMsg import topdicks #### https://docs.python-arango.com/en/main/ @@ -27,83 +28,67 @@ async def up_dick(message: types.Message): dicks_collection = pipisa_db.collection('dicks') - # рандомайзер - numb = randint(-9,10) - dick_plus = ( - 'вырос', - 'подрос', - 'привстал', - 'увеличился', - 'преисполнился' - ) - dick_minus = ( - 'неудачно потусил на сходке', - 'уменьшился', - 'откусила злая гадюка', - 'продали евреи, он стал дешевле', - 'схуднул' - ) - dick_stayed = ( - 'продвинулся', - 'наноуменьшился', - 'зафиксировал прибыль' - ) + + result = randint(-9,10) # главный рандомайзер - if numb > 0: - size_change = random.choice(dick_plus) + '🚀' - elif numb == 0: - size_change = random.choice(dick_stayed) + '🤨' - else: - size_change = random.choice(dick_minus) + '✂' - - - try: - #### Чекнуть есть ли юзер в базе - candidate_cursor = dicks_collection.find( + try: ## Тело метода прокрутки + + candidate_cursor = dicks_collection.find( ## Проверить наличие пользователя в базе { 'user_id': message.from_user.id, 'chat_id': message.chat.id }, skip=0, limit=1488) - if candidate_cursor.count() > 0: - ## Если есть то нарастить и отправить сообщение - + if candidate_cursor.count() > 0: ## Если пользователь есть то нарастить и отправить сообщение + user = candidate_cursor.pop() - - if pipisa_time.rolltime(check_datetime=user['datetimes'], curr_time=datetime.datetime.now()): - # пришло время крутить!! + if pipisa_time.rolltime(check_datetime=user['datetimes'], curr_time=datetime.datetime.now()): - updetedDick = user["dick_size"] + numb + updetedDick = user["dick_size"] + result ## получение итогового результата + + pipisa_word = ForReadDict.RandomDick() + change_word = change_words.ChangeWord(result) + + prev_enl_message_id = user["reply_id"] + await bot.delete_message(prev_enl_message_id) + + + enl_message = await bot.send_message(message.chat.id, f"@\ + {message.from_user.username}, \ + ваш {pipisa_word} ,{change_word(result)} на {abs(result)} см!\n\ \ + Теперь он равен {updetedDick} см! ") + + try: dt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") metadata = dicks_collection.insert( { - '_key': user['_key'], ### этот нужен чтобы апдейт прилетал тому же юзеру + '_key': user['_key'], ## этот нужен чтобы апдейт прилетал тому же юзеру 'user_id': user['user_id'], 'user_fullname': message.from_user.full_name, 'dick_size': updetedDick, 'datetimes': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), 'attempts': user['attempts'] + 1, - 'chat_id': message.chat.id + 'chat_id': message.chat.id, + 'reply_id': enl_message.id + }, overwrite_mode='update' ) print(f'Успешно апдейтнули пипису @{message.from_user.username}') - except Exception as e2: + except Exception as update_err: print(f'ошибка в обновлении пиписы @{message.from_user.username}') - print(e2) - - randomword = ForReadDict.RandomDick() - - - await bot.send_message(message.chat.id, f'@{message.from_user.username}, ваш {randomword} {size_change}\ -на {abs(numb)} см!\n\ -Теперь он равен {updetedDick} см! ') + print(update_err) else: - await bot.send_message(message.chat.id, f'@{message.from_user.username},🚫 вы уже крутили пипису, ее размер {user["dick_size"]} см! ') - + + prev_err_message_id = user["reply_id"] ##удалить предыдущее сообщение + await bot.delete_message(prev_err_message_id) + error_msg = await bot.send_message(message.chat.id, f'@\ + {message.from_user.username},🚫 вы уже крутили пипису, \ + ее размер {user["dick_size"]} см! ') + try: metadata = dicks_collection.insert( { @@ -113,51 +98,39 @@ async def up_dick(message: types.Message): 'dick_size': user['dick_size'] , 'datetimes': user['datetimes'] , 'attempts': user['attempts'] + 1, - 'chat_id': message.chat.id + 'chat_id': message.chat.id, + 'reply_id': error_msg.id }, overwrite_mode='update' ) print(f'Успешно апдейтнули попытку крутить пипису @{message.from_user.username}') - except Exception as e2: + except Exception as roll_err: print(f'ошибка в обновлении попытки крутить пипису @{message.from_user.username}') - print(e2) + print(roll_err) print(f'пользователь @{message.from_user.username} уже крутил') - else: - ## если нету, то создать - - try: - novenkiy = { - 'user_id': message.from_user.id, - 'user_fullname': message.from_user.full_name, - 'dick_size': numb, - 'datetimes': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), - 'attempts': 1, - 'chat_id': message.chat.id - } - - metadata = dicks_collection.insert(novenkiy, overwrite_mode='update') - - - if numb > 0: - await bot.send_message(message.chat.id, f'@{message.from_user.username}, ваш писюн показал головку 🚀\n\ -на {abs(numb)} см!\n\ -Теперь он равен {numb} см!') + else: ## если пользователь не найден то создаём ему запись в БД + + if result > 0: + new_reply = await bot.send_message(message.chat.id, f'@\ + {message.from_user.username}, ваш писюн показал головку 🚀\n\ + на {abs(result)} см!\n\ + Теперь он равен {result} см!') else: - await bot.send_message(message.chat.id, f'@{message.from_user.username}, добро пожаловать в игру!🚀\n\ -Ты стартуешь не с лучшей позиции, природа наградила тебя всего {numb} см 😬') - - + new_reply =await bot.send_message(message.chat.id, f'@\ + {message.from_user.username}, добро пожаловать в игру!🚀\n\ + Ты стартуешь не с лучшей позиции, природа наградила тебя всего {result} см 😬') + + user_operations.UserCreate(dicks_collection, message, result, new_reply.id) + print(f'Успешно добавлен пользователь @{message.from_user.username}') - except Exception as e1: - print('ошибка в добавлении нового пользователя') - print(e1) + - except Exception as e: + except Exception as crit_err: print('ошибка DB в /dick') - print(e) + print(crit_err) else: await message.reply('Растить елду можно только в общих чатах!') @@ -166,74 +139,22 @@ async def up_dick(message: types.Message): @dp.message_handler(commands=["topdick"]) -async def send_topchat(message: types.Message): +async def send_topchat(message: types.Message): # тело метода лучших результатов отдельной конфы if message.from_user.id in admins or message.chat.type != 'private': - arango_client = ArangoClient(hosts='https://arango.guaranteedstruggle.host') - pipisa_db = arango_client.db('pipisa', username='root', password='stolendick527') - dicks_collection = pipisa_db.collection('dicks') - - try: - dicks = dicks_collection.find({'chat_id': message.chat.id}, skip=0, limit=1100) - dicks = [d for d in dicks] - except Exception as e: - print('ошибка DB в /topdick') - print(e) - - top_dicks = sorted(dicks, key=lambda dick: dick['dick_size'], reverse=True) - - dick_limit = min(len(top_dicks), 10) - top_dicks = top_dicks[:dick_limit] - - dickos = '' - emo = ['🏆','🚀','🍆','🍌','🐍','🐎','🌭','🌶','👌','💩'] - - if len(top_dicks) == 0: - await bot.send_message(message.chat.id, '🍆 Никто ничего не нарастил! 🍌') - else: - for i in range(len(top_dicks)): - dickos += f' {emo[i]} {i+1}. {top_dicks[i]["user_fullname"]}: {top_dicks[i]["dick_size"]}см\n' - i += 1 - - await bot.send_message(message.chat.id, '🏆Топ 10 бубылд чата🏆\n\n' + dickos) + dickos = topdicks.topdicks_conf(message.chat.id) + await bot.send_message(message.chat.id, '🏆Топ 10 бубылд чата🏆\n\n' + dickos) else: await message.reply('Работает только в общих чатах!\n'\ - 'Вы мсжете посмотреть топ по миру /globaldick') + 'Вы мсжете посмотреть топ по миру: /globaldick') @dp.message_handler(commands=["globaldick"]) -async def send_global_top(message: types.Message): - - - arango_client = ArangoClient(hosts='https://arango.guaranteedstruggle.host') - pipisa_db = arango_client.db('pipisa', username='root', password='stolendick527') - dicks_collection = pipisa_db.collection('dicks') - - try: - dicks = dicks_collection.all( ) - dicks = [d for d in dicks if d['user_id'] != d['chat_id']] - except Exception as e: - print('ошибка DB в /glovaldick') - print(e) - - top_dicks = sorted(dicks, key=lambda dick: dick['dick_size'], reverse=True) - - - dick_limit = min(len(top_dicks), 10) - top_dicks = top_dicks[:dick_limit] - - dickos = '' - emo = ['🏆','🚀','💫','🍆','🍌','🐍','🐎','🌭','🌶','👌'] - - if len(top_dicks) == 0: - await bot.send_message(message.chat.id, '🍆 Никто ничего не нарастил! 🍌') - else: - for i in range(len(top_dicks)): - dickos += f' {emo[i]} {i+1}. {top_dicks[i]["user_fullname"]}: {top_dicks[i]["dick_size"]}см\n' - i += 1 - - await bot.send_message(message.chat.id, '🏆Топ 10 пипис в мире🏆\n\n' + dickos) +async def send_global_top(message: types.Message): # тело метода лучших результатов + tops = topdicks.topdicks_global(message.chat.id,) + + await bot.send_message(message.chat.id, '🏆Топ 10 пипис в мире🏆\n\n' + tops) diff --git a/handlers/time_new_year.py b/handlers/time_new_year.py index 51cbd17..753ddb2 100644 --- a/handlers/time_new_year.py +++ b/handlers/time_new_year.py @@ -4,7 +4,7 @@ import datetime @dp.message_handler(commands=["time"]) async def send_time(message: types.Message): - new_year = datetime.datetime(2023, 12, 31) #дата нового года + new_year = datetime.datetime(datetime.now().year, 12, 31) #дата нового года ct = datetime.datetime.now() #датавремя cd = datetime.datetime.now().strftime("%d/%m/%Y") #дата (д,м,г) ct1 = ct+datetime.timedelta(hours=15) # +14 часов от сервера