我正在尝试编写一个机器人,其中用户单击命令,将链接作为消息发送,然后该机器人将链接添加到某个数据库。外观如下:
所以我认为我应该使用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
中生成)。但是我不知道如何传递这个变量。我该怎么办?
答案 0 :(得分:3)
借助此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"]
非常简单直观。这是输出: