如何从 Telegram Bot 组中的消息中获取用户对象
最近我正在开发一个用 python 编写的简单 Telegram 机器人(使用 python-telegram-bot
库).在这个机器人中,我可以使用以下命令获取最后一个消息对象:
Recently I was working on a simple Telegram bot written in python (with the python-telegram-bot
library). In this bot I can get the last message object using following command :
bot.getUpdates()[-1].message
并且根据 Telegram Doc 消息对象包含一些属性,例如 message_id,from,date,chat
,... from
属性返回一个 User 对象,它是消息的发送者.但由于 from
是一个 python关键字(在导入时使用)因此我们不能使用它引发语法错误.
and according the Telegram Doc a message object is contains some attributes such as message_id,from,date,chat
,... which the from
attribute returns a User object which is the sender of a message. But since from
is a python keyword (used at import time) thus we can not use it which raise a SyntaxError.
作为另一种方式,我们可以使用 chat
属性,它在个人聊天中返回一个 User 对象,在它不包含的组中返回一个 GroupChat
对象以及有关用户.我也找不到任何直接报告此错误的方法.
As an alternative way we can use chat
attribute which returns a User object in personal chats and a GroupChat
object in groups that it doesn't contains and information about the user.Also I couldn't find any direct way to report this bug.
那么问题是有没有办法完成这项工作?或者任何替代解决方案?
So the question is that is there any way to do this job? or any alternative solution maybe?
既然已经澄清您正在使用 python-telegram-bot 库,解决方法很简单.库的作者重命名Python 不兼容的 from
属性到 from_user
.所以就这样做:
Since it was clarified that you're using the python-telegram-bot library, the solution is simple. The author of the library renamed the Python-incompatible from
attribute to from_user
. So just do:
user = bot.getUpdates()[-1].from_user