Keep Python Bot Tokens Safe with Environment Variables
A simple secret-handling workflow for bots deployed from Git or ZIP files.
A token in a Python file can leak through Git history, a shared ZIP, a pasted traceback or a screenshot. Environment variables let you separate code from credentials. They are not magic encryption, but they make accidental disclosure less likely when combined with restricted dashboard access and careful logging.
Read secrets at startup
Give each secret a clear name and fail early if it is missing. For example, read TELEGRAM_BOT_TOKEN before creating the bot client. Do not log its value. For local development, load a private .env file with an appropriate library or set the variable in your shell; add .env to .gitignore.
import os
token = os.environ.get("TELEGRAM_BOT_TOKEN")
if not token:
raise RuntimeError("TELEGRAM_BOT_TOKEN is not configured")
Configure the host
Enter the value in the host's secret or environment setting, save it and restart the bot so the new process receives it. A successful upload does not prove the variable was set. Check for the explicit missing-secret error, then test one real bot action. Avoid passing secrets as command-line arguments where they may appear in process listings.
If a token leaks
Rotate or revoke it with the issuing service first. Remove the token from current source and deployment settings, but remember that deleting a line from Git does not erase past commits. Replace the credential on the host, restart, and review logs or account activity for unexpected use. Give each bot its own token when possible to limit the impact of one leak.
Explore PyHost plans and deploy your Python code from the browser.
Explore hosting plans