Question: I'm trying to build a slackbot and retrieve the slack token from a separate .env file. When I run it, I get thrown an error that looks like this:

```
raise KeyError(key) from None
KeyError: 'SLACK_TOKEN'

```

The code for the bot (ShoppingListBot.py) is here:

```
import slack
import os
from pathlib import Path
from dotenv import load_dotenv

env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)

client = slack.WebClient(token=os.environ["SLACK_TOKEN"])

```

The code for the .env file (.env) is here:

```
SLACK_TOKEN="xoxb-1691324762768-1693412284260-RdP0ZQUaQxD9j9mtLlwfNMbD"

```

Answer: 
Instead of `os.environ["SLACK_TOKEN"]` you should use `os.getenv("SLACK_TOKEN")`.

From the [docs](https://docs.python.org/3/library/os.html#os.environ) (emphasis mine):

> 
> This mapping is captured the **first time the os module is imported**, typically during Python startup as part of processing site.py. **Changes** to the environment made after this time **are not reflected** in os.environ, except for changes made by modifying os.environ directly.
> 
> 
> 

Or use `override=True` in `load_dotenv()`
Not sure if you're still having this problem, but anyone else with this problem - this is how I solved it. note: *I am still learning*

I created a `.env` file in the same directory with the proper values, then wrote the following to 'app.py'

```
from http import client
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
import os
from dotenv import load_dotenv
from pathlib import Path

load_dotenv()
#loading from .env file that was made
SLACK_BOT_TOKEN = os.environ['SLACK_BOT_TOKEN']
SLACK_APP_TOKEN = os.environ['SLACK_APP_TOKEN']

app = App(token=SLACK_BOT_TOKEN)

if __name__ == '__main__':
    SocketModeHandler(app, os.environ['SLACK_APP_TOKEN']).start()

```

Before running, make sure that you go into your python install folder and run the install certificates command as well. Must be installed in order to successfully communicate with servers.

This was returned with a confirmation that the bolt app was running.

Hope this helps!

-----[Source](https://www.twilio.com/blog/how-to-build-a-slackbot-in-socket-mode-with-python)----