Compare commits

..

38 Commits
main ... main

Author SHA1 Message Date
9f7ae4b9a7 we r so fucking back
All checks were successful
continuous-integration/drone/push Build is passing
2024-08-11 01:07:53 +10:00
hogweed1
d41eeb3232 make pipisa secure
All checks were successful
continuous-integration/drone/push Build is passing
2024-07-03 17:38:45 +10:00
hogweed1
55e5303ab2 trying artifitial antitop !!
All checks were successful
continuous-integration/drone/push Build is passing
2024-06-29 01:51:07 +10:00
hogweed1
31235ef9ac trying artifitial antitop !
All checks were successful
continuous-integration/drone/push Build is passing
2024-06-29 01:47:23 +10:00
hogweed1
6709eebb88 trying artifitial antitop
All checks were successful
continuous-integration/drone/push Build is passing
2024-06-29 01:36:59 +10:00
Pavel_Durov
1533c5eb91 dsfs
All checks were successful
continuous-integration/drone/push Build is passing
2024-05-10 20:49:20 +03:00
Pavel_Durov
4c520b39fe asdadasdassa
All checks were successful
continuous-integration/drone/push Build is passing
2024-05-10 20:37:34 +03:00
Pavel_Durov
db842a1ceb eweww
All checks were successful
continuous-integration/drone/push Build is passing
2024-05-10 19:46:37 +03:00
Simple_Not
a571709afa #11 fixxxx scary bug
All checks were successful
continuous-integration/drone Build is passing
2024-03-19 14:12:14 +10:00
Pavel_Durov
192687a5ea теперь пипис у новеньких положительный
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-28 14:30:31 +03:00
Simple_Not
f20c90ea34 fx
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-28 14:14:41 +10:00
Pavel_Durov
1b2410afc4 только положительный пипис для новичков
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-28 14:04:58 +03:00
Simple_Not
56450bc566 fix пост-делишон
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-25 14:28:14 +10:00
Simple_Not
aa3ea439fe fix new yeatr
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-24 18:31:46 +10:00
Simple_Not
dae3f05aa7 fix new yeatr
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-24 17:54:54 +10:00
Simple_Not
66c2ef80c3 #10 теперь логгируется
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-24 14:09:31 +10:00
Simple_Not
4a3f799284 #5 another way
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-23 15:35:41 +10:00
Simple_Not
7090ab218e #5 fixxo
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-23 15:31:23 +10:00
Simple_Not
53bac66692 #5 fixxo
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-23 15:29:34 +10:00
Simple_Not
ee27dbfd7b #5 удаляем!
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-23 15:12:59 +10:00
Simple_Not
14c238ec2f меньше кода - лучше!
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-23 13:29:31 +10:00
Simple_Not
9d6d8791fd меньше кода - лучше!
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-23 13:23:04 +10:00
Simple_Not
d2b8c76817 меньше кода - лучше!
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-23 13:21:10 +10:00
Simple_Not
48d53fd1b9 меньше кода - лучше!
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-23 13:18:51 +10:00
Simple_Not
505d90aea8 меньше кода - лучше!
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-23 12:45:44 +10:00
Simple_Not
eb59091615 меньше кода - лучше!
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-23 02:26:29 +10:00
Simple_Not
c8a9936a00 меньше кода - лучше!
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-23 02:21:29 +10:00
Simple_Not
ecbe419abb меньше кода - лучше!
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-23 02:19:06 +10:00
Simple_Not
a58f6c404f меньше кода - лучше! 2024-01-23 02:18:50 +10:00
Simple_Not
e677591b97 фикс
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-22 03:26:08 +10:00
Simple_Not
c734044b71 фикс
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-22 02:59:48 +10:00
Simple_Not
e55b1c54d8 делаем интереснее
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-22 02:59:25 +10:00
Simple_Not
21bc3724c8 #9 fix
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-21 22:40:59 +10:00
Simple_Not
52f9edf9f4 #8 клинини
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-21 22:36:34 +10:00
Simple_Not
ef4c806071 #8 надеюсь не сломается
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-21 22:33:15 +10:00
Simple_Not
b188edd98d #7 убирац
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-21 22:02:22 +10:00
Simple_Not
bb91a90e9e #6 убирац
All checks were successful
continuous-integration/drone/push Build is passing
2024-01-21 21:55:47 +10:00
Simple_Not
d6da239718 #4 wow, we beccomin secure!
All checks were successful
continuous-integration/drone Build is passing
continuous-integration/drone/push Build is passing
2024-01-21 21:35:52 +10:00
26 changed files with 565 additions and 459 deletions

View File

@ -24,6 +24,11 @@ steps:
when: when:
branch: branch:
- main - main
environment:
ARANGO_PASSWORD:
from_secret: arango-pwd
ARANGO_USERNAME:
from_secret: arango-usr
- name: restart systemd unit - name: restart systemd unit
commands: commands:
- systemctl restart jack_bot - systemctl restart jack_bot

View File

@ -1,18 +0,0 @@
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)

View File

@ -1,64 +0,0 @@
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

38
bot.py
View File

@ -1,11 +1,40 @@
import logging import logging
from aiogram import executor from aiogram import executor, Bot, Dispatcher
from create_bot import dp from create_bot import dp
import handlers import handlers
import json, logging
from global_conf import CONFIG
def remake_field_generator(d, field='text'):
if isinstance(d, list):
for k2 in d:
for id_val in remake_field_generator(k2):
yield id_val
elif isinstance(d, dict):
for k, v in d.items():
if k == field:
d[k] = '<blank!>'
yield v
elif isinstance(v, list):
for k2 in v:
for id_val in remake_field_generator(k2):
yield id_val
elif isinstance(v, dict):
for id_val in remake_field_generator(v):
yield id_val
def filter_grammar_messages(record):
if record.args and (not None in record.args):
j = json.loads(record.args[2])
for _ in remake_field_generator(j):
pass
record.args = (record.args[0], record.args[1], json.dumps(j))
return True
logging.basicConfig(level=logging.DEBUG) logging.basicConfig(level=logging.DEBUG)
logging.getLogger("aiogram").addFilter(filter_grammar_messages)
# pipisa.register_handlers_pipisa(dp) # pipisa.register_handlers_pipisa(dp)
@ -13,9 +42,12 @@ logging.basicConfig(level=logging.DEBUG)
# sendalarm.register_handlers_test(dp) # sendalarm.register_handlers_test(dp)
# start_help.register_handlers_StartHelp(dp) # start_help.register_handlers_StartHelp(dp)
if __name__ == '__main__': if __name__ == '__main__':
#print(CONFIG)
logging.info('Бот в строю.')
executor.start_polling(dp, skip_updates=True) executor.start_polling(dp, skip_updates=True)
logging.info('Всем пока.')

19
config.yaml Normal file
View File

@ -0,0 +1,19 @@
---
databaso:
host: 'https://arango.guaranteedstruggle.host'
#user: root
#pass: stolendick527
base: pipisa
collection: dicks
posts_removal_collection: posts_removal
telegram_token: 6991523312:AAFpxPlWHfnNq2dVXM_v1GuHcrbNgWdSWBM
telegram_admins_ids:
- 317051301 # hogweed1
- 226765676 # blackjack
- 94830892 # viktorRMI
- 132002803
openai:
token: 5947963644:AAF_GKgMmU5ovqMpc1KXIpcf4aN0JMyKPqc
api_key: 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 ## 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

View File

@ -1,7 +1,8 @@
from aiogram import Bot, Dispatcher from aiogram import Bot, Dispatcher
from global_conf import CONFIG
API_TOKEN = '5724991559:AAEuLvpLsgP6LHRGMSyFtQLlR5qPQUO4b_w'
bot = Bot(token=API_TOKEN, parse_mode="HTML")
bot = Bot(token=CONFIG['telegram_token'], parse_mode="HTML")
dp = Dispatcher(bot) dp = Dispatcher(bot)

