Files
post_bot/.history/handlers/new_post_20250904013938.py
Andrey K. Choi aca280b64d
Some checks failed
continuous-integration/drone Build is failing
init commit
2025-09-04 01:51:59 +09:00

74 lines
3.6 KiB
Python

from telegram import Update, InputMediaPhoto, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import ContextTypes, ConversationHandler, MessageHandler, CommandHandler, filters, CallbackQueryHandler, ContextTypes
from db import SessionLocal
from models import Channel, Group, Button
SELECT_MEDIA, SELECT_TEXT, SELECT_TARGET = range(3)
async def new_post_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text('Отправьте картинку для поста или /skip:')
return SELECT_MEDIA
async def select_media(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.message.photo:
context.user_data['photo'] = update.message.photo[-1].file_id
await update.message.reply_text('Введите текст поста или пересланное сообщение:')
return SELECT_TEXT
async def select_text(update: Update, context: ContextTypes.DEFAULT_TYPE):
context.user_data['text'] = update.message.text or update.message.caption
session = SessionLocal()
channels = session.query(Channel).all()
groups = session.query(Group).all()
session.close()
keyboard = []
for c in channels:
keyboard.append([InlineKeyboardButton(f'Канал: {c.name}', callback_data=f'channel_{c.id}')])
for g in groups:
keyboard.append([InlineKeyboardButton(f'Группа: {g.name}', callback_data=f'group_{g.id}')])
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text('Выберите, куда отправить пост:', reply_markup=reply_markup)
return SELECT_TARGET
async def select_target(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
await query.answer()
data = query.data
session = SessionLocal()
try:
if data.startswith('channel_'):
channel_id = int(data.split('_')[1])
channel = session.query(Channel).get(channel_id)
buttons = session.query(Button).filter_by(channel_id=channel_id).all()
markup = InlineKeyboardMarkup([[InlineKeyboardButton(b.name, url=b.url)] for b in buttons]) if buttons else None
chat_id = channel.link.strip()
else:
group_id = int(data.split('_')[1])
group = session.query(Group).get(group_id)
buttons = session.query(Button).filter_by(group_id=group_id).all()
markup = InlineKeyboardMarkup([[InlineKeyboardButton(b.name, url=b.url)] for b in buttons]) if buttons else None
chat_id = group.link.strip()
# Проверка chat_id
if not (chat_id.startswith('@') or chat_id.startswith('-')):
await query.edit_message_text('Ошибка: ссылка должна быть username (@channel) или числовой ID (-100...)')
return ConversationHandler.END
try:
await context.bot.send_photo(chat_id=chat_id, photo=context.user_data.get('photo'), caption=context.user_data.get('text'), reply_markup=markup)
await query.edit_message_text('Пост отправлен!')
except Exception as e:
await query.edit_message_text(f'Ошибка отправки поста: {e}')
finally:
session.close()
return ConversationHandler.END
new_post_conv = ConversationHandler(
entry_points=[CommandHandler('new_post', new_post_start)],
states={
SELECT_MEDIA: [MessageHandler(filters.PHOTO | filters.Document.IMAGE | filters.COMMAND, select_media)],
SELECT_TEXT: [MessageHandler(filters.TEXT | filters.FORWARDED, select_text)],
SELECT_TARGET: [CallbackQueryHandler(select_target)],
},
fallbacks=[]
)