0

I tried a few things but while I'm able to display an inline button, I'm unable to get a picture button with a local icon stored in a folder within the script directory. Any advice?

I've tried

import io
import os
import logging

from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.types import InputFile, InlineKeyboardButton, InlineKeyboardMarkup
from aiogram.utils import executor


# Set up logging
logging.basicConfig(level=logging.INFO)

# Create a bot object
bot = Bot(token=os.environ['BOT_TOKEN'])
dp = Dispatcher(bot)


# Handler for the /start command
@dp.message_handler(commands=['start'])
async def start_handler(message: types.Message):
    # Load the image file and create a picture button
    with open('buttonPics/button_image.png', 'rb') as f:
        button_icon_data = io.BytesIO(f.read())
    button = InlineKeyboardButton(text="Click me!", callback_data="button_callback", )
    button.set_image(button_icon_data.getvalue())
    markup = InlineKeyboardMarkup().add(button)

    # Send the message with the picture button
    await bot.send_photo(chat_id=message.chat.id, photo=InputFile('buttonPics/button_image.png'), reply_markup=markup)


# Handler for the button callback
@dp.callback_query_handler(lambda callback_query: callback_query.data == "button_callback")
async def button_callback_handler(callback_query: types.CallbackQuery):
    await bot.answer_callback_query(callback_query.id)
    await bot.send_message(chat_id=callback_query.message.chat.id, text="You clicked the button!")


# Start the bot
if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)

The error I get is pretty clear: AttributeError: 'InlineKeyboardButton' object has no attribute 'set_image'

I've tried other examples I found but, I found nothing that displays a local picture inside a button. Any advice?

1 Answers1

0

Try this in the constructor

with open('buttonPics/button_image.png', 'rb') as f:
    button_icon_data = f.read()

button = InlineKeyboardButton(text="Click me!", callback_data="button_callback", icon=button_icon_data)
  • Thanks for the effort. Unfortunately I still get the same AttributeError –  May 13 '23 at 16:19
  • 1
    scanning the documentation of aiogram, there is nowhere a parameter `icon` mentioned, which might have resulted in a similar (but I don't think "same") AttributeError. – MaKaNu May 13 '23 at 23:47