0
db_logic/__init__.py Normal file
View File

44
db_logic/collections.py Normal file
View File

@ -0,0 +1,44 @@
from global_conf import CONFIG
#### https://docs.python-arango.com/en/main/
from arango import ArangoClient
import logging
import os
def get_dicks_collection():
try:
arango_client = ArangoClient(hosts=CONFIG['databaso']['host'] )
pipisa_db = arango_client.db(
CONFIG['databaso']['base'],
username=os.environ['ARANGO_USR'],
password=os.environ['ARANGO_PWD'],
#username=CONFIG['databaso']['user'],
#password=CONFIG['databaso']['pass']
)
dicks_collection = pipisa_db.collection(CONFIG['databaso']['collection'])
return dicks_collection
except Exception as e:
logging.error('ошибка DB при взятии коллекции пипис')
logging.error(e)
def get_posts_removal_collection():
try:
arango_client = ArangoClient(hosts=CONFIG['databaso']['host'] )
pipisa_db = arango_client.db(
CONFIG['databaso']['base'],
username=os.environ['ARANGO_USR'],
password=os.environ['ARANGO_PWD'],
#username=CONFIG['databaso']['user'],
#password=CONFIG['databaso']['pass']
)
posts_removal_collection = pipisa_db.collection(CONFIG['databaso']['posts_removal_collection'])
return posts_removal_collection
except Exception as e:
logging.error('ошибка DB при взятии коллекции постов-на-удаление')
logging.error(e)

75
db_logic/postcleaner.py Normal file
View File

