如何在 AWS Lambda 中为 Telegram 机器人使用 ConversationHandler

How to use ConversationHandler for Telegram bot in AWS Lambda

我目前正在使用 python-telegram-bot 作为包装器编写 Telegram 机器人。我想尝试在 AWS Lambda 上托管它。然而,到目前为止,我看到的例子都是简单、愚蠢的机器人,它们无法继续对话。我正在利用 ConversationHandler 运行 机器人的对话,但这在 AWS Lambda 上效果不佳。我不确定如何解决这个问题。

bot = MyBot()

def lambda_handler(event=None, context=None):
    try:
        dispatcher = bot.updater.dispatcher
        message = json.loads(event['body'])
        print("Incoming:", message)
        dispatcher.process_update(Update.de_json(message, bot.updater.bot))
    except Exception as e:
        print(e)
        return {"statusCode": 500}
    bot.updater.idle()

    return {"statusCode": 200}

如何让机器人始终保持对话状态?

ConversationHandler 在内部存储状态,即在内存中。我不知道 AWS 如何处理变量的初始化,但如果 ConversationHandler 在每次传入更新时重新初始化,它不会记住每个对话所处的状态。如果你可以使用某种 database/file AWS 上的存储,您可以尝试使用 PTB persistence 设置来存储转换状态并为每个传入更新重新加载它们。


免责声明:我目前是 python-telegram-bot

的维护者