0

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?

Anonymous
  • 21
  • 6

1 Answers1

1

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.

pluckplk
  • 131
  • 8
  • 1
    Hello, I tried this, but I now get a new error, which says "Attribute Error: 'NoneType' object has no attribute 'strip'. Edit: fixed it by importing load_dotenv from dotenv module and running that. – Anonymous Sep 26 '22 at 23:02
  • 1
    You're right, you need to import os and dotenv both to use .env file. – pluckplk Sep 26 '22 at 23:59