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

六月ゝ 毕业季﹏ 提交于 2021-01-01 04:23:31

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/62245275/how-to-migrate-conversationhandler-module-from-python-telegram-bot-to-telethon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!