Steps on how to setup environment variable for FCC Python Bot Tutorial

Read this post if you are watching the Code a Discord Bot tutorial by FCC and don’t know how to setup your environment variables in replit.

A few months ago, Replit changed how to add environment variables.
The suggestions from the video will not work.

Here is what you do.

Use this starter code from discord.py docs

This is the exact same code from the video.
You can just copy it.

import discord

client = discord.Client()

@client.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  if message.content.startswith('$hello'):
    await message.channel.send('Hello!')

client.run('your token here')

Now let’s setup the environment variables.

Step 1:
Click the lock icon that says secrets
click on secrets tab

Step 2:
Add your key and value to the secrets tab and click add new secret.
My suggestion: Just use TOKEN for the key name.
Keep it simple for now.

Step 3:
Click insert to add import os to the top of your file
click import os

Step 4:
Click insert to add your environment variable to the bottom of your code
insert your token

Now we are going to change this line client.run('your token here')

Step 5:
Add the my_secret variable to your client.run.

client.run(my_secret)

Here is the complete code to get your bot up and running.
If you are successful then you should see this message in the console

import os
import discord

client = discord.Client()

@client.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  if message.content.startswith('$hello'):
    await message.channel.send('Hello!')


my_secret = os.environ['TOKEN']
client.run(my_secret)

If you are still getting errors, make a new post in the forum and tell us what the error message is and provide your code/replit link.

Hopefully that will help some people. :grinning:

1 Like