python-3.x - 如何使用 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
只能使用。
解决方案
您可以制作一个名为 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
您可以使用更新和上下文在此函数内添加您想要对该消息执行的任何操作。
推荐阅读
- android - 在根项目“android”中找不到任务“SigningRequest”
- python - 使用 python 和 playwright 库将文件上传到大小超过 1 GB 的测试网站
- php - PHP ob_get_contents 为空
- c++ - 没有引用的对象的内存会自动清除吗?
- reactjs - 在表格中的视图按钮上添加模态
- mysql - 我的Mysql版本是8.0.18,但是不能使用函数JSON_VALUE
- typescript - Vue3 + TS PropType 的泛型
- powershell - 在 Powershell 中无头运行 Selenium 时出现未知错误:net::ERR_CONNECTION_REFUSED
- google-chrome - 带有触摸屏的 Kiosk 模式下的 Chrome
- azure-bot-service - 通过对 Web 应用程序的 IP 限制允许 Web App Bot 和 Direct Line