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.')
2
Answers
My guess would be that the elements of
chatid_list
are strings because you read them from a text file, butchat_id
is an integer. So you’d either have to convertchat_id
to a string or the elements ofchatid_list
to integers.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: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:
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
):And then read the allowed IDs as follows:
OR, you could simply drop all the IDs into a text file (
ids.txt
), with one ID per line:And then read them as follows:
Finally, replace
os.getenv('ALLOWED_IDS')
from the above code snippet withallowed_ids
.