python电报bot ForceReply回调

2024-04-23 23:11:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在用python电报机器人开发一个电报机器人。我希望能够得到回复ForceReply的消息。预期的流量如下:

  1. 用户发送/启动命令
  2. Bot发送带有一些信息的消息。该消息与ForceReply链接
  3. 用户对消息的回复
  4. 处理和操作信息

我怎样才能达到预期的结果?谢谢

initial_message = "Hi... Please reply to this message to proceed to the next step..."

def start (update: Update, context: CallbackContext):
    chat_id = update.message.chat_id
    print(update.message.from_user.username)
    context.bot.send_message(chat_id=chat_id, text=initial_message, reply_markup=ForceReply())

Tags: to用户信息id消息messagecontextchat
1条回答
网友
1楼 · 发布于 2024-04-23 23:11:02

要能够处理ForceReply(),必须实现ConversationHandler。一旦用户回复ForceReply,使用ConversationHandler,您就可以处理他/她的回复。就是这样做的:

END = ConversationHandler.END
NEXTSTEP = range (1)

initial_message = "Hi... Please reply to this message to proceed to the next step..."
def start (update, context):
    chat_id = update.message.chat_id
    print(update.message.from_user.username)
    context.bot.send_message(chat_id=chat_id,
                             text=initial_message,
                             reply_markup=ForceReply())

    return NEXTSTEP

def nextstep (update, context):

    chat_id = update.message.chat_id
    ##user reply will be assigned to replied variable below
    replied = update.message.text
    print(replied)

    return END

def main():
    ##handler start
    start_handler = ConversationHandler(
        entry_points = [CommandHandler('start', start)],
        states = {
            NEXTSTEP: [MessageHandler(Filters.text & ~Filters.command, nextstep)]},
        fallbacks = [CommandHandler('cancel', callback = functions.cancel)])
    dp.add_handler(start_handler)

相关问题 更多 >