skip to Main Content

I’m trying to create a telegram bot with telethon that uses inline buttons and can’t seem to figure out how to edit my messages after a button is pressed. I have something like this to start:

@bot.on(events.NewMessage(pattern='/start'))
async def send_welcome(event):

    await bot.send_message(event.from_id, 'What food do you like?', buttons=[
        Button.inline('Fruits', 'fruit'),
        Button.inline('Meat', 'meat')
    ])

@bot.on(events.CallbackQuery(data='fruit'))
async def handler(event):

    await bot.edit_message(event.from_id, event.id, 'What fruits do you like?', buttons=[
        Button.inline('Apple', 'apple'),
        Button.inline('Pear', 'pear'),
        ...
    ])

After clicking on the Fruits button, nothing happens. Would love some help on this!

2

Answers


  1. Like this u can edit

    message = await client.send_message(chat, 'hello')
    await client.edit_message(chat, message, 'hello!')
    # or
    await client.edit_message(chat, message.id, 'hello!!')
    # or
    await client.edit_message(message, 'hello!!!')
    

    from the official documentation of telethon

    Login or Signup to reply.
  2. May I suggest a solution.
    It implements the exact idea of mr. Snowman’s question. But it might be useful to place conditions inside the handler.

    from telethon import TelegramClient, sync, events, Button 
    
    api_id = xxx
    api_hash = 'xxx'
    bot = TelegramClient('session', api_id, api_hash)
    
    @bot.on(events.NewMessage(pattern='/start'))
    async def send_welcome(event):
        await bot.send_message(event.sender_id,
            'What food do you like?',
            buttons=[
                Button.inline('Fruits', 'fruit'),
                Button.inline('Meat', 'meat')
            ]
        )
    
    @bot.on(events.CallbackQuery(data='fruit'))
    async def handler(event):
        await bot.edit_message(event.sender_id, event.message_id,
            'What fruits do you like?',
            buttons=[
                Button.inline('Apple', 'apple'),
                Button.inline('Pear', 'pear')
            ]
        )
    
    bot.start()
    bot.run_until_disconnected()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search