pythondiscord.pybotskeyerrorenv-file

Getting Discord Bot Token from Env File in Python


I have a folder which has a few files: Procfile, requirements.txt, main.py and secret.env. Secret.env has one line of code in it:

TOKEN = "my bot token"

"My bot token" is my Discord token. Now, in main.py, I want to get access to this token from the environment file so I can run my bot. However, I'm not very sure how to do it. I imported os and tried the following:

bot.run(os.environ['TOKEN'])

However, I get a KeyError when running this. Anyone know how to resolve this? I'm using VSCode and am on a Windows device. Do I need to use the dotenv module?


Solution

  • You are close to solution :)

    import os
    from dotenv import load_dotenv
    # ...
    bot.run(os.getenv("TOKEN"))
    
    

    Be sure to name your file ".env" and just that, and that it is in the same folder as your .py file.

    EDIT : some editors don't manage that ".env" file, prefer to run it in console directly.