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

cod*_*hiz 5 python migration python-telegram-bot telegram-bot telethon

Python-telegram-bot是 HTTP Telegram Bot API 包装器,具有telegram.ext.ConversationHandler模块,其功能是: “通过管理四个其他处理程序集合来与单个用户进行对话的处理程序。”

我正在从这个python-telegram-bot迁移到Telethon MTProto API。我有这个ConversationHandler来管理对话。如何ConversationHandlerTelethon 中创建任何类型的。

下面是给出了一些小概述马拉松式节目,以从蟒蛇,电报BOT迁移。他们使用ptb 示例中的echobot2.py。如何使用此示例对话机器人.py 进行迁移。

Lon*_*ami 8

您可以轻松创建所谓的“有限状态机”(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...
Run Code Online (Sandbox Code Playgroud)

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

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

我不建议使用 Telethon 1.0,client.conversation因为您很快就会遇到限制。