【问题标题】:i want to write some text in .txt file with bot command (telegram bot)我想用 bot 命令(电报机器人)在 .txt 文件中写一些文本
【发布时间】:2021-12-07 04:17:41
【问题描述】:

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

我的问题是,我不知道如何从电报中添加用户。 我想做一个类似的命令:

/add_user george as admin

请帮帮我。

这是我的代码的一部分:

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

【问题讨论】:

    标签: python python-telegram-bot


    【解决方案1】:

    首先,您需要创建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))
    

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

    希望对你有用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-12
      • 1970-01-01
      • 2018-06-13
      • 2017-06-16
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多