skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.


  2. 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

    Login or Signup to reply.
  3. 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')
    
    Login or Signup to reply.
  4. 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).

    Login or Signup to reply.
  5. ...
    admins = ['123456', '565825', '2514588']
    user = message.from_user.id 
    if user in admins:
    ...
    
    Login or Signup to reply.
  6. You can use telegram.ext.filters.User.

    Small example below

    from telegram import Update
    from telegram.ext import ApplicationBuilder, CommandHandler
    from telegram.ext.filters import User
    
    ALLOWED_IDS = [123456, 78910]
    TOKEN = 'TOKEN'
    
    
    async def start(update: Update, context):
        await context.bot.send_message(chat_id=update.effective_chat.id, text="Wow! Admin found!")
    
    
    if __name__ == '__main__':
        application = ApplicationBuilder().token(TOKEN).build()
        start_handler = CommandHandler('start', start, filters=User(ALLOWED_IDS))
        application.add_handler(start_handler)
        application.run_polling()
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search