Stopped using db in bot

This commit is contained in:
2023-11-22 20:57:20 +03:00
parent abf365f2f9
commit 642c347bba
15 changed files with 45 additions and 505 deletions

View File

@@ -1,14 +1,10 @@
from datetime import datetime
from typing import Any
from uuid import uuid4
from aiogram import Bot, F, Router, types
from aiogram.filters import Command
from aiogram.fsm.context import FSMContext
from aiogram.utils.media_group import MediaGroupBuilder
from sqlalchemy.orm import Session
from db.data import Admin, Image, Post, User, engine
from handlers.filters.new_post import (ChangePosts, NewPostFilter,
NewSoloPostFilter)
from handlers.filters.reply_to_user import ReplyToUser
@@ -17,10 +13,10 @@ from handlers.states.change_post import ChangePost
from neuroapi import neuroapi
def get_post_info(post: Post, post_id: int) -> str:
text = post.text
time = post.timestamp
from_user = post.from_user_id
def get_post_info(post: dict, post_id: int) -> str:
text = post["text"]
time = post["timestamp"]
from_user = post["from_user_id"]
s = f"""Индекс: {post_id}\nТекст: {text}\nВремя отправки: {time}\nОт: [id{from_user}](tg://user?id={from_user})""".replace('#', '\#').replace(
"_", "\_").replace('.', '\.').replace(',', '\,').replace('!', '\!').replace('-', '\-').replace(':', '\:')
return s
@@ -51,38 +47,34 @@ class Admin_commands:
post_c[post['from_user_id']] += 1
await message.answer(str(post_c))
#TODO: Post changing with backend
######################################3
@self.router.message(ChangePosts())
async def change_post(message: types.Message, state: FSMContext):
with Session(engine) as session:
posts = session.query(Post).filter(
Post.posted == False).order_by(Post.timestamp.asc()).all()
if len(posts):
await state.update_data(posts=posts, id=0)
select_btns = []
if len(posts) > 1:
select_btns.append(types.InlineKeyboardButton(
text='->', callback_data='next_post'))
kb = [
select_btns,
[types.InlineKeyboardButton(
callback_data='change_post_text', text='Текст')],
[types.InlineKeyboardButton(
text='Отмена', callback_data='cancel')]
]
keyboard = types.InlineKeyboardMarkup(inline_keyboard=kb)
images = MediaGroupBuilder(
caption=get_post_info(posts[0], 1))
for image in posts[0].images:
images.add_photo(
image.file_id, parse_mode='markdownv2')
mes = await message.answer_media_group(media=images.build())
await state.update_data(edit_msg=mes[0].message_id)
await message.answer('Действия', reply_markup=keyboard)
# await message.answer(get_post_info(posts[0]), reply_markup=keyboard, parse_mode='markdownv2')
else:
await message.answer('Нет постов')
posts = await neuroapi.post.get_will_post()
if (posts):
await state.update_data(posts=posts, id=0)
select_btns = []
if len(posts) > 1:
select_btns.append(types.InlineKeyboardButton(
text='->', callback_data='next_post'))
kb = [
select_btns,
[types.InlineKeyboardButton(
callback_data='change_post_text', text='Текст')],
[types.InlineKeyboardButton(
text='Отмена', callback_data='cancel')]
]
keyboard = types.InlineKeyboardMarkup(inline_keyboard=kb)
post = await neuroapi.post.get(posts[0]['uuid'])
images = MediaGroupBuilder(
caption=get_post_info(post, 1))
for image in sorted(post['images'], key=lambda x: x['message_id']):
images.add_photo(image['file_id'],
has_spoiler=image['has_spoiler'], parse_mode='markdownv2')
mes = await message.answer_media_group(images.build())
await state.update_data(edit_msg=mes[0].message_id)
await message.answer('Действия', reply_markup=keyboard)
else:
await message.answer('Нет постов')
@self.router.callback_query(F.data == 'next_post')
async def next_post_changing(callback: types.CallbackQuery, state: FSMContext):
@@ -108,7 +100,8 @@ class Admin_commands:
]
keyboard = types.InlineKeyboardMarkup(inline_keyboard=kb)
await state.update_data(id=post_id)
await bot.edit_message_caption(caption=get_post_info(posts[post_id], post_id+1), chat_id=callback.message.chat.id, message_id=data['edit_msg'], parse_mode='markdownv2')
post = await neuroapi.post.get(posts[post_id]['uuid'])
await bot.edit_message_caption(caption=get_post_info(post, post_id+1), chat_id=callback.message.chat.id, message_id=data['edit_msg'], parse_mode='markdownv2')
await callback.message.edit_reply_markup(reply_markup=keyboard)
await callback.answer()
@@ -138,13 +131,13 @@ class Admin_commands:
return
posts = data['posts']
post_id = data['id']
post: Post = posts[post_id]
with Session(engine) as session:
p = session.get(Post, post.uuid)
p.text = message.text
session.commit()
post_uuid = posts[post_id]['uuid']
try:
await neuroapi.post.edit_text(post_uuid, message.text)
await message.answer(f'Текст поста изменен на: {message.text}')
except:
await message.answer('Ошибка')
await state.clear()
await message.answer(f'Текст поста изменен на: {message.text}')
@self.router.callback_query(F.data == 'prev_post')
async def prev_post_changing(callback: types.CallbackQuery, state: FSMContext):
@@ -170,7 +163,8 @@ class Admin_commands:
]
keyboard = types.InlineKeyboardMarkup(inline_keyboard=kb)
await state.update_data(id=post_id)
await bot.edit_message_caption(caption=get_post_info(posts[post_id], post_id), chat_id=callback.message.chat.id, message_id=data['edit_msg'], parse_mode='markdownv2')
post = await neuroapi.post.get(posts[post_id]['uuid'])
await bot.edit_message_caption(caption=get_post_info(post, post_id), chat_id=callback.message.chat.id, message_id=data['edit_msg'], parse_mode='markdownv2')
await callback.message.edit_reply_markup(reply_markup=keyboard)
await callback.answer()
@@ -182,8 +176,6 @@ class Admin_commands:
data = await state.get_data()
if 'edit_msg' in data:
await bot.delete_message(message_id=data['edit_msg'], chat_id=callback.message.chat.id)
##########################################################
@self.router.message(Command('post'))
async def post(message: types.Message):
@@ -192,7 +184,8 @@ class Admin_commands:
post = await neuroapi.post.get(posts[0]['uuid'])
images = MediaGroupBuilder(caption=post['text'])
for image in sorted(post['images'], key=lambda x: x['message_id']):
images.add_photo(image['file_id'], has_spoiler=image['has_spoiler'])
images.add_photo(image['file_id'],
has_spoiler=image['has_spoiler'])
await message.answer_media_group(images.build())
else:
await message.answer('Нет постов')
@@ -202,7 +195,7 @@ class Admin_commands:
post = await neuroapi.post.new(message.caption.replace('/newpost ', ''), message.from_user.id)
await neuroapi.image.add(post['uuid'], message.photo[-1].file_id, message.has_media_spoiler, message.message_id)
await message.answer('Пост успешно добавлен!')
@self.router.message(ReplyToUser())
async def reply_user(message: types.Message):
if message.reply_to_message.forward_from is None:

View File

@@ -1,13 +1,6 @@
from asyncio import create_task
from time import sleep
from typing import Any
from uuid import uuid4
from aiogram import types
from aiogram.filters import Filter
from sqlalchemy.orm import Session
from db.data import Admin, Image, Post, User, engine
from neuroapi import neuroapi
@@ -19,9 +12,9 @@ class NewPostFilter(Filter):
await neuroapi.post.get_by_media_group_id(message.media_group_id)
except:
if not (message.caption.startswith('/newpost ') if message.caption else False):
return False
return False
await neuroapi.post.new(message.caption.replace(
'/newpost ', ''), str(message.from_user.id), str(message.media_group_id))
'/newpost ', ''), str(message.from_user.id), str(message.media_group_id))
await message.answer('Пост успешно добавлен!')
return True

View File

@@ -1,4 +1,3 @@
from typing import Any
from aiogram import types
from aiogram.filters import Filter