我想用 bot 命令(电报机器人)在 .txt 文件中写一些文本

i want to write some text in .txt file with bot command (telegram bot)

首先,我使用 python 3.10 和 telegram.ext 作为模块制作了一个电报机器人。 我让某个命令可以 运行 只具有特定的作用。因此,我为每个角色制作了一个 txt 文件。因此,例如“/add_user”的命令只能是 运行,具有来自 admin.txt.

的“admin”角色

我的问题是,我不知道如何从电报中添加用户。 我想发出这样的命令:

/add_user george as admin <- 此命令将在 admin.txt 上写入 george /add_user johnson as user <- 此命令将在 user.txt

上写入 johnson

请帮助我。

这是我的代码的一部分:

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

首先,您需要创建 admin.txt 文件。我建议存储管理员的 chat.id,而不是用户名或用户名(可以更改)。

所以在我要添加的所有代码之前

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

所以你有你的管理员 ID 列表。

然后你可以添加

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

如果您有一个数据库,您可以在其中查看更新 usernames/names 您可以查询它,而不是向机器人发送 ID,您可以发送用户名。我的建议是始终保存管理员 ID,而不是用户名。

希望对你有用