How do I resolve `raise KeyError(key) from None KeyError: [SLACK_BOT_TOKEN_HERE]` while uploading file to slack using python?

Viewed 1469

Here is my code to send a pdf file to my slack workspace. But it produces error.

client = WebClient(token=os.environ[SLACK_BOT_TOKEN])

try:
    filepath = "./output.pdf"
    response = client.files_upload(channels='#mychannelid_here', file=filepath)
    assert response["file"]  # the uploaded file
except SlackApiError as e:
    # You will get a SlackApiError if "ok" is False
    assert e.response["ok"] is False
    assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
    print(f"Got an error: {e.response['error']}")

Error is :

raise KeyError(key) from None KeyError: SLACK_BOT_TOKEN_HERE

Thanks in advance for help !

2 Answers

You better use getenv with a default (if it makes sense).

import os

SLACK_BOT_TOKEN = 'SLACK_BOT_TOKEN'
DEFAULT_SLACK_BOT_TOKEN_VALUE = 'Hello Slack'
token = os.getenv(SLACK_BOT_TOKEN, DEFAULT_SLACK_BOT_TOKEN_VALUE)
print(token)

You are trying to refer to a variable SLACK_BOT_TOKEN but your code does not define a variable with this name.

Probably you mean token=os.environ["SLACK_BOT_TOKEN"] where the literal string SLACK_BOT_TOKEN is looked up in the environment (so you should have an environment variable with this name, and now you are looking it up).

A common arrangement is to store the token in a place where it is not saved in your code (so kept out of your git repository etc) and require you to set it in the environment before running Python. So, for example

bash$ secrettoken="your token here"
bash$ export secrettoken
bash$ python -c 'import os; print(os.environ["secrettoken"])'
your token here

This works similarly (though not exactly the same) on Windows, with the usual different syntax and weird corner cases.

Related