меньше кода - лучше!
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Simple_Not 2024-01-23 13:18:51 +10:00
parent 505d90aea8
commit 48d53fd1b9
2 changed files with 127 additions and 95 deletions

86
db_logic/user_stuff.py Normal file
View File

@ -0,0 +1,86 @@
from global_conf import CONFIG
from db_logic import collections
import datetime
def store_new_user(dicks_collection, message, result ):
try:
novenkiy = {
'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
}
metadata = dicks_collection.insert(novenkiy, overwrite_mode='update')
print(f'Успешно добавлен нового пользователь @{message.from_user.username}')
except Exception as e2:
print(f'ошибка DB в /dick :: добавление нового пользователя @{message.from_user.username}')
print(e2)
def update_attempts(dicks_collection, message, user ):
try:
metadata = dicks_collection.insert(
{
'_key': user['_key'], ### этот нужен чтобы апдейт прилетал тому же юзеру
'user_id': user['user_id'] ,
'user_fullname': message.from_user.full_name,
'dick_size': user['dick_size'] ,
'datetimes': user['datetimes'] ,
'attempts': user['attempts'] + 1,
'chat_id': message.chat.id
},
overwrite_mode='update'
)
print(f'Успешно апдейтнули попытку крутить пипису @{message.from_user.username}')
except Exception as e2:
print(f'ошибка DB в /dick :: обновление попытки крутить пипису @{message.from_user.username}')
print(e2)
def update_dick_size(dicks_collection, message, user, updatedDick ):
try:
metadata = dicks_collection.insert(
{
'_key': user['_key'], ### этот нужен чтобы апдейт прилетал тому же юзеру
'user_id': user['user_id'],
'user_fullname': message.from_user.full_name,
'dick_size': updatedDick,
'datetimes': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
'attempts': user['attempts'] + 1,
'chat_id': message.chat.id
},
overwrite_mode='update'
)
print(f'Успешно апдейтнули пипису @{message.from_user.username}')
except Exception as e2:
print(f'ошибка DB в /dick :: обновление пиписы @{message.from_user.username}')
print(e2)
def get_user(dicks_collection, message):
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:
user = candidate_cursor.pop()
else:
user = None
return user
except Exception as e:
print('ошибка DB в /dick :: поиск юзера')
print(e)

View File

@ -8,8 +8,7 @@ from pipisa_functions import pipisa_time
from global_conf import CONFIG from global_conf import CONFIG
from db_logic import tops from db_logic import collections, tops, user_stuff
from db_logic import collections
admins = CONFIG['telegram_admins_ids'] admins = CONFIG['telegram_admins_ids']
@ -28,86 +27,37 @@ async def up_dick(message: types.Message):
# рандомайзер # рандомайзер
result = randint(-9,10) result = randint(-9,10)
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: #### Чекнуть есть ли юзер в базе
user = user_stuff.get_user(dicks_collection, message)
if user:
## Если есть то нарастить и отправить сообщение ## Если есть то нарастить и отправить сообщение
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"] + result updatedDick = user["dick_size"] + result
try: user_stuff.store_new_user(dicks_collection, message, user, updatedDick)
metadata = dicks_collection.insert(
{
'_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
},
overwrite_mode='update'
)
print(f'Успешно апдейтнули пипису @{message.from_user.username}')
except Exception as e2:
print(f'ошибка в обновлении пиписы @{message.from_user.username}')
print(e2)
randomword = ForReadDict.RandomDick() randomword = ForReadDict.RandomDick()
change_phrase = WordsChange.ChangeWord(result) change_phrase = WordsChange.ChangeWord(result)
await bot.send_message( message.chat.id, await bot.send_message( message.chat.id,
f'@{message.from_user.username}, ваш <em>{randomword}</em> {change_phrase} на <b>{abs(result)}</b> см!\nТеперь он равен <b>{updetedDick}</b> см! ' f'@{message.from_user.username}, ваш <em>{randomword}</em> {change_phrase} на <b>{abs(result)}</b> см!\nТеперь он равен <b>{updatedDick}</b> см! '
) )
else: else:
await bot.send_message( message.chat.id, await bot.send_message( message.chat.id,
f'@{message.from_user.username}, 🚫 вы уже крутили пипису, ее размер <b>{user["dick_size"]}</b> см! ' f'@{message.from_user.username}, 🚫 вы уже крутили пипису, ее размер <b>{user["dick_size"]}</b> см! '
) )
try: user_stuff.update_attempts(dicks_collection, message, user)
metadata = dicks_collection.insert(
{
'_key': user['_key'], ### этот нужен чтобы апдейт прилетал тому же юзеру
'user_id': user['user_id'] ,
'user_fullname': message.from_user.full_name,
'dick_size': user['dick_size'] ,
'datetimes': user['datetimes'] ,
'attempts': user['attempts'] + 1,
'chat_id': message.chat.id
},
overwrite_mode='update'
)
print(f'Успешно апдейтнули попытку крутить пипису @{message.from_user.username}')
except Exception as e2:
print(f'ошибка в обновлении попытки крутить пипису @{message.from_user.username}')
print(e2)
print(f'пользователь @{message.from_user.username} уже крутил') print(f'пользователь @{message.from_user.username} уже крутил')
else: else:
## если нету, то создать ## если нету, то создать
user_stuff.store_new_user(dicks_collection, message, result)
try:
novenkiy = {
'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
}
metadata = dicks_collection.insert(novenkiy, overwrite_mode='update')
if result > 0: if result > 0:
await bot.send_message( message.chat.id, await bot.send_message( message.chat.id,
@ -118,14 +68,10 @@ async def up_dick(message: types.Message):
f'@{message.from_user.username}, добро пожаловать в игру!🚀\nТы стартуешь не с лучшей позиции, природа наградила тебя всего <b>{result}</b> см 😬' f'@{message.from_user.username}, добро пожаловать в игру!🚀\nТы стартуешь не с лучшей позиции, природа наградила тебя всего <b>{result}</b> см 😬'
) )
print(f'Успешно добавлен пользователь @{message.from_user.username}')
except Exception as e1:
print('ошибка в добавлении нового пользователя')
print(e1)
except Exception as e: # except Exception as e:
print('ошибка DB в /dick') # print('ошибка DB в /dick')
print(e) # print(e)
#### для всех отложенных сообщений #### для всех отложенных сообщений
## проверить если прошло ?пять минут? с публикации ## проверить если прошло ?пять минут? с публикации
@ -144,9 +90,9 @@ async def send_topchat(message: types.Message):
glob_ = message['text'].startswith('/globaldick') glob_ = message['text'].startswith('/globaldick')
if top_: if top_:
dickos = tops.get_tops( top_=True, chat_id=message.chat.id ) dickos = tops.get_tops( top_ = True, chat_id=message.chat.id )
elif glob_: elif glob_:
dickos = tops.get_tops( glob_=True ) dickos = tops.get_tops( glob_ = True )
else: else:
print('вызывают хз что!') print('вызывают хз что!')