Bot token undefined error when starting Telegram bot

I’m getting an error when I try to run my Telegram bot. The error says “Bot token is not defined” but I think I set it up correctly. I put my token in a .env file and I’m using os.getenv to read it.

My code:

import os
import telebot

BOT_TOKEN = os.getenv('BOT_KEY')
telegram_bot = telebot.TeleBot(BOT_TOKEN)

@telegram_bot.message_handler(commands=['start'])
def welcome_message(msg):
    telegram_bot.reply_to(msg, "Hello there!")
    
telegram_bot.polling()

Error I get:

Exception: Bot token is not defined

This is my first Telegram bot project. I’ve made Discord bots before and they worked fine. What am I doing wrong with the token setup?

Check if your Python script is actually finding the .env file. This happens a lot when the .env file sits in a different directory than your script. By default, load_dotenv() only looks in the current working directory. If your .env file is somewhere else, you’ll need to specify the path: load_dotenv(‘/path/to/your/.env’). After loading the variables, throw in a quick print(BOT_TOKEN) right after your os.getenv line to see if the token’s actually getting read. I’ve used this debugging trick tons of times when tokens show up empty even though the .env file looks fine.

The issue arises because os.getenv() alone cannot read values from your .env file; you need to load it using the python-dotenv package. First, make sure to install it via pip install python-dotenv. Then, at the beginning of your script, include the following lines:

from dotenv import load_dotenv
load_dotenv()

This will ensure that os.getenv('BOT_KEY') retrieves the correct token. Also, double-check that your .env file contains the line BOT_KEY=your_actual_token_here, ensuring there are no extra quotes or spaces. I faced a similar issue, and applying this solution resolved it immediately.

hey, just make sure ur .env file is named right and in the right folder. also, dont forget to install python-dotenv and load it properly like they said. should help with the issue!

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.