Skip to content
← Back to Community
How to use environment variables with Python?
Profile icon
G1zmotronn

Hi guys, so I'm working on a Discord bot for one of my projects. I'm using the environment variables feature in Repl.it to keep my tokens safe. The file for the bot is called DiscoBot.py but I'm receiving errors when running it:

import os import discord import random client = discord.Client() @client.event async def on_ready(): print("We have logged in as {0.user}".format(client)) TOKEN = os.environ['discotoken'] client.run(TOKEN)

I even tried using os.getenv:

import os import discord import random client = discord.Client() @client.event async def on_ready(): print("We have logged in as {0.user}".format(client)) TOKEN = os.getenv['discotoken'] client.run(TOKEN)``` In both cases I get this error: ```bash ~/GeminiStationClient$ python Discobot.py Traceback (most recent call last): File "Discobot.py", line 11, in <module> TOKEN = os.environ['discotoken'] File "/usr/lib/python3.8/os.py", line 675, in __getitem__ raise KeyError(key) from None KeyError: 'discotoken' ~/GeminiStationClient$ python Discobot.py Traceback (most recent call last): File "Discobot.py", line 11, in <module> TOKEN = os.getenv['discotoken'] TypeError: 'function' object is not subscriptable

What am I doing wrong?

Answered by Coder100 [earned 5 cycles]
View Answer
Voters
Profile icon
G1zmotronn
Comments
hotnewtop
Profile icon
Coder100

Have you checked out the docs?
Because you are using the functions incorrectly:
https://docs.replit.com/repls/secrets-environment-variables#secrets-environment-variables

Profile icon
G1zmotronn
Profile icon
Coder100
Profile icon
FishballNooodle

Hi its is token = os.getenv("discotoken")
There are also other ways to do this:
token = os.environ["discotoken"]

Sometimes both of these won't work cos Replit is autistic

Anyways we can still use ReplDB since its private and unique for every Repl.

from replit import db token = db["discotoken"]

Before this works:

  • Go to Shell (Bottom Right, next to Console Tab)
  • follow these commands
    python3
    from replit import db
    db["discotoken"] = <put token here>

Should all work now