отпилен хуй от пользователей, вынесен в автономию

This commit is contained in:
hopelessjames 2023-06-20 13:21:28 +10:00
parent da06b5ad23
commit 33418e0c8b
8 changed files with 113 additions and 84 deletions

8
bot.py
View File

@ -12,8 +12,8 @@ logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(
level = logging.DEBUG,
handlers = [ graypy.GELFUDPHandler('localhost', 12201) ]
level=logging.DEBUG,
handlers=[graypy.GELFUDPHandler('localhost', 12201)]
)
# pipisa.register_handlers_pipisa(dp)
@ -25,7 +25,3 @@ logging.basicConfig(
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)

View File

@ -1,23 +1,24 @@
import openai
from aiogram import types, Dispatcher
from create_bot import dp, bot
from aiogram import types
from create_bot import dp
token = '5947963644:AAF_GKgMmU5ovqMpc1KXIpcf4aN0JMyKPqc'
openai.api_key = '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'
@dp.message_handler()
async def send(message: types.Message):
if 'тупица' in message.text.lower():
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=["сброс"]
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'])

View File

@ -1,7 +1,7 @@
from aiogram import types, Dispatcher
from aiogram import types
from sqlalchemy.orm.session import close_all_sessions
from create_bot import bot, dp
from sqdb import user, session, DickRequest
from sqdb import User, session, DickRequest, UserDick
import random
import traceback
from random import randint
@ -13,6 +13,10 @@ dick_plus = None
dick_minus = None
def get_dick(user_id, chat_id):
dick = session.query(UserDick).filter(UserDick.user_id == user_id, UserDick.chat_id == chat_id).first()
return dick
def top_dick_message(delimiter, top_list):
message = f'🏆Топ 10 бубылд чата🏆\n\n'
f'🚀 {delimiter.join(map(str, top_list[0]))}\n'
@ -28,10 +32,12 @@ def top_dick_message(delimiter, top_list):
return message
@dp.message_handler(commands=["maintainance"])
@dp.message_handler(commands=["maintenance"])
async def stop_for_maintenance(message: types.Message): # остановить бота
if message.from_user.id == 226765676:
close_all_sessions() # TODO Вспомнить, как это, блять, делается.
bot.send_message(message.from_user.id, "Блять. Как же больно. Мне холодно. Наверное это конец...")
close_all_sessions()
dp.stop_polling()
@dp.message_handler(commands=["dick"])
@ -51,7 +57,7 @@ async def up_dick(message: types.Message): # рандомайзер
# работа с таблицей
try:
dick_request = DickRequest(size_change=numb, date_changed=datetime.datetime.now())
b = session.query(user).filter(user.user_id == message.from_user.id).first()
b = session.query(User).filter(User.user_id == message.from_user.id).first()
if b:
last_time = b.date_updated
now_time = datetime.datetime.now()
@ -72,9 +78,10 @@ async def up_dick(message: types.Message): # рандомайзер
else:
try:
usr = session.query(user)
a = usr.filter(user.user_id == message.from_user.id).first() # запрос на поиск в таблице
updated_dick = a.dick_size = (a.dick_size + numb)
usr = session.query(User)
a = usr.filter(User.user_id == message.from_user.id).first() # запрос на поиск в таблице
dick = get_dick(User.user_id, message.chat.id)
updated_dick = dick.dick_size = (dick.dick_size + numb)
dick_request.user = a
a.date_updated = datetime.datetime.now()
session.add(dick_request)
@ -97,15 +104,17 @@ async def up_dick(message: types.Message): # рандомайзер
else:
session.close()
try:
int_table = user(user_id=message.from_user.id,
int_table = User(user_id=message.from_user.id,
user_fullname=message.from_user.full_name,
dick_size=numb,
date_updated=datetime.datetime.now(),
date_created=datetime.datetime.now(),
chat_id=message.chat.id)
date_created=datetime.datetime.now())
new_dick = DickRequest(user_id=message.from_user.id,
chat_id=message.chat.id,
dick_size=numb)
dick_request.user = int_table
session.add(int_table)
session.add(new_dick)
session.add(dick_request)
session.flush()
session.commit()
@ -130,26 +139,27 @@ async def up_dick(message: types.Message): # рандомайзер
@dp.message_handler(commands=["topdick"])
async def send_topchat(message: types.Message):
async def send_top_chat(message: types.Message):
try:
changechat_id = session.query(user).filter(user.user_id == message.from_user.id).first()
delimiter = ': '
top = []
chats = message.chat.id
if changechat_id.chat_id != chats:
changechat_id.chat_id = chats
session.commit()
session.close()
else:
session.close()
users = session.query(user.user_fullname, user.dick_size).order_by(user.dick_size.desc())
top = users.filter(user.chat_id == chats).limit(10).all()
changechat_id = session.query(DickRequest).filter(DickRequest.user_id == message.from_user.id,
DickRequest.chat_id == chats).first()
dicks = session.query(DickRequest)\
.filter(DickRequest.chat_id == chats)\
.limit(10).all()\
.order_by(DickRequest.dick_size.desc())
for dick in dicks:
user = session.query(User.user_fullname).filter(User.user_id == dick.user_id)
top.append([user.full_name, dick.dick_size])
delimiter = ': '
# проверка на длину списка, если меньше limit, то:
size_len = len(top)
if size_len < 10:
len_minus = 10 - size_len
top.extend(('-'*len_minus))
top.extend([('-'*len_minus),""])
await bot.send_message(message.chat.id, top_dick_message(delimiter, top))
session.close()
# если все нормально и участников минимум 10
@ -167,11 +177,16 @@ async def send_topchat(message: types.Message):
@dp.message_handler(commands=["globaldick"])
async def send_global_top(message: types.Message):
try:
top_chat = session.query(user.user_fullname, user.dick_size).order_by(user.dick_size.desc()).limit(10).all()
top = []
dicks = session.query(DickRequest) \
.limit(10).all() \
.order_by(DickRequest.dick_size.desc())
for dick in dicks:
user = session.query(User.user_fullname).filter(User.user_id == dick.user_id)
top.append([user.full_name, dick.dick_size])
delimiter = ': '
await bot.send_message(message.chat.id, top_dick_message(delimiter, top_chat))
await bot.send_message(message.chat.id, top_dick_message(delimiter, top))
except Exception as e:
session.rollback()
print('ошибка в /globaldick, трейсбэк:\n' + '\n'.join(traceback.format_tb(e.__traceback__)))

