I’m getting an error saying ‘Bot token is not defined’ when trying to run my Telegram bot. This is my second attempt at building a bot after working with Discord bots previously.
The error happens right when polling starts. I’ve stored my token in a .env file and I’m using os.getenv to access it. The bot should respond to /start command with a greeting message. I’ve followed several guides but can’t figure out why the token isn’t being recognized properly.
os.getenv() can’t read .env files automatically; you need to use python-dotenv to load them first. Install it by running pip install python-dotenv. Then, add these lines at the top of your script before importing telebot:
from dotenv import load_dotenv
load_dotenv()
Alternatively, you can export the variable in your terminal using export BOT_KEY=your_token_here before executing the script. I faced a similar issue when switching from other frameworks, and using python-dotenv simplifies the process while keeping your tokens secure.
check if your .env file is in the same directory as your python script. also make sure there’s no spaces around the = sign in your .env file like BOT_KEY=your_token not BOT_KEY = your_token. this got me before
Add a print statement to see what os.getenv() actually returns. Put print(f"Token: {BOT_TOKEN}") right after the BOT_TOKEN line - this’ll show if it’s None or has weird characters. I had this same issue and my token was loading but had invisible whitespace that broke auth. If it prints None, your environment variable isn’t loading. If it shows the token but still fails, try .strip() on it to remove trailing whitespace from your .env file.