python-telegram-bot在对话处理程序之间传递参数

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

我正在尝试编写一个机器人,在该机器人中,用户单击命令,将链接作为消息发送,然后该机器人将链接添加到某个数据库。外观如下:

python-telegram-bot

所以我认为我应该使用ConversationHandler。这是我写的bot.py

from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,
        ConversationHandler)
from settings import BOT_TOKEN
import commands

def main():
    updater = Updater(BOT_TOKEN, use_context=True)
    dispatcher = updater.dispatcher

    conversation = ConversationHandler(
            entry_points=[
                MessageHandler(
                    (Filters.command & Filters.regex("al_(.*)")),
                    commands.add_link
                )
            ],
            states={
                commands.ADD_LINK: [
                    MessageHandler(Filters.entity("url"), commands.receive_link)
                ]
            },
            fallbacks=[]
    )

    dispatcher.add_handler(CommandHandler("search", commands.search))
    dispatcher.add_handler(conversation)

    updater.start_polling()
    updater.idle()

if __name__ == "__main__":
    main()

并且命令在另一个名为commands.py的文件中:

from telegram.ext import ConversationHandler

ADD_LINK = range(1)

def receive_link(update, context):
    bot = context.bot
    url = update.message.text
    chat_id = update.message.chat.id

    bot.send_message(
            chat_id=chat_id,
            text="The link has been added."
    )
    return ConversationHandler.END

def add_link(update, context):
    bot = context.bot
    uuid = update.message.text.replace("/al_", "")
    chat_id = update.message.chat.id
    bot.send_message(
            chat_id=chat_id,
            text="Send the link as a message."
    )

    return ADD_LINK

现在的问题是,我需要能够在uuid函数中使用add_link变量(在receive_link中生成)。但是我不知道如何传递这个变量。我该怎么办?

python python-telegram-bot
1个回答
0
投票

借助于此article,我这样解决了它。

通过在任何处理程序回调中使用context.user_data,您可以访问用户特定的字典。

所以我的代码将更改如下:

from telegram.ext import ConversationHandler

ADD_LINK = range(1)

def receive_link(update, context):
    bot = context.bot
    url = update.message.text
    chat_id = update.message.chat.id
    uuid = context.user_data["uuid"]

    bot.send_message(
            chat_id=chat_id,
            text=f"The link has been added to '{uuid}'."
    )
    return ConversationHandler.END

def add_link(update, context):
    bot = context.bot
    uuid = update.message.text.replace("/al_", "")
    context.user_data["uuid"] = uuid
    chat_id = update.message.chat.id
    bot.send_message(
            chat_id=chat_id,
            text=f"Send the link as a message."
    )

    return ADD_LINK

我像这样存储了uuid变量:

context.user_data["uuid"] = uuid

并像这样使用它:

uuid = context.user_data["uuid"]

非常简单直观。这是输出:

python-telegram-bot store user data

© www.soinside.com 2019 - 2024. All rights reserved.