@TPHsMP

Почему Telegram бот неправильно обрабатывает нажатие кнопок?

Доброго времени суток!

Возникла такая проблема с ботом: пользователю выводятся три кнопки для загрузки разных изображений. По идее при выборе кнопки 1 отправленное изображение должно загружаться в папку 1, при выборе кнопки 2 в папку 2 и так далее. Но если была нажата кнопка 1, то потом при нажатии кнопки 2 или 3 изображение все равно загружается в папку 1.

Прошу помочь разобраться.

import logging
import os
import random

from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, ContentType
from aiogram.utils import executor

# установка уровня логирования
logging.basicConfig(level=logging.INFO)

# инициализация бота и диспетчера
bot = Bot(token='')
dp = Dispatcher(bot, storage=MemoryStorage())


# выбор случайного изображения из папки указанной в /path
def random_image(path):
    folder = path
    files = os.listdir(folder)
    paths = [os.path.join(folder, file) for file in files]
    random_path = random.choice(paths)
    image = open(random_path, 'rb')
    return image


# обработчик команды /start
@dp.message_handler(commands=['start'])
async def start_command(message: types.Message):
    show_mem = KeyboardButton('show_mem')
    show_motivator = KeyboardButton('show_motivator')
    show_art = KeyboardButton('show_art')
    send_mem = KeyboardButton('send_mem')
    send_motivator = KeyboardButton('send_motivator')
    send_art = KeyboardButton('send_art')
    keyboard = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True).add(show_mem,
                                                                                     show_motivator,
                                                                                     show_art,
                                                                                     send_mem,
                                                                                     send_motivator,
                                                                                     send_art)
    await bot.send_message(message.from_user.id, 'Hey!', reply_markup=keyboard)


# обработка кнопок
@dp.message_handler(content_types=['text'])
async def button_processing(message):
    if message.text == 'show_mem':
        await bot.send_photo(message.from_user.id, photo=random_image("photo/mem"))
    if message.text == 'show_motivator':
        await bot.send_photo(message.from_user.id, photo=random_image("photo/motivator"))
    if message.text == 'show_art':
        await bot.send_photo(message.from_user.id, photo=random_image("photo/photo"))
    if message.text == 'send_mem':
        picture_saver("photo/mem/")
    if message.text == 'send_motivator':
        picture_saver("photo/motivator/")
    if message.text == 'send_art':
        picture_saver("photo/photo/")


# сохранение изображения в папку указанную в path
def picture_saver(path):
    @dp.message_handler(content_types=['photo'])
    async def get_photo(message: types.Message):
        try:
            await message.photo[-1].download(destination_file=f"{path}/picture_{message.message_id}.jpg")
            await bot.send_message(message.from_user.id, 'Download complete')
        except Exception as ex:
            print(ex)


# запуск бота
if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)
  • Вопрос задан
  • 88 просмотров
Пригласить эксперта
Ответы на вопрос 1
но в общем, так работать не будет. потому что вы хотите регистрировать один и тот же хендлер несколько раз. а так нельзя
для решение этой задачки нужно использовать машину состояний. вы бы немного поизучали aiogram прежде чем браться за такие задачки. вот хороший мануал и ссылка непосредственно на статью про машину состояний
https://mastergroosha.github.io/aiogram-2-guide/fsm/
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы