On GitHub in the public domain is the code of my telegram bot, where is my token. I want to hide it, what should I do? I know that this should be done with 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)
If you want to deploy to Heroku, a better approach would be to use an environment variable.
Change:
TOKEN = None
with open("token.txt") as f:
TOKEN = f.read().strip()
to:
import os
TOKEN = os.environ["TOKEN"]
Then, use the command heroku config:add TOKEN=…
to set the environment variable.
To run your bot locally, use:
TOKEN=… python3 bot.py
I hope that helps!
.gitignore
cannot be used to ignore lines of code, only whole files.
However, you could read the token from a file, and put that in your .gitignore
.
Here's how I'd do it:
To be safe, first revoke your token by sending the /revoke
command to @BotFather on Telegram.
Put token.txt
in your .gitignore
and commit.
Create a file token.txt
next to your bot code and put your
new token in it.
After that, change the the line that says TOKEN = …
to:
TOKEN = None
with open("token.txt") as f:
TOKEN = f.read().strip()
This will read the token.txt
file you created earlier, and store
it in the TOKEN
variable, so your token stays private.