ns28
ns28

Reputation: 61

Limit the access of telegram bot through Chat ID

I have attached the code. I want chat_id to be accessed from the text file located at my local machine.

#constants.py
  chatid_list = []
  file1 = open(r'D:\\folder1\\chatids.txt', "r")
  for chat_id in file1:
       chatid_list.append(chat_id)

 #main.py
    def start(update, context):
   chat_id = update.message.chat_id
     first_name =update.message.chat.first_name
last_name = update.message.chat.last_name
username = update.message.chat.username
if chat_id in cp.chatid_list:
    print("chat_id : {} and firstname : {} lastname : {}  username {}". format(chat_id, first_name, last_name , username))
    context.bot.send_message(chat_id, 'Hi ' + first_name + '   Whats up?')
    update.message.reply_text( text=main_menu_message(),reply_markup=main_menu_keyboard())
else:
    print("WARNING: Unauthorized access denied for {}.".format(chat_id))
    update.message.reply_text('User disallowed.')

Upvotes: 0

Views: 1469

Answers (2)

Pronex
Pronex

Reputation: 359

As a cleaner alternative, you could consider using environment variables (e.g. with dotenv) to add configuration elements like the chat IDs (as strings, as noted by @CallMeStag).

That would remove the necessity of having to format and read a file for that purpose. In this case, you can have a .env file in the same directory with:

#.env file
# allowed ids - users allowed to use bot
ALLOWED_IDS = 12345678, 24567896

I'm assuming you're using python 3 and can use f-strings. So, you can throw your constants.py away and your main.py would look like below:

#main.py file
import os
from dotenv import load_dotenv
load_dotenv()

def start(update, context):
    chat_id = update.message.chat_id
    first_name = update.message.chat.first_name
    last_name = update.message.chat.last_name
    username = update.message.chat.username

if chat_id in os.getenv('ALLOWED_IDS'):
    print(f'chat_id : {chat_id } and firstname : {first_name } lastname : {last_name }  username {username }')
    context.bot.send_message(chat_id, f'Hi {first_name}, Whats up?')
    update.message.reply_text(text=main_menu_message(),reply_markup=main_menu_keyboard())

else:
    print(f'WARNING: Unauthorized access denied for {chat_id}.')
    update.message.reply_text('User disallowed.')

Finally, in case you want multiple functions to be "protected", you can use a wrapper as shown here.


Edit: added alternative local file types after OP's comment.

You could also store your allowed users in a JSON (ids.json):

{
    "allowed_users": [
        {
            "name": "john wick",
            "id": 1234567
        },
        {
            "name": "rick wick",
            "id": 2345738
        }
    ]
}

And then read the allowed IDs as follows:

import json

with open(r'./ids.json', 'r') as in_file:
    allowed_users = json.load(in_file)['allowed_users']
allowed_ids = [user['id'] for user in allowed_users]

OR, you could simply drop all the IDs into a text file (ids.txt), with one ID per line:

1234567
2345738

And then read them as follows:

allowed_ids = []
with open(r'./ids.txt', 'r') as in_file:
    for row in in_file:
        allowed_ids.append(int(row.strip()))

Finally, replace os.getenv('ALLOWED_IDS') from the above code snippet with allowed_ids.

Upvotes: 1

CallMeStag
CallMeStag

Reputation: 7020

My guess would be that the elements of chatid_list are strings because you read them from a text file, but chat_id is an integer. So you'd either have to convert chat_id to a string or the elements of chatid_list to integers.

Upvotes: 1

Related Questions