async refactor & docker deploy environment
Some checks failed
continuous-integration/drone/push Build is failing

This commit is contained in:
2025-09-05 12:04:58 +09:00
parent 0d3bcdfc64
commit d17f0f5507
15 changed files with 361 additions and 187 deletions

View File

@@ -1,58 +1,76 @@
from telegram import Update
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ContextTypes, ConversationHandler, CommandHandler, CallbackQueryHandler, MessageHandler, filters
from db import SessionLocal
from db import AsyncSessionLocal
from models import Channel, Group, Button
SELECT_TARGET, INPUT_NAME, INPUT_URL = range(3)
async def add_button_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
# Если выбран канал или группа уже сохранены — сразу переход к названию
if context.user_data.get('channel_id'):
context.user_data['target'] = f"channel_{context.user_data['channel_id']}"
await update.message.reply_text('Введите название кнопки:')
if context.user_data is None:
context.user_data = {}
user_data = context.user_data
if user_data.get('channel_id'):
context.user_data['target'] = f"channel_{user_data['channel_id']}"
if update.message:
await update.message.reply_text('Введите название кнопки:')
return INPUT_NAME
elif context.user_data.get('group_id'):
context.user_data['target'] = f"group_{context.user_data['group_id']}"
await update.message.reply_text('Введите название кнопки:')
elif user_data.get('group_id'):
context.user_data['target'] = f"group_{user_data['group_id']}"
if update.message:
await update.message.reply_text('Введите название кнопки:')
return INPUT_NAME
# Если нет — стандартный выбор
session = SessionLocal()
channels = session.query(Channel).all()
groups = session.query(Group).all()
session.close()
from sqlalchemy import select
async with AsyncSessionLocal() as session:
result_channels = await session.execute(select(Channel))
channels = result_channels.scalars().all()
result_groups = await session.execute(select(Group))
groups = result_groups.scalars().all()
keyboard = []
for c in channels:
keyboard.append([{'text': f'Канал: {c.name}', 'callback_data': f'channel_{c.id}'}])
keyboard.append([InlineKeyboardButton(f'Канал: {getattr(c, "name", str(c.name))}', callback_data=f'channel_{getattr(c, "id", str(c.id))}')])
for g in groups:
keyboard.append([{'text': f'Группа: {g.name}', 'callback_data': f'group_{g.id}'}])
keyboard.append([InlineKeyboardButton(f'Группа: {getattr(g, "name", str(g.name))}', callback_data=f'group_{getattr(g, "id", str(g.id))}')])
if not keyboard:
await update.message.reply_text('Нет каналов или групп для добавления кнопки.')
if update.message:
await update.message.reply_text('Нет каналов или групп для добавления кнопки.')
return ConversationHandler.END
await update.message.reply_text('Выберите канал или группу:', reply_markup=None)
if update.message:
await update.message.reply_text('Выберите канал или группу:', reply_markup=InlineKeyboardMarkup(keyboard))
context.user_data['keyboard'] = keyboard
return SELECT_TARGET
async def select_target(update: Update, context: ContextTypes.DEFAULT_TYPE):
if context.user_data is None:
context.user_data = {}
query = update.callback_query
await query.answer()
data = query.data
context.user_data['target'] = data
await query.edit_message_text('Введите название кнопки:')
return INPUT_NAME
if query:
await query.answer()
data = query.data
context.user_data['target'] = data
await query.edit_message_text('Введите название кнопки:')
return INPUT_NAME
return ConversationHandler.END
async def input_name(update: Update, context: ContextTypes.DEFAULT_TYPE):
context.user_data['button_name'] = update.message.text
await update.message.reply_text('Введите ссылку для кнопки:')
return INPUT_URL
if context.user_data is None:
context.user_data = {}
if update.message and hasattr(update.message, 'text'):
context.user_data['button_name'] = update.message.text
await update.message.reply_text('Введите ссылку для кнопки:')
return INPUT_URL
return ConversationHandler.END
async def input_url(update: Update, context: ContextTypes.DEFAULT_TYPE):
url = update.message.text
name = context.user_data.get('button_name')
target = context.user_data.get('target')
if not target or ('_' not in target):
await update.message.reply_text('Ошибка: не выбран канал или группа. Попробуйте снова.')
url = update.message.text if update.message and hasattr(update.message, 'text') else None
name = context.user_data.get('button_name') if context.user_data else None
target = context.user_data.get('target') if context.user_data else None
if not url or not name or not target or ('_' not in target):
if update.message:
await update.message.reply_text('Ошибка: не выбран канал или группа. Попробуйте снова.')
return ConversationHandler.END
session = SessionLocal()
session = AsyncSessionLocal()
try:
type_, obj_id = target.split('_', 1)
obj_id = int(obj_id)
@@ -61,16 +79,19 @@ async def input_url(update: Update, context: ContextTypes.DEFAULT_TYPE):
elif type_ == 'group':
button = Button(name=name, url=url, group_id=obj_id)
else:
await update.message.reply_text('Ошибка: неверный тип объекта.')
session.close()
if update.message:
await update.message.reply_text('Ошибка: неверный тип объекта.')
await session.close()
return ConversationHandler.END
session.add(button)
session.commit()
await update.message.reply_text('Кнопка добавлена.')
await session.commit()
if update.message:
await update.message.reply_text('Кнопка добавлена.')
except Exception as e:
await update.message.reply_text(f'Ошибка при добавлении кнопки: {e}')
if update.message:
await update.message.reply_text(f'Ошибка при добавлении кнопки: {e}')
finally:
session.close()
await session.close()
return ConversationHandler.END
add_button_conv = ConversationHandler(
@@ -81,4 +102,4 @@ add_button_conv = ConversationHandler(
INPUT_URL: [MessageHandler(filters.TEXT & ~filters.COMMAND, input_url)],
},
fallbacks=[]
)
)