[QUESTION] How to check if a user block and stop bot #2485
-
How to check if a user block and stop botI use a database to store all users ids and information, and then my bot iterate users id and send message to them. But when a user block and stop bot I don't know how to remove user from database and bot will try to send message to a blocked user and this will raise an exception. I added a handler of type Related part of your codedef log_update(u: Update, c:CallbackContext):
message = (
'Received a new update event from telegram\n'
f'update = {json.dumps(u.to_dict(), indent = 2, ensure_ascii = False)}\n'
f'user_data = {json.dumps(c.user_data, indent = 2, ensure_ascii = False)}\n'
f'chat_data = {json.dumps(c.chat_data, indent = 2, ensure_ascii = False)}'
)
logging.info(message)
if self.debug:
try:
self.bot.send_message(self.ownerID,html.escape(message), parse_mode = ParseMode.HTML)
except Exception as e:
self.log_bug(e,'Exception while sending update log to owner',ownerID=self.ownerID, message=html.escape(message))
self.dispatcher.add_handler(MessageHandler(Filters.update,log_update)) |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
As of API 5.1 you will get an update with |
Beta Was this translation helpful? Give feedback.
-
Can I use |
Beta Was this translation helpful? Give feedback.
-
Yes. By comparing the |
Beta Was this translation helpful? Give feedback.
As of API 5.1 you will get an update with
update.my_chat_member
, whereupdate.my_chat_member.new_chat_member.status
can be used to check if the bot has been blocked. In PTB v13.4+ you can useChatMemberHandler
to catch those updates.Nevertherless, handling exceptions is a very sane & advisable thing to do. IIRC
Unauthorized
is raised when the user has blocked the bot, but you can also check the exception message (str(e)
) to see that.