【问题标题】:How to migrate ConversationHandler module from Python-Telegram-Bot to Telethon如何将 ConversationHandler 模块从 Python-Telegram-Bot 迁移到 Telethon
【发布时间】:2020-09-26 10:15:10
【问题描述】:

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

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

这是 Telethonmigrate from python-telegram-bot 的一些小概述。他们使用 ptb 示例中的echobot2.py。如何使用此示例进行迁移 conversationbot.py

【问题讨论】:

    标签: python migration telegram-bot python-telegram-bot telethon


    【解决方案1】:

    您可以轻松创建所谓的“有限状态机”(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,因为您很快就会遇到限制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-03
      • 2021-06-14
      • 1970-01-01
      相关资源
      最近更新 更多