【问题标题】:How to hide bot Telegram token with gitignore?如何用 gitignore 隐藏 bot Telegram 令牌?
【发布时间】:2019-04-20 19:00:49
【问题描述】:

在公共领域的 GitHub 上是我的电报机器人的代码,我的令牌在哪里。我想隐藏它,我该怎么办?我知道这应该用 gitignore 来完成

import telebot
import time
TOKEN = "872521057:AAF2Kx4Y3WC-cs................"
bot = telebot.TeleBot(TOKEN)
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
    bot.reply_to(message, "Hello")
@bot.message_handler(func=lambda m: True)
def echo_all(message):
    bot.reply_to(message, message.text)
bot.polling(none_stop=True)

【问题讨论】:

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


    【解决方案1】:

    更新

    如果您想部署到 Heroku,更好的方法是使用环境变量。

    变化:

    TOKEN = None
    
    with open("token.txt") as f:
        TOKEN = f.read().strip()
    

    到:

    import os
    
    TOKEN = os.environ["TOKEN"]
    

    然后,使用命令heroku config:add TOKEN=…设置环境变量。

    要在本地运行您的机器人,请使用:

    TOKEN=… python3 bot.py
    

    希望对你有帮助!


    原答案

    .gitignore 不能用于忽略代码行,只能用于忽略整个文件。

    但是,您可以从文件中读取令牌,并将那个放入您的.gitignore

    我会这样做:

    1. 为了安全起见,首先通过将/revoke 命令发送到@BotFather on Telegram 来撤销您的令牌。

    2. token.txt 放入您的.gitignore 并提交。

    3. 在您的机器人代码旁边创建一个文件 token.txt 并将您的 里面有新的令牌。

    4. 之后,将TOKEN = … 的行更改为:

      TOKEN = None
      
      with open("token.txt") as f:
          TOKEN = f.read().strip()
      

      这将读取您之前创建的token.txt 文件,并存储 它在 TOKEN 变量中,因此您的令牌保持私有。

    【讨论】:

    • 请解释一下如何将 token.txt 放入 .gitignore 中?感谢您的回答)
    • @ИванИванов 您可以将token.txt 附加到您的.gitignore 的末尾。
    • 我在 Heroku 上部署了我的机器人,并且 Heroku 在日志中写道 FileNotFoundError: [Errno 2] No su h file or directory: 'token.txt'
    • @ИванИванов 我更新了我的答案。我希望这有帮助,它应该工作。 :)
    猜你喜欢
    • 2016-10-20
    • 2016-12-06
    • 2015-12-10
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多