I’m programming a Telegram bot in python with the python-telegram-bot
library for python3.x It’s a bot for private use only (me and some relatives), so I would like to prevent other users from using it. My idea is to create a list of authorized user IDs and the bot must not answer to messages received from users not in the list. How can I do that?
Edit: I’m quite a newbie to both python and python-telegram-bot
. I’d appreciate a code snippet as example if possible =).
6
Answers
I found a solution from the official wiki of the library which uses a decorator. Code:
I just
@restricted
each function.Using the chat id. Create a little list with the chat id’s you want to allow, you can ignore the rest.
A link to the docs where you can find the specifics
https://python-telegram-bot.readthedocs.io/en/stable/telegram.chat.html
You can also create a custom Handler to restrict message handlers being executed.
Just make sure to register
AdminHandler
as the first handler:Now every update (or message) that is received by the Bot will be rejected if it’s not from an authorized user (
admin_ids
).You can use telegram.ext.filters.User.
Small example below