@ -0,0 +1,75 @@
from db_logic import collections
import datetime, logging
def append_post_to_cleaning_sequence(message, type=None):
try:
novenkiy = {
'msg_id': message.message_id,
'chat_id': message.chat.id,
'type': type,
'datetimes': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
metadata = collections.get_posts_removal_collection().insert(novenkiy, overwrite_mode='update')
logging.debug('Успешно добавлен пост на удаление')
except Exception as e2:
logging.error('ошибка DB :: добавление нового поста на удаление')
logging.error(e2)
def get_posts_to_be_removed(chat_id, type=None, max_id=None):
# собираем
try:
#posts = [p for p in collections.get_posts_removal_collection().all( ) ]
if type:
posts = [p for p in collections.get_posts_removal_collection().find({'chat_id': chat_id, 'type': type}, skip=0, limit=1100) ]
else:
posts = [p for p in collections.get_posts_removal_collection().find({'chat_id': chat_id}, skip=0, limit=1100) ]
posts_ret = [ p for p in posts ]
# # for p in posts:
# # last_time = datetime.datetime.strptime(p['datetimes'], '%Y-%m-%d %H:%M:%S')
# # timediff = (datetime.datetime.now() - last_time).total_seconds()
# # if timediff > 60:
# # posts_ret.append(p)
if max_id:
posts_ret = [ p for p in posts_ret if p['msg_id'] != max_id]
else:
posts_ret = [ p for p in posts_ret if p['msg_id'] != max([pp['msg_id'] for pp in posts_ret])]
#### TODO удалять все предыдущие без учёта времени
return posts_ret
except Exception as e:
logging.error('ошибка DB :: получение постов на удаление')
logging.error(e)
def del_post(msg_id, chat_id):
# удаляем из базы
try:
candidate_cursor = collections.get_posts_removal_collection().find(
{
'msg_id': msg_id,
'chat_id': chat_id,
},
skip = 0,
limit = 1488
)
if candidate_cursor.count() > 0:
pp = candidate_cursor.pop()
else:
pp = None
collections.get_posts_removal_collection().delete(pp)
except Exception as e:
logging.error('ошибка DB :: удаление поста на удаление')
logging.error(e)

65
db_logic/tops.py Normal file
View File

@ -0,0 +1,65 @@
from global_conf import CONFIG
from db_logic import collections
import logging
def get_tops(top_ = False, glob_ = False, chat_id = None):
if top_:
try:
dicks = [d for d in collections.get_dicks_collection().find({'chat_id': chat_id}, skip=0, limit=1100)]
except Exception as e:
logging.error('ошибка DB в /topdick')
logging.error(e)
elif glob_:
try:
dicks = [d for d in collections.get_dicks_collection().all( ) if d['user_id'] != d['chat_id']]
except Exception as e:
logging.error('ошибка DB в /globaldick')
logging.error(e)
else:
logging.error('вызывают хз что!')
top_dicks = sorted(dicks, key=lambda dick: dick['dick_size'], reverse=True)
top_dicks = top_dicks[:( min(len(top_dicks), 10) )]
dickos = ''
emo = ['🏆','🚀','🍆','🍌','🐍','🐎','🌭','🌶','👌','💩']
if len(top_dicks) > 0:
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
return dickos
def get_antitops(top_ = False, glob_ = False, chat_id = None):
dicks = []
if top_:
try:
dicks = [d for d in collections.get_dicks_collection().find({'chat_id': chat_id}, skip=0, limit=1100)]
except Exception as e:
logging.error('ошибка DB в /topdick')
logging.error(e)
elif glob_:
try:
dicks = [d for d in collections.get_dicks_collection().all() if d['user_id'] != d['chat_id']]
except Exception as e:
logging.error('ошибка DB в /globaldick')
logging.error(e)
else:
logging.error('вызывают хз что!')
antitop_dicks = sorted(dicks, key=lambda dick: dick['dick_size'], reverse=False)
antitop_dicks = antitop_dicks[:( min(len(antitop_dicks), 10) )]
dickos = ''
emo = ['💩', '😞', '🤕', '😣', '🙁', '😐', '😑', '😶', '😒', '😕']
if len(antitop_dicks) > 0:
for i in range(len(antitop_dicks)):
dickos += f' {emo[i]} {i+1}. {antitop_dicks[i]["user_fullname"]}: {antitop_dicks[i]["dick_size"]}см\n'
i += 1
return dickos

86
db_logic/user_stuff.py Normal file
View File

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

View File

@ -8,9 +8,5 @@ def RandomDick():
with open('dicktxt/dick_sinonims.txt', 'r', encoding='utf-8') as file: with open('dicktxt/dick_sinonims.txt', 'r', encoding='utf-8') as file:
words = file.readlines() words = file.readlines()
random_line = random.choice(words).strip() return random.choice(words).strip()
return random_line

21
dicktxt/WordsChange.py Normal file
View File

@ -0,0 +1,21 @@
import yaml
import random
def ChangeWord(result): #выбирает рандомное слово для изменения размера пиписы
with open("dicktxt/dick_changes.yaml", 'r', encoding='utf-8') as f:
words = yaml.load(f, Loader=yaml.Loader)
dick_inc = [ f'<b>{w}</b>' for w in words['increment'] ]
dick_static = [ f'<b>{w}</b>' for w in words['nothing'] ]
dick_decr = [ f'<b>{w}</b>' for w in words['decrement'] ]
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) + ''
return size_change

View File

@ -1,34 +0,0 @@
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

30
dicktxt/dick_changes.yaml Normal file
View File

@ -0,0 +1,30 @@
---
increment:
- вырос
- подрос
- привстал
- увеличился
- преисполнился
- приподнялся
- изменил размер
- облагородился
- чрезвычайно преуспел
decrement:
- неудачно потусил на сходке
- уменьшился
- откусила злая гадюка
- продали евреи, он стал дешевле
- схуднул
- отрицательно вырос
- словил низкие вибрации
- повредился после простуды
- стал жертвой репрессий
- был подло использован
nothing:
- продвинулся
- наноуменьшился
- познал стабильность
- зафиксировал прибыль
- подумал о судьбах Китая
- прогулялся по лесу
- самоутвердился

6
global_conf.py Normal file
View File

@ -0,0 +1,6 @@
import yaml
with open("config.yaml", 'r') as f:
CONFIG = yaml.load(f, Loader=yaml.Loader)

