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

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

这是我将 pdf 文件发送到我的松弛工作区的代码。但它会产生错误。

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']}")

错误是:

raise KeyError(key) from None KeyError: SLACK_BOT_TOKEN_HERE

在此先感谢您的帮助!

您正在尝试引用一个变量 SLACK_BOT_TOKEN 但您的代码没有定义具有该名称的变量。

可能你的意思是 token=os.environ["SLACK_BOT_TOKEN"] 在环境中查找文字字符串 SLACK_BOT_TOKEN 的地方(所以你应该有一个具有这个名称的环境变量,现在你正在查找它)。

一种常见的安排是将令牌存储在代码中未保存的位置(因此不保存在 git 存储库等中)并要求您在 [= 之前​​在环境中设置它25=] Python。所以,例如

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

这在 Windows 上的工作方式类似(尽管不完全相同),但语法通常不同,而且极端情况也很奇怪。

您最好使用带有默认值的 getenv(如果有意义的话)。

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)