View File

@ -1,8 +1,8 @@
import traceback
from create_bot import dp, bot
from aiogram import types, Dispatcher
from sqdb import user, session
from sqdb import User, session
@dp.message_handler(commands=['sendall'])
@ -12,17 +12,20 @@ async def sendall(message: types.Message):
if message.from_user.id == 226765676:
text = message.text[9:]
try:
chats_id = session.query(user.chat_id).distinct()
chats_id = session.query(User.chat_id).distinct()
for row in chats_id:
try:
await bot.send_message(row[0], text)
except:
print('вероятно бота нет в чате')
except Exception as e:
print('вероятно бота нет в чате, на всякий случай трейсбек:\n' +
"\n".join(traceback.format_tb(e.__traceback__)))
await bot.send_message(message.from_user.id, 'Сообщение успешно отправлено во все чаты')
except:
except Exception as e:
session.rollback()
print('eror sendall')
finally: session.close_all()
print('error sendall, traceback:\n' +
"\n".join(traceback.format_tb(e.__traceback__)))
finally:
session.close_all()
# def register_handlers_test(dp: Dispatcher):

View File

@ -1,22 +1,28 @@
from aiogram import types, Dispatcher
from aiogram import types
from create_bot import dp, bot
@dp.message_handler(commands=['start'])
async def start_func(message: types.Message):
await message.reply('похуй')
@dp.message_handler(commands=['photo'])
async def send_image(message: types.Message):
await bot.send_photo(message.chat.id, photo='https://memepedia.ru/wp-content/uploads/2018/08/ya-pidoras.jpg', reply_to_message_id=message.message_id)
await bot.send_photo(message.chat.id,
photo='https://memepedia.ru/wp-content/uploads/2018/08/ya-pidoras.jpg',
reply_to_message_id=message.message_id)
@dp.message_handler(content_types=types.ContentTypes.TEXT)
async def send_faggot(message: types.Message):
print(message.text)
if message.text == 'хто я':
await bot.send_photo(message.chat.id, photo='https://www.meme-arsenal.com/memes/ecebd2339c7eab40e09874bd86a38a09.jpg')
await bot.send_photo(message.chat.id,
photo='https://www.meme-arsenal.com/memes/ecebd2339c7eab40e09874bd86a38a09.jpg')
def register_handlers_StartHelp(dp: Dispatcher):
dp.register_message_handler(start_func)
dp.register_message_handler(send_faggot)
dp.register_message_handler(send_image)
# def register_handlers_StartHelp(dp: Dispatcher):
# dp.register_message_handler(start_func)
# dp.register_message_handler(send_faggot)
# dp.register_message_handler(send_image)