View File

@ -3,6 +3,4 @@ from handlers import pipisa
from handlers import start_help from handlers import start_help
from handlers import time_new_year from handlers import time_new_year
from handlers import sendalarm
from handlers import davinci

View File

@ -1,73 +1,64 @@
import openai from openai import AsyncOpenAI
from aiogram import types, Dispatcher from aiogram import types
from create_bot import dp, bot from create_bot import dp, bot
import logging import logging
from global_conf import CONFIG
admins = CONFIG['telegram_admins_ids']
token = '5947963644:AAF_GKgMmU5ovqMpc1KXIpcf4aN0JMyKPqc' ban_comands = ['/dick','/topdick']
#openai.api_key = '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'
openai.api_key = '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'
ban_comands = ['/dick','/topdick']
# Image_promt =['тупица сгенерируй','тупица сгенерируй картинку',\ # Image_promt =['тупица сгенерируй','тупица сгенерируй картинку',\
# 'тупица отправь картинку', 'тупица отправь картинку'] # 'тупица отправь картинку', 'тупица отправь картинку']
client = AsyncOpenAI(api_key="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")
# @dp.message_handler(commands=['image'])
# async def send_image(message: types.Message):
# if message.from_user.id in admins and message.chat.type == 'private':
# try:
# description = message.text.replace('/image', '').strip()
# if not description:
# await message.reply('Ты даун, описание запроса напиши после пробела')
# return
# except Exception as e:
# logging.error(f'Error in send_image: {e}')
# try:
# response = openai.Image.create(
# prompt=message.text,
# n=1,
# size="1024x1024",
# response_format="url",
# )
# image_url = response['data'][0]['url']
# await message.answer('Генерирую изображение...')
# await message.reply_photo(image_url)
# except Exception as e:
# await message.reply('у меня не получилось')
@dp.message_handler(commands=['image']) async def gpt_text(req):
async def send_image(message: types.Message): completion = await client.chat.completions.create(
try: messages=[
description = message.text.replace('/image', '').strip() {
"role": "user",
if not description: "content": req,
await message.reply('Ты даун, описание запроса напиши после пробела') }
return ],
except Exception as e: model="gpt-4",
logging.error(f'Error in send_image: {e}')
try:
response = openai.Image.create(
prompt=message.text,
n=1,
size="1024x1024",
response_format="url",
) )
image_url = response['data'][0]['url'] return completion
await message.answer('Генерирую изображение...')
await message.reply_photo(image_url)
except Exception as e:
await message.reply('у меня не получилось')
@dp.message_handler() @dp.message_handler()
async def send(message: types.Message): async def send(message: types.Message):
if message.text.lower().startswith('тупица'): if message.from_user.id in admins and message.chat.type == 'private':
response = await gpt_text(message.text)
## TODO уточнить остатки токенов и денег await message.answer(response.choices[0].message.content)
response = openai.Completion.create(
model="text-davinci-003",
prompt=message.text[7:],
temperature=0.7,
max_tokens=1000,
top_p=1.0,
frequency_penalty=0.0,
presence_penalty=0.6,
stop=["сброс"]
)
await message.reply(response['choices'][0]['text'])
elif message.reply_to_message.from_user.is_bot:
response = openai.Completion.create(
model="text-davinci-003",
prompt=message.text,
temperature=0.7,
max_tokens=1000,
top_p=1.0,
frequency_penalty=0.0,
presence_penalty=0.6,
stop=["сброс"]
)
await message.reply(response['choices'][0]['text'])

View File

@ -1,155 +1,146 @@
from aiogram import types, Dispatcher from aiogram import types
from create_bot import bot, dp from create_bot import bot, dp
import random import random
from random import randint from random import randint
import datetime import datetime, logging
from dicktxt import ForReadDict from dicktxt import ForReadDict, WordsChange
from dicktxt import change_words
from pipisa_functions import pipisa_time from pipisa_functions import pipisa_time
from DBChat import user_operations
from TopMsg import topdicks from global_conf import CONFIG
from handlers import post_cleaner
from db_logic import tops, user_stuff, postcleaner
#### https://docs.python-arango.com/en/main/ admins = CONFIG['telegram_admins_ids']
from arango import ArangoClient
admins = [317051301, 226765676]
@dp.message_handler(commands=["dick"]) @dp.message_handler(commands=["dick"])
async def up_dick(message: types.Message): async def up_dick(message: types.Message):
#global size_change, dick_plus, dick_minus
if message.from_user.id in admins or message.chat.type != 'private': if message.from_user.id in admins or message.chat.type != 'private':
arango_client = ArangoClient(hosts='https://arango.guaranteedstruggle.host') postcleaner.append_post_to_cleaning_sequence(message=message, type=f'COMMAND_CALL__DICK')
pipisa_db = arango_client.db('pipisa', username='root', password='stolendick527') await clean_posts(chat_id=message.chat.id, type='COMMAND_CALL__DICK', max_id=message.message_id)
dicks_collection = pipisa_db.collection('dicks')
#### TODO уплатить нолог с 100 см для самого нищего
# рандомайзер
result = randint(-9,10)
result = randint(-9,10) # главный рандомайзер #### Чекнуть есть ли юзер в базе
user = user_stuff.get_user(message)
try: ## Тело метода прокрутки if user:
## Если есть то нарастить и отправить сообщение
candidate_cursor = dicks_collection.find( ## Проверить наличие пользователя в базе if pipisa_time.rolltime(check_datetime=user['datetimes'], curr_time=datetime.datetime.now()):
{ # пришло время крутить!!
'user_id': message.from_user.id,
'chat_id': message.chat.id
},
skip=0, limit=1488)
if candidate_cursor.count() > 0: ## Если пользователь есть то нарастить и отправить сообщение updatedDick = user["dick_size"] + result
user_stuff.update_dick_size(message, user, updatedDick)
user = candidate_cursor.pop() randomdickword = ForReadDict.RandomDick()
change_phrase = WordsChange.ChangeWord(result)
if pipisa_time.rolltime(check_datetime=user['datetimes'], curr_time=datetime.datetime.now()): await bot.send_message( message.chat.id,
f'@{message.from_user.username}, ваш <em>{randomdickword}</em> {change_phrase} на <b>{abs(result)}</b> см!\nТеперь он равен <b>{updatedDick}</b> см! '
)
else:
mmm = await bot.send_message( message.chat.id,
f'@{message.from_user.username}, 🚫 вы уже крутили пипису, её размер <b>{user["dick_size"]}</b> см! '
)
user_stuff.update_attempts( message, user)
updetedDick = user["dick_size"] + result ## получение итогового результата postcleaner.append_post_to_cleaning_sequence(message=mmm, type='ALREADY_ROLLED')
await clean_posts(chat_id=mmm.chat.id, type='ALREADY_ROLLED', max_id=mmm.message_id)
else:
## если нету, то создать
user_stuff.store_new_user(message, result)
pipisa_word = ForReadDict.RandomDick() await bot.send_message( message.chat.id,
change_word = change_words.ChangeWord(result) f'@{message.from_user.username}, Добро пожаловать в игру! Ваш писюн показал головку 🚀\nна <b>{abs(result)}</b> см!\nТеперь он равен <b>{abs(result)}</b> см!'
)
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'], ## этот нужен чтобы апдейт прилетал тому же юзеру
'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 update_err:
print(f'ошибка в обновлении пиписы @{message.from_user.username}')
print(update_err)
else:
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(
{
'_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 roll_err:
print(f'ошибка в обновлении попытки крутить пипису @{message.from_user.username}')
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:
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 crit_err:
print('ошибка DB в /dick')
print(crit_err)
else: else:
await message.reply('Растить елду можно только в общих чатах!') await message.reply('Растить елду можно только в общих чатах!')
@dp.message_handler(commands = ['topdick', 'globaldick'])
async def send_topchat(message: types.Message):
@dp.message_handler(commands=["topdick"])
async def send_topchat(message: types.Message): # тело метода лучших результатов отдельной конфы
if message.from_user.id in admins or message.chat.type != 'private': if message.from_user.id in admins or message.chat.type != 'private':
dickos = topdicks.topdicks_conf(message.chat.id) top_ = message['text'].startswith('/topdick')
await bot.send_message(message.chat.id, '🏆Топ 10 бубылд чата🏆\n\n' + dickos) glob_ = message['text'].startswith('/globaldick')
if top_:
dickos = tops.get_tops( top_ = True, chat_id=message.chat.id )
postcleaner.append_post_to_cleaning_sequence(message=message, type=f'COMMAND_CALL__TOPDICK')
await clean_posts(chat_id=message.chat.id, type='COMMAND_CALL__TOPDICK', max_id=message.message_id)
elif glob_:
dickos = tops.get_tops( glob_ = True )
postcleaner.append_post_to_cleaning_sequence(message=message, type=f'COMMAND_CALL__GLOBALDICK')
await clean_posts(chat_id=message.chat.id, type='COMMAND_CALL__GLOBALDICK', max_id=message.message_id)
else:
logging.error('вызывают хз что!')
if not dickos:
await bot.send_message(message.chat.id, '🍆 Никто ничего не нарастил! 🍌')
else:
if top_:
await bot.send_message(message.chat.id, '🏆Топ 10 бубылд чата🏆\n\n' + dickos)
elif glob_:
await bot.send_message(message.chat.id, '🏆Топ 10 пипис в мире🏆\n\n' + dickos)
else: else:
await message.reply('Работает только в общих чатах!\n'\ await message.reply('Работает только в общих чатах!\n'\
'Вы мсжете посмотреть топ по миру: /globaldick') 'Вы можете посмотреть топ по миру /globaldick')
@dp.message_handler(commands = ['antitopdick', 'antiglobaldick'])
async def send_antitopchat(message: types.Message):
if message.from_user.id in admins or message.chat.type != 'private':
antitop_ = message['text'].startswith('/antitopdick')
antiglob_ = message['text'].startswith('/antiglobaldick')
if antitop_:
dickos = tops.get_antitops(top_=True, chat_id=message.chat.id)
postcleaner.append_post_to_cleaning_sequence(message=message, type=f'COMMAND_CALL__ANTITOPDICK')
await clean_posts(chat_id=message.chat.id, type='COMMAND_CALL__ANTITOPDICK', max_id=message.message_id)
elif antiglob_:
dickos = tops.get_antitops(glob_=True)
postcleaner.append_post_to_cleaning_sequence(message=message, type=f'COMMAND_CALL__ANTIGLOBALDICK')
await clean_posts(chat_id=message.chat.id, type='COMMAND_CALL__ANTIGLOBALDICK', max_id=message.message_id)
else:
logging.error('вызывают хз что!')
if not dickos:
await bot.send_message(message.chat.id, '🍌 У всех пользователей бубылда растёт! 🍆')
else:
if antitop_:
await bot.send_message(message.chat.id, '🚫Антитоп 10 вагись чата🚫\n\n' + dickos)
elif antiglob_:
await bot.send_message(message.chat.id, '🚫Антитоп 10 вагись в мире🚫\n\n' + dickos)
else:
await message.reply('Работает только в общих чатах!\n'\
'Вы можете посмотреть антитоп по миру /antiglobaldick')
async def clean_posts(chat_id, type=None, max_id=None):
psts = postcleaner.get_posts_to_be_removed(chat_id, type, max_id)
@dp.message_handler(commands=["globaldick"]) for p in psts:
async def send_global_top(message: types.Message): # тело метода лучших результатов postcleaner.del_post(chat_id=p['chat_id'], msg_id=p['msg_id'])
tops = topdicks.topdicks_global(message.chat.id,)
await bot.send_message(message.chat.id, '🏆Топ 10 пипис в мире🏆\n\n' + tops) #### TODO проверить админит ли бот
try:
await bot.delete_message( chat_id=p['chat_id'], message_id=p['msg_id'], )
except Exception as e:
logging.error('ошибка удаления поста-на-удаление')
logging.error(e)

View File

@ -1,69 +0,0 @@
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

@ -1,29 +0,0 @@
from create_bot import dp, bot
from aiogram import types, Dispatcher
from sqdb import user, session
@dp.message_handler(commands=['sendall'])
async def sendall(message: types.Message):
print('команда прошла')
if message.chat.type == 'private':
if message.from_user.id == 226765676:
text = message.text[9:]
try:
chats_id = -1001355646177
try:
await bot.send_message(chats_id, text)
except:
print('вероятно бота нет в чате')
await bot.send_message(message.from_user.id, 'Сообщение успешно отправлено во все чаты')
except:
session.rollback()
print('eror sendall')
finally: session.close_all()
# def register_handlers_test(dp: Dispatcher):
# dp.register_message_handler(send_welcome)

View File

@ -1,4 +1,4 @@
from aiogram import types, Dispatcher from aiogram import types
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from create_bot import dp, bot from create_bot import dp, bot

View File

@ -4,10 +4,10 @@ import datetime
@dp.message_handler(commands=["time"]) @dp.message_handler(commands=["time"])
async def send_time(message: types.Message): async def send_time(message: types.Message):
new_year = datetime.datetime(datetime.now().year, 12, 31) #дата нового года new_year = datetime.datetime(datetime.datetime.now().year, 12, 31) #дата нового года
ct = datetime.datetime.now() #датавремя ct = datetime.datetime.now() #датавремя
cd = datetime.datetime.now().strftime("%d/%m/%Y") #дата (д,м,г) cd = datetime.datetime.now().strftime("%d/%m/%Y") #дата (д,м,г)
ct1 = ct+datetime.timedelta(hours=15) # +14 часов от сервера ct1 = ct # zoichem??? +datetime.timedelta(hours=15) # +14 часов от сервера
ct2 = ct1.strftime('%H:%M') # форматирует датувремя просто во время(ч,м) ct2 = ct1.strftime('%H:%M') # форматирует датувремя просто во время(ч,м)
raznitsa = (new_year - ct).days #отнимает от нг текущее время и получаем разницу в днях raznitsa = (new_year - ct).days #отнимает от нг текущее время и получаем разницу в днях

15
jack_bot.service Normal file
View File

@ -0,0 +1,15 @@
# пример того что лежит на хосте
[Unit]
Description=pipisa-bot
After=network.target
[Service]
User=jack
Type=simple
Restart=always
WorkingDirectory=/usr/share/python_bot
ExecStart=/usr/bin/python3 /usr/share/python_bot/bot.py
ExecStart=/usr/bin/python3 /usr/share/python_bot/bot.py
[Install]
WantedBy=multi-user.target#

View File

@ -1,2 +1,3 @@
aiogram aiogram==2.15
python-arango python-arango
pyyaml

56
sqdb.py
View File

@ -1,56 +0,0 @@
from sqlalchemy import create_engine, MetaData, Table, Integer, String, BIGINT, \
Column, DateTime, ForeignKey, Numeric
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import select, update
engine = create_engine('postgresql+psycopg2://postgres:postgres@postgres.vdk2ch.ru:5432/jack_bot', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class user(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
user_id = Column(Integer)
user_fullname = Column(String)
dick_size = (Column(Integer))
datetimes = (Column(DateTime))
chat_id = Column(BIGINT)
session.close()
engine.dispose()
# top = session.query(user.user_fullname, user.dick_size).order_by(user.dick_size.desc()).filter(user.chat_id == user.chat_id).limit(10).all()
# print(top)
#Base.metadata.create_all(engine)
# int_table = user(user_id = 12345678, user_fullname = 'test', dick_size = 10) #импортирую юзер из sqdb
# session.add(int_table)
# session.commit()
# select user_id, name from employees limit 10
# def adding():
# session.add()
# session.commit()