Aiogram. Не изменяет формат фото?
Пишу телеграм-бота на библиотеке aiogram. Функционал: пользователь отправляет изображение, а дальше бот изменяет формат фото.
НО при выборе кнопки "JPG-BMP", отправляю изображение, а оно изменяет формат фото на .png, как и в первой кнопке. Может дело в порядке расположения хендлеров? Заранее благодарен.
button0 = InlineKeyboardButton('Фото', callback_data='photo')
keyboard0 = InlineKeyboardMarkup().add(button0)
button3 = InlineKeyboardButton('JPG', callback_data='jpg')
keyboard3 = InlineKeyboardMarkup().add(button3)
button1 = InlineKeyboardButton('JPG-PNG', callback_data='jpg_png')
button4 = InlineKeyboardButton('JPG-BMP', callback_data='jpg_bmp')
keyboard1 = InlineKeyboardMarkup().add(button1).add(button4)
button2 = InlineKeyboardButton('Вернуться в меню', callback_data='menu')
keyboard2 = InlineKeyboardMarkup().add(button2)
#головне меню
@dp.message_handler(commands=['start'])
async def process_start_command(message: types.Message):
# Отправляем пользователю приветственное сообщение и клавиатуру
await message.answer("Привет. Выбери, что тебе нужно конвертировать:", reply_markup=keyboard0)
@dp.callback_query_handler(lambda call: call.data == 'photo')
async def process_photo_conversion(callback_query: types.CallbackQuery):
await callback_query.answer()
await bot.edit_message_text(chat_id=callback_query.message.chat.id,
message_id=callback_query.message.message_id,
text="Какая форматировка нужна?",
reply_markup=keyboard3)
is_jpg_png_message_sent = False
@dp.callback_query_handler(lambda call: call.data == 'jpg')
async def process_jpg_to_png(callback_query: types.CallbackQuery):
await callback_query.answer()
await bot.edit_message_text(chat_id=callback_query.message.chat.id,
message_id=callback_query.message.message_id,
text="Во что нужно переформатировать?",
reply_markup=keyboard1)
@dp.callback_query_handler(lambda call: call.data == 'jpg_png')
async def process_jpg_to_png(callback_query: types.CallbackQuery):
global is_jpg_png_message_sent
await callback_query.answer()
await bot.edit_message_text(chat_id=callback_query.message.chat.id,
message_id=callback_query.message.message_id,
text="Хорошо, отправьте фото.")
is_jpg_png_message_sent = True
@dp.message_handler(content_types='photo')
async def convert_photo(message: types.Message):
global is_jpg_png_message_sent
if is_jpg_png_message_sent:
image = io.BytesIO()
photo = message.photo[-1]
file = await photo.download(destination_file=image)
with Image.open(file) as im:
im.save(image, format="png")
image.seek(0)
await message.answer_document(('your_file.png', image), reply_markup=keyboard2)
is_jpg_png_message_sent = False
else:
await message.answer("Пожалуйста, сначала пройдите все шаги по выбору формата.")
@dp.callback_query_handler(lambda call: call.data == 'jpg_bmp')
async def process_jpg_to_bmp(callback_query: types.CallbackQuery):
global is_jpg_bmp_message_sent
await callback_query.answer()
await bot.edit_message_text(chat_id=callback_query.message.chat.id,
message_id=callback_query.message.message_id,
text="Хорошо, отправьте фото.")
is_jpg_bmp_message_sent = True
@dp.message_handler(content_types='photo')
async def convert_photo_to_bmp(message: types.Message):
global is_jpg_bmp_message_sent
if is_jpg_bmp_message_sent:
image = io.BytesIO()
photo = message.photo[-1]
file = await photo.download(destination_file=image)
with Image.open(file) as im:
im.save(image, format="bmp")
image.seek(0)
await bot.send_document(message.chat.id, document=image, filename='your_file.bmp', reply_markup=keyboard2)
is_jpg_bmp_message_sent = False
else:
await message.answer("Пожалуйста, сначала пройдите все шаги по выбору формата.")
@dp.callback_query_handler(lambda call: call.data == 'menu')
async def return_to_menu(callback_query: types.CallbackQuery):
await callback_query.answer()
await bot.send_message(chat_id=callback_query.message.chat.id,
text="Привет. Выбери, что тебе нужно конвертировать:",
reply_markup=keyboard0)
@dp.message_handler(content_types=types.ContentType.ANY)
async def handle_other_messages(message: types.Message):
await message.answer("Ошибка!")
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
Ответы (1 шт):
Автор решения: ZxNuClear
→ Ссылка
Ну, можно сделать например вот так. Запрос на отправку фото делать до запроса в какой формат преобразовывать, сохранять фото, а дальше, в зависимости от выбора пользователем формата конвертировать и отправлять файл
import logging
from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.utils import executor
from PIL import Image
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
logging.basicConfig(level=logging.INFO)
bot = Bot(token='ТВОЙ ТОКЕН')
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)
class Form(StatesGroup):
photo = State()
button0 = InlineKeyboardButton('Фото', callback_data='photo')
keyboard0 = InlineKeyboardMarkup().add(button0)
button1 = InlineKeyboardButton('JPG-PNG', callback_data='jpg_png')
button2 = InlineKeyboardButton('JPG-BMP', callback_data='jpg_bmp')
keyboard1 = InlineKeyboardMarkup(2).add(button1, button2)
button3 = InlineKeyboardButton('Вернуться в меню', callback_data='menu')
keyboard2 = InlineKeyboardMarkup().add(button3)
@dp.message_handler(commands=['start'])
async def process_start_command(message: types.Message):
await message.answer("Привет. Выбери, что тебе нужно конвертировать:", reply_markup=keyboard0)
@dp.callback_query_handler(text='photo')
async def cmd_get_photo(callback: types.CallbackQuery):
await callback.message.edit_text(text="Отправь мне фото!!!")
await Form.photo.set()
@dp.message_handler(state=Form.photo, content_types='photo')
async def cmd_photo(message: types.Message, state: FSMContext):
await message.photo[-1].download(destination_file='image.jpg')
await message.reply('В какой формат конвертировать?', reply_markup=keyboard1)
await state.finish()
@dp.callback_query_handler(text='jpg_png')
async def cmd_jpg_png(callback: types.CallbackQuery):
image = Image.open('image.jpg')
image.save('image.png')
await callback.message.answer_document(open('image.png', 'rb'), reply_markup=keyboard2)
@dp.callback_query_handler(text='jpg_bmp')
async def cmd_jpg_bmp(callback: types.CallbackQuery):
image = Image.open('image.jpg')
image.save('image.bmp')
await callback.message.answer_document(open('image.bmp', 'rb'), reply_markup=keyboard2)
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)