4

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"
fnaimi
  • 51
  • 1
  • 4

4 Answers4

4

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

From the docs (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()

Mike Scotty
  • 10,530
  • 5
  • 38
  • 50
0

I usally use YAML files but it would appear you should use os.getenv("SLACK_TOKEN") not os.environ["SLACK_TOKEN"] according to pip python-dotenv

Jxck
  • 3
  • 1
0

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----

Zeesna
  • 1
  • 1
0

I had same problem and even with updating the .env file it didn't help and the code was not reading the new variable, so I tried cml and use SET NAMEOFVARIABLE = VALUE , it worked

  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/33647965) – import random Jan 23 '23 at 03:24