【问题标题】:How to migrate ConversationHandler module from Python-Telegram-Bot to Telethon如何将 ConversationHandler 模块从 Python-Telegram-Bot 迁移到 Telethon
【发布时间】:2020-09-26 10:15:10
【问题描述】:
【问题讨论】:
标签:
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,因为您很快就会遇到限制。