在公共(public)领域的 GitHub 上是我的电报机器人的代码,我的 token 在哪里。我想隐藏它,我该怎么办?我知道这应该用 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)
最佳答案
更新
如果您想部署到 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
不能用于忽略代码行,只能忽略整个文件。
但是,您可以从文件中读取 token ,并将该放入.gitignore
中。
我的做法是这样的:
为了安全起见,请首先通过将
/revoke
命令发送到 @BotFather on Telegram 来撤销您的 token 。 .将
token.txt
放入.gitignore
中并提交。在您的机器人代码旁边创建一个文件
token.txt
并将您的 其中有新 token 。之后,将
TOKEN = ...
行更改为:TOKEN = None with open("token.txt") as f: TOKEN = f.read().strip()
这将读取您之前创建的
token.txt
文件,并存储 它位于TOKEN
变量中,因此您的 token 保持私有(private)。
关于python-3.x - 如何使用 gitignore 隐藏机器人 Telegram token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55776767/