Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to migrate ConversationHandler module from Python-Telegram-Bot to Telethon

Python-telegram-bot which is HTTP Telegram Bot API wrapper has telegram.ext.ConversationHandler module and its functionality is: "A handler to hold a conversation with a single user by managing four collections of other handlers."

I'm migrating from this python-telegram-bot to Telethon MTProto API. And I have this ConversationHandler to manage conversation. How can I create any type of ConversationHandler in Telethon.

Here is some little overview given by Telethon to migrate from python-telegram-bot. They use echobot2.py from ptb's examples. How can I migrate using this example conversationbot.py.

like image 690
codewhiz Avatar asked Mar 03 '23 09:03

codewhiz


1 Answers

You can easily create what's known as a "finite state machine" (FSM) that is able to differentiate between the different states of a conversation a user can find themselves in.

from enum import Enum, auto

# We use a Python Enum for the state because it's a clean and easy way to do it
class State(Enum):
    WAIT_NAME = auto()
    WAIT_AGE = auto()

# The state in which different users are, {user_id: state}
conversation_state = {}

# ...code to create and setup your client...

@client.on(events.NewMessage)
async def handler(event):
    who = event.sender_id
    state = conversation_state.get(who)
    
    if state is None:
        # Starting a conversation
        await event.respond('Hi! What is your name?')
        conversation_state[who] = State.WAIT_NAME

    elif state == State.WAIT_NAME:
        name = event.text  # Save the name wherever you want
        await event.respond('Nice! What is your age?')
        conversation_state[who] = State.WAIT_AGE

    elif state == State.WAIT_AGE:
        age = event.text  # Save the age wherever you want
        await event.respond('Thank you!')
        # Conversation is done so we can forget the state of this user
        del conversation_state[who]

# ...code to keep Telethon running...

You can get as fancy as you want with this approach. You could make your own decorators and return new_state to automatically change the state or to only enter a handler if the state is correct, you can leave the state unchanged to create a loop (if the user entered an invalid age number for example), or perform any jumps to other states you want.

This approach is very flexible and powerful, although it may need some time to get used to it. It has other benefits like being very easy to persist only the data you need, however you want.

I would not recommend using Telethon 1.0's client.conversation because you will quickly run into limitations.

like image 83
Lonami Avatar answered Mar 04 '23 22:03

Lonami