2

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 =).

Ntakwetet
  • 253
  • 2
  • 12
  • Does this answer your question? [How to restrict the acess to a few users in pyTelegramBotAPI?](https://stackoverflow.com/questions/55437732/how-to-restrict-the-acess-to-a-few-users-in-pytelegrambotapi/55445114#55445114) – 0stone0 Jun 19 '20 at 10:28
  • @0stone0 It doesn't - it uses `telebot`, but I use `python-telegram-bot`. I'm working on solutions to [the linked question](https://stackoverflow.com/questions/35368557/how-to-limit-access-to-a-telegram-bot), though. – Ntakwetet Jun 19 '20 at 18:47

6 Answers6

9

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.

Ntakwetet
  • 253
  • 2
  • 12
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).

Majid
  • 3,128
  • 1
  • 26
  • 31
1
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')
0

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

0
...
admins = ['123456', '565825', '2514588']
user = message.from_user.id 
if user in admins:
...
0

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()