'How can I restrict a Telegram bot's use to some users only?
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 =).
Solution 1:[1]
I found a solution from the official wiki of the library which uses a decorator. Code:
from functools import wraps
LIST_OF_ADMINS = [12345678, 87654321] # List of user_id of authorized users
def restricted(func):
@wraps(func)
def wrapped(update, context, *args, **kwargs):
user_id = update.effective_user.id
if user_id not in LIST_OF_ADMINS:
print("Unauthorized access denied for {}.".format(user_id))
return
return func(update, context, *args, **kwargs)
return wrapped
@restricted
def my_handler(update, context):
pass # only accessible if `user_id` is in `LIST_OF_ADMINS`.
I just @restricted
each function.
Solution 2:[2]
You can also create a custom Handler to restrict message handlers being executed.
import telegram
from telegram import Update
from telegram.ext import Handler
admin_ids = [123456, 456789, 1231515]
class AdminHandler(Handler):
def __init__(self):
super().__init__(self.cb)
def cb(self, update: telegram.Update, context):
update.message.reply_text('Unauthorized access')
def check_update(self, update: telegram.update.Update):
if update.message is None or update.message.from_user.id not in admin_ids:
return True
return False
Just make sure to register AdminHandler
as the first handler:
dispatcher.add_handler(AdminHandler())
Now every update (or message) that is received by the Bot will be rejected if it's not from an authorized user (admin_ids
).
Solution 3:[3]
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
Solution 4:[4]
admins=[123456,456789]
if update.message.from_user.id in admins:
update.message.reply_text('You are authorized to use this BOT!')
else:
update.message.reply_text('You are not authorized to access this BOT')
Solution 5:[5]
...
admins = ['123456', '565825', '2514588']
user = message.from_user.id
if user in admins:
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ntakwetet |
Solution 2 | Majid |
Solution 3 | Thijs Tops |
Solution 4 | thesalah1212 |
Solution 5 | MaurĂcio Morhy |