首页 > 解决方案 > 如何使用 python-telegram-bot 获取和存储用户的消息?

问题描述

我正在编写一个 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只能使用。

标签: python-3.xtelegrampython-telegram-bot

解决方案


您可以制作一个名为 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)

注意:您应该将 TOKEN 替换为您自己的令牌。
通过添加此行,当用户发送消息时,它会调用function_name函数,您可以像这样定义它:

def function_name(update, context):
    global waiting_for_response
    if waiting_for_response:
        pass

您可以使用更新和上下文在此函数内添加您想要对该消息执行的任何操作。


推荐阅读