View File

@ -1,27 +1,28 @@
from aiogram import types, Dispatcher
from create_bot import dp, bot
from aiogram import types
from create_bot import dp
import datetime
@dp.message_handler(commands=["time"])
async def send_time(message: types.Message):
new_year = datetime.datetime(2022, 12, 31) #дата нового года
ct = datetime.datetime.now() #датавремя
cd = datetime.datetime.now().strftime("%d/%m/%Y") #дата (д,м,г)
ct1 = ct+datetime.timedelta(hours=15) # +14 часов от сервера
ct2 = ct1.strftime('%H:%M') # форматирует датувремя просто во время(ч,м)
raznitsa = (new_year - ct).days #отнимает от нг текущее время и получаем разницу в днях
new_year = datetime.datetime(2022, 12, 31) # дата нового года
ct = datetime.datetime.now() # дата/время
cd = datetime.datetime.now().strftime("%d/%m/%Y") # дата (д,м,г)
ct1 = ct+datetime.timedelta(hours=15) # +14 часов от сервера
ct2 = ct1.strftime('%H:%M') # форматирует дату/время просто во время(ч, м)
date_difference = (new_year - ct).days # отнимает от нг текущее время и получаем разницу в днях
days = ['день', 'дня', 'дней']
if raznitsa % 10 == 1 and raznitsa % 100 != 11:
if date_difference % 10 == 1 and date_difference % 100 != 11:
p = 0
elif 2 <= raznitsa % 10 <= 4 and (raznitsa % 100 < 10 or raznitsa % 100 >= 20):
elif 2 <= date_difference % 10 <= 4 and (date_difference % 100 < 10 or date_difference % 100 >= 20):
p = 1
else:
p = 2
num=(str(raznitsa) + ' ' + days[p])
num = (str(date_difference) + ' ' + days[p])
await message.reply(f'Сегодня {cd} \nВремя: {ct2} \nДо Нового Года осталось {num}')
def register_handlers_time(dp: Dispatcher):
dp.register_message_handler(send_time)
# def register_handlers_time(dp: Dispatcher):
# dp.register_message_handler(send_time)

View File

@ -2,3 +2,4 @@ aiogram
sqdb
sqlalchemy
graypy
openai

26
sqdb.py
View File

@ -8,23 +8,29 @@ engine = create_engine('postgresql+psycopg2://postgres:postgres@postgres.vdk2ch.
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class user(Base):
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
user_id = Column(Integer)
date_created = (Column(DateTime))
user_fullname = Column(String)
dick_size = (Column(Integer))
date_updated = (Column(DateTime))
chat_id = Column(BIGINT)
dick_requests = relationship("DickRequest", back_populates="user")
dicks = relationship("UserDick", back_populates="user")
class UserDick(Base):
__tablename__ = 'user_dicks'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey("users.user_id"))
dick_size = (Column(Integer))
chat_id = Column(BIGINT)
user = relationship("User", back_populates="dick_requests")
class DickRequest(Base):
@ -35,12 +41,12 @@ class DickRequest(Base):
user = relationship("User", back_populates="dick_requests")
date_changed = (Column(DateTime))
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()
# 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)