我正在编写一个Telegram机器人,该机器人必须将图像发送给用户,获得答复并将其存储为字符串。
我设法编写了启动机器人并发送图像的脚本(非常基本,我知道),但是我不知道如何获得答案。这是我脚本的MWE:
import telegram.ext
token = '1234567890:ABCdEffGH-IJKlm1n23oPqrst_UVzAbcdE4'
bot=telegram.Bot(token=token)
user_id = 567890123
image_path='./image.png'
with open(image_path,'rb') as my_image:
bot.send_photo(chat_id=user_id,photo=my_image,caption='What is this?')
% Somehow store the answer
% Do some other stuff
如何获取和存储用户的答案?
我可以根据需要更改脚本,但是要与Telegram的API交互,我只能使用python-telegram-bot
。
答案 0 :(得分:0)
您可以创建一个名为waiting_for_response的标志,并在发送图像后将其设置为 True 。 之后,您应该向漫游器添加一个处理程序,以接收用户的回复。您可以这样操作:
from telegram.ext import Updater, CommandHandler
updater = Updater(token=TOKEN, use_context=True)
dispatcher = updater.dispatcher
handler = RegexHandler(r'.+', function_name)
dispatcher.add_handler(handler)
注意:您应该使用自己的令牌替换令牌。
通过添加以下行,当用户发送消息时,它将调用 function_name 函数,您可以这样定义它:
def function_name(update, context):
global waiting_for_response
if waiting_for_response:
pass
您可以使用更新和上下文在此功能内添加对该消息进行的任何操作。