python-3.xbuttontelethonreply

Telethon make user reply to the sent message


Code should work like this I'm writing a telethon bot that should do the following:

  1. Bot listens to the messages sent by users in the channel.
  2. To the message '/start', bot greets the user with 'Hi {username}!'
  3. Bot makes the user auto reply to the message sent in step #2 (as if the user clicked the reply button of the message received from bot)

So far, I tried this code.

from telethon import TelegramClient, events


api_id = 'api_id'
api_hash = 'api_hash'
channel_id = 'channel_id'


client = TelegramClient("session", api_id, api_hash)
@client.on(events.NewMessage(chats=channel_id, pattern="/start"))
async def handler(event):
    sender = await event.get_sender()
    response = f"Hi [{sender.first_name}](tg://user?id={sender.id})!"
    await event.respond(response)
    await event.click(0)


client.start()
client.run_until_disconnected()

Code doesn't give any errors, but the button is not clicked either.


Solution

  • from telethon import TelegramClient, events
    from telethon.tl.custom.button import Button
    
    api_id = 'api_id'
    api_hash = 'api_hash'
    bot_token = 'bot_token'
    bot = TelegramClient("bot", api_id, api_hash).start(bot_token=bot_token)
    
    async def main():
        async with bot:
    
            @bot.on(events.NewMessage(pattern="/start"))
            async def handler(event):
                sender = await event.get_sender()
                response = f"Hi [{sender.first_name}](tg://user?id={sender.id})!"
                await event.respond(response, buttons=Button.force_reply("some text"))
    
            await bot.run_until_disconnected()