-1

first of all, i make a telegram bot using python 3.10 with telegram.ext as module. i make a certain command can be run only with certain role. thus, i make a txt file for each role. so that command for example "/add_user" can only be run with "admin" role from admin.txt.

my problem is, i dont know how to add user from telegram. i want to make a command like:

/add_user george as admin <- this command will write george on admin.txt /add_user johnson as user <- this command will write johnson on user.txt

please help me.

this is part of my code:

from telegram.ext import *
import os

API_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

def start_command(update, context):
    update.message.reply_text('Hello there! I\'m a very useful bot. What\'s up?')
    
def abs_command(update, context):
    update.message.reply_text('ABS command is started . .')
    os.system('python abs.py')
    update.message.reply_text('ABS command is Finished . .')    
    
def add_user_command(update, context):
    # i dont know how to make command here  
    
# Run the programme
if __name__ == '__main__':
    updater = Updater(API_KEY, use_context=True)
    dp = updater.dispatcher

    # User List
    user = open('./userlist/user.txt', 'r').read()
    admin = open('./userlist/admin.txt', 'r').read()
    
    dp.add_handler(CommandHandler('start', start_command, Filters.user(username=user)))
    dp.add_handler(CommandHandler('start', start_command, Filters.user(username=admin)))    
    dp.add_handler(CommandHandler('abs', abs_command, Filters.user(username=absensak)))
    dp.add_handler(CommandHandler('add_user', add_user_command, Filters.user(username=admin)))
    
    # Run the bot
    updater.start_polling(1.0)
    updater.idle()

1 Answers1

0

First of all, you need to create the admin.txt file. I suggest storing the chat.id of the admin, not the username nor the username (can be changed).

So before all the code I'll add

with open("admin.txt") as f:
    lines = f.readlines()
admin = [int(i.strip()) for i in lines]

so you have your list of admin ids.

Then you can add

def add_user_command(update, context):
    # message should contain the id of the person you'd like to promote to admin. 
    # You can't get the id from username or the name unless you have stored it before in a db
    if update.message.chat.id not in admin: 
         context.bot.send_message(update.message.chat.id, "You have no power here!")
         return None
    mex = int(update.message.text[len("/add_user"):].strip())
    admin.append(mex)
    context.bot.send_message(mex, "Congratulation you've been promoted to admin")
    with open("admin.txt", "w") as f:
        f.write('\n'.join(admin))

If you have a db in which you stare updated usernames/names you can query that and, instead of sending the bot the id, you can send the username. My suggestion is always to save the admin ID, and not the username.

Hope it works for you