Compare commits

...

3 Commits
main ... main

Author SHA1 Message Date
RakVhalate
c3b6e56010 #5 old posts delete function 2024-01-23 06:33:53 +10:00
RakVhalate
150472a2de Deleter Temlpate 2024-01-22 05:16:36 +10:00
RakVhalate
10df69242d Some refactor 2024-01-21 17:00:25 +10:00
7 changed files with 250 additions and 148 deletions

18
DBChat/user_operations.py Normal file
View File

@ -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)

64
TopMsg/topdicks.py Normal file
View File

@ -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

34
dicktxt/change_words.py Normal file
View File

@ -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 = (
'<b>вырос</b>',
'<b>подрос</b>',
'<b>привстал</b>',
'<b>увеличился</b>',
'<b>преисполнился</b>'
)
dick_static = (
'<b>продвинулся</b>',
'<b>наноуменьшился</b>',
'<b>познал стабильность</b>',
'<b>зафиксировал прибыль</b>'
)
dick_decr = (
'<b>неудачно потусил на сходке</b>',
'<b>уменьшился</b>',
'<b>откусила злая гадюка</b>',
'<b>продали евреи, он стал дешевле</b>',
'<b>схуднул</b>'
'<b>отрицательно вырос</b>'
)
return size_change

View File

@ -1,4 +1,4 @@
Кожаный бабах
кожаный бабах
пистон
дуршлаг
елдак
@ -93,3 +93,4 @@
венерический суккуб
боец невидимого фронта
сморчок
джечник

View File

@ -1,12 +1,14 @@
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
from handlers import post_cleaner
#### https://docs.python-arango.com/en/main/
@ -27,60 +29,42 @@ async def up_dick(message: types.Message):
dicks_collection = pipisa_db.collection('dicks')
# рандомайзер
numb = randint(-9,10)
dick_plus = (
'<b>вырос</b>',
'<b>подрос</b>',
'<b>привстал</b>',
'<b>увеличился</b>',
'<b>преисполнился</b>'
)
dick_minus = (
'<b>неудачно потусил на сходке</b>',
'<b>уменьшился</b>',
'<b>откусила злая гадюка</b>',
'<b>продали евреи, он стал дешевле</b>',
'<b>схуднул</b>'
)
dick_stayed = (
'<b>продвинулся</b>',
'<b>наноуменьшился</b>',
'<b>зафиксировал прибыль</b>'
)
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) + ''
result = randint(-9,10) # главный рандомайзер
try: ## Тело метода прокрутки
try:
#### Чекнуть есть ли юзер в базе
candidate_cursor = dicks_collection.find(
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()):
# пришло время крутить!!
updetedDick = user["dick_size"] + numb
updetedDick = user["dick_size"] + result ## получение итогового результата
pipisa_word = ForReadDict.RandomDick()
change_word = change_words.ChangeWord(result)
enl_message = await bot.send_message(message.chat.id, f"@\
{message.from_user.username}, \
ваш <em>{pipisa_word}</em> ,{change_word(result)} на <b>{abs(result)}</b> см!\n\ \
Теперь он равен <b>{updetedDick}</b> см! ")
post_cleaner.cleanup_sequence(user['user_id'], enl_message.id, message.chat.id)
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,
@ -91,18 +75,15 @@ async def up_dick(message: types.Message):
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}, ваш <em>{randomword}</em> {size_change}\
на <b>{abs(numb)}</b> см!\n\
Теперь он равен <b>{updetedDick}</b> см! ')
print(update_err)
else:
await bot.send_message(message.chat.id, f'@{message.from_user.username},🚫 вы уже крутили пипису, ее размер <b>{user["dick_size"]}</b> см! ')
error_msg = await bot.send_message(message.chat.id, f'@\
{message.from_user.username},🚫 вы уже крутили пипису, \
ее размер <b>{user["dick_size"]}</b> см! ')
post_cleaner.cleanup_sequence(user['user_id'], error_msg.id, error_msg.chat.id)
try:
metadata = dicks_collection.insert(
@ -113,51 +94,38 @@ 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,
},
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: ## если пользователь не найден то создаём ему запись в БД
if result > 0:
new_reply = await bot.send_message(message.chat.id, f'@\
{message.from_user.username}, ваш писюн показал головку 🚀\n\
на <b>{abs(result)}</b> см!\n\
Теперь он равен <b>{result}</b> см!')
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\
на <b>{abs(numb)}</b> см!\n\
Теперь он равен <b>{numb}</b> см!')
else:
await bot.send_message(message.chat.id, f'@{message.from_user.username}, добро пожаловать в игру!🚀\n\
Ты стартуешь не с лучшей позиции, природа наградила тебя всего <b>{numb}</b> см 😬')
new_reply =await bot.send_message(message.chat.id, f'@\
{message.from_user.username}, добро пожаловать в игру!🚀\n\
Ты стартуешь не с лучшей позиции, природа наградила тебя всего <b>{result}</b> см 😬')
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 +134,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
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)

69
handlers/post_cleaner.py Normal file
View File

@ -0,0 +1,69 @@
import datetime
from arango import ArangoClient
from create_bot import bot
def get_remove_collection():
arango_client = ArangoClient(hosts=CONFIG['databaso']['host'] )
pipisa_db = arango_client.db(
CONFIG['databaso']['base'],
username=CONFIG['databaso']['user'],
password=CONFIG['databaso']['pass']
)
remove_collection = pipisa_db.collection(CONFIG['databaso']['deleteCollection'])
return remove_collection
async def cleanup_sequence(userID: int, messageID:int, chatID:int):
#remove last reply and check posts older than 5 minutes to delete
remove_collection = get_remove_collection
try:
clean_candidate = remove_collection.find(
{
'_key': userID,
'chat_id': chatID
},
skip=0, limit=1000)
prev_enl_message_id = clean_candidate["messageID"]
await bot.delete_message(prev_enl_message_id) #delete last reply to this user
current_time = datetime.datetime.now()
too_old = current_time-datetime.timedelta(min=5)
old_posts = remove_collection.find(
{
'chat_id': chatID,
},
skip=0, limit=1000)
for old_Post in old_posts:
if old_Post["datetimes"] <= too_old:
to_delete_ID = old_Post["messageID"]
to_delete_UserId = old_Post['_key']
await bot.delete_message(to_delete_ID) #delete old message
old_posts.delete(to_delete_UserId) #delete old message DB entry
except Exception as autoCleanErr:
print(autoCleanErr)
#write last reply post ID to db
remove_collection = get_remove_collection
message_time = datetime.datetime.now()
try:
lastReply = {
'_key': userID,
'datetimes': message_time,
'chat_id': chatID,
'messageID': messageID
}
metadata = remove_collection.insert(lastReply, overwrite_mode='update') #write last reply time
except Exception as lastWriteErr:
print(lastWriteErr)
return 0

View File

@ -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 часов от сервера