如何将 ConversationHandler 模块从 Python-Telegram-Bot 迁移到 Telethon

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 模块及其功能是:"A handler to hold a conversation with a single user by managing four collections of other handlers."

我正在从这个 python-telegram-bot 迁移到 Telethon MTProto API。我有这个 ConversationHandler 来管理对话。我如何在 Telethon.

中创建任何类型的 ConversationHandler

这里是 Telethonmigrate from python-telegram-bot. They use echobot2.py from ptb's examples. How can I migrate using this example conversationbot.py 的一些小概述。

您可以轻松创建所谓的“有限状态机”(FSM),它能够区分用户可能发现的对话的不同状态

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...

通过这种方法,您可以随心所欲。您可以制作自己的装饰器和 return new_state 来自动更改状态或仅在状态正确时输入处理程序,您可以保持状态不变以创建循环(例如,如果用户输入了无效的年龄数字), 或执行任何跳转到您想要的其他状态。

这种方法非常灵活和强大,尽管可能需要一些时间来适应它。它还有其他好处,例如非常容易只保留您需要的数据,无论您想要什么。

我不推荐使用 Telethon 1.0 的 client.conversation,因为你很快就会 运行 进入限制。