Search code examples
pythonslackslack-api

Slack API throwing KeyError with Slack Token


So I've been trying to make a slack bot and have the following code run to make sure everything is working fine, just been following a video, but VS Code is giving me a key error. I'm using a virtual environment, activated with the right libraries installed. I've used both slackclient and slack_sdk packages and I am still getting the same error. I have looked up similar questions and I have the most updated version of the libraries, installed and uninstalled multiple times to no avail. SLACK_TOKEN is in a .env file in the same directory. Any clue as to why I am getting this error?

import dotenv
import os
from slack_sdk import WebClient
from pathlib import Path
from dotenv import load_dotenv
import slack_sdk

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

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

Solution

  • Your code should work and it works for me. You should recheck your .env file one more time, maybe you have a typo or incorrect .env file format. And if I understand correctly your problem has nothing to do with Slack, the problem with dotenv loading. You can check it by outputting os.environ._data dict and checking the keys of this dict.