【问题标题】:Limit the access of telegram bot through Chat ID通过 Chat ID 限制 Telegram bot 的访问
【发布时间】:2022-01-20 17:17:48
【问题描述】:

我已附上代码。我希望从本地机器上的文本文件中访问 c​​hat_id。

#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.')

【问题讨论】:

  • 嗨。你到底卡在哪里了?请查看this article 以及 python-telegram-bots ask-right 页面
  • @CallMeStag - 执行 Main.py 文件时。输出始终是用户不允许的。

标签: python-3.x telegram telegram-bot python-telegram-bot


【解决方案1】:

我的猜测是chatid_list 的元素是字符串,因为您从文本文件中读取它们,但chat_id 是一个整数。因此,您要么必须将 chat_id 转换为字符串,要么将 chatid_list 的元素转换为整数。

【讨论】:

    【解决方案2】:

    作为一种更简洁的替代方法,您可以考虑使用环境变量(例如使用dotenv)来添加配置元素,例如聊天 ID(作为字符串,如 @CallMeStag 所述)。

    这将消除为此目的而必须格式化和读取文件的必要性。在这种情况下,您可以在同一目录中拥有一个 .env 文件:

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

    我假设您使用的是 python 3 并且可以使用 f-strings。 所以,你可以把你的 constants.py 扔掉,你的 main.py 会如下所示:

    #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.')
    

    最后,如果您希望“保护”多个函数,您可以使用包装器,如 here 所示。


    编辑:在 OP 的评论之后添加了替代的本地文件类型。

    您还可以将允许的用户存储在 JSON (ids.json) 中:

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

    然后读取允许的ID如下:

    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]
    

    或者,您可以简单地将所有 ID 放入一个文本文件 (ids.txt),每行一个 ID:

    1234567
    2345738
    

    然后阅读如下:

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

    最后,将上述代码 sn-p 中的os.getenv('ALLOWED_IDS') 替换为allowed_ids

    【讨论】:

    • 我已经实现了这个方法。我想添加 100 个聊天 ID,我希望从笔记本电脑上的文本文件中访问 c​​hat_id。
    • 好的,现在我了解了您的环境。编辑以显示建议的实现。还添加了一个 JSON 替代方案,它允许使用名称而不只是 ID 进行某种用户管理/映射。
    猜你喜欢
    • 2020-10-09
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2022-06-21
    • 1970-01-01
    相关资源
    最近更新 更多