python-telegram-bot:如果会话处理程序中没有响应,则等待用户响应并设置过期时间

问题描述 投票:0回答:2

如何让机器人在 5 秒内等待回复?如果用户未在 5 秒内输入回复,则在另一个对话旁边。

我制作了一个收集媒体并将其保存到数据库的机器人。

  1. 用户上传媒体
  2. bot 会等待 5 秒回复
  3. 如果 5 秒内没有上传新媒体,bot 将要求用户选择媒体的位置。但是如果有新的媒体上传就再去步骤2
  4. 机器人选择媒体上传位置后结束对话

我设法使用了

job_queue
但失败了并得到了这个错误:

TypeError: waiting_respond() missing 2 required positional arguments: 'update' and 'context''"

代码如下:

async def waiting_respond(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
    if update.update_id == context.user_data["lastUpdate"]:
        return WAITING
    else:
        return CHOOSING

def main() -> None:
    """Run the bot."""
    application = Application.builder().token(bot_token).build()
    conv_handler = ConversationHandler(
    entry_points=[MessageHandler(filters.ALL, first_upload)],
    states={
        WAITING: [
            application.job_queue.run_once(waiting_respond(), 5)
        ],
        CHOOSING: [
            MessageHandler(
                filters.Regex("^(database sparepart|database item|galery item)$"), regular_choice
            ),
            MessageHandler(filters.Regex("^cancel$"), cancel_upload),
        ],
    },
    fallbacks=[MessageHandler(filters.Regex("^Done$"), complete_received_information)],
    )
python telegram-bot python-telegram-bot
2个回答
0
投票

看来你应该通过

waiting_respond
作为回调:

application.job_queue.run_once(waiting_respond, 5)
.


0
投票

首先你好像忘了设置状态。第二:对话具有称为

timeout
的属性,该属性在对话初始化期间设置并在每次用户更新对话时扩展。一旦超时 - 对话设置系统状态 TIMEOUT 并寻找处理程序。 试试这个:

async def waiting_respond(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
    if update.update_id == context.user_data["lastUpdate"]:
        return WAITING
    else:
        return CHOOSING

async def timeout(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # do some cleanup and finish the conversation
    return ConversationHandler.END

def main() -> None:
    """Run the bot."""
    application = Application.builder().token(bot_token).build()
    CHOOSING, WAIT = range(2)
    conv_handler = ConversationHandler(
        timeout=5,
        entry_points=[MessageHandler(filters.ALL, first_upload)],
        states={
            WAIT: [MessageHandler(filters.ALL, waiting_respond)],
            CHOOSING: [MessageHandler(filters.Regex("^(database|sparepart|database item|galery item)$"), regular_choice),
                       MessageHandler(filters.Regex("^cancel$"), cancel_upload),
                       ],
            ConversationHandler.TIMEOUT: [MessageHandler(filters.ALL, timeout)]
            },
        fallbacks=[MessageHandler(filters.Regex("^Done$"), complete_received_information)],
        )
© www.soinside.com 2019 - 2024. All rights reserved.