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

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

View File

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

View File

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

View File

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

View File

@ -2,3 +2,4 @@ aiogram
sqdb sqdb
sqlalchemy sqlalchemy
graypy 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 = sessionmaker(bind=engine)
session = Session() session = Session()
Base = declarative_base() Base = declarative_base()
class User(Base):
class user(Base):
__tablename__ = 'users' __tablename__ = 'users'
id = Column(Integer, primary_key=True) id = Column(Integer, primary_key=True)
user_id = Column(Integer) user_id = Column(Integer)
date_created = (Column(DateTime)) date_created = (Column(DateTime))
user_fullname = Column(String) user_fullname = Column(String)
dick_size = (Column(Integer))
date_updated = (Column(DateTime)) date_updated = (Column(DateTime))
chat_id = Column(BIGINT)
dick_requests = relationship("DickRequest", back_populates="user") 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): class DickRequest(Base):
@ -35,12 +41,12 @@ class DickRequest(Base):
user = relationship("User", back_populates="dick_requests") user = relationship("User", back_populates="dick_requests")
date_changed = (Column(DateTime)) date_changed = (Column(DateTime))
session.close() session.close()
engine.dispose() 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) # print(top)