How To Limit Access To A Telegram Bot

后端 未结 5 1310
感情败类
感情败类 2020-12-16 12:07

When I send a message to my Telegram Bot, it responses with no problems.

I wanna limit the access such that me and only me can send message to it.

How can I

相关标签:
5条回答
  • 2020-12-16 12:30

    Start a conversation with your bot, and send it a message. This will queue up an updates for the bot containing the message and the chat ID for your conversation.

    To view recent updates, you call the getUpdates method. This is done by making a HTTP GET request to the URL https://api.telegram.org/bot$TOKEN/getUpdates Where $TOKEN is the token provided by the BotFather. Something like:

    "chat":{
            "id":12345,
            "first_name":"Bob",
            "last_name":"Jones",
            "username":"bjones",
            "type":"private"},
          "date":1452933785,
          "text":"Hi there, bot!"}}]}
    

    Once you determined your chat id you can write a piece of code in your bot like:

    id_a = [111111,2222222,3333333,4444444,5555555]
    
        def handle(msg):
            chat_id = msg['chat']['id']
            command = msg['text']
            sender = msg['from']['id']
         if sender in id_a:
        [...]
         else:
               bot.sendMessage(chat_id, 'Forbidden access!')
               bot.sendMessage(chat_id, sender)
    
    0 讨论(0)
  • 2020-12-16 12:44

    Based on the python-telegram-bot code snippets, one can build a simple wrapper around the handler:

    def restricted(func):
        """Restrict usage of func to allowed users only and replies if necessary"""
        @wraps(func)
        def wrapped(bot, update, *args, **kwargs):
            user_id = update.effective_user.id
            if user_id not in conf['restricted_ids']:
                print("WARNING: Unauthorized access denied for {}.".format(user_id))
                update.message.reply_text('User disallowed.')
                return  # quit function
            return func(bot, update, *args, **kwargs)
        return wrapped
    

    where conf['restricted_ids'] might be an id list, e.g. [11111111, 22222222].

    So the usage would look like this:

    @restricted
    def bot_start(bot, update):
        """Send a message when the command /start is issued"""
        update.message.reply_text('Hi! This is {} speaking.'.format(bot.username))
    
    0 讨论(0)
  • 2020-12-16 12:47

    As this question is related to python-telegram-bot, information below is related to it:

    When you add handlers to your bot's dispatcher, you can specify various pre-built filters (read more at docs, github) or you can create custom ones in order to filter incoming updates.

    To limit access to a specific user, you need to add Filters.user(username="@telegramusername") when initializing handler, e.g.:

    dispatcher.add_handler(CommandHandler("start", text_callback, Filters.user(username="@username")))

    This handler will accept /start command only from user with username @username.

    You can also specify user-id instead of username, which I would highly recommend, as latter is non-constant and can be changed over time.

    0 讨论(0)
  • 2020-12-16 12:47

    Filter messages by field update.message.from.id

    0 讨论(0)
  • 2020-12-16 12:48

    Filtering by update.message.chat_id works for me. In order to find your chat id, send a message to your bot and browse to

    https://api.telegram.org/bot$TOKEN/getUpdates
    

    where $TOKEN is the bot token as provided by BotFather, as mentioned in the answer by fdicarlo, where you can find the chat id in the json structure.

    0 讨论(0)
提交回复
热议问题