简体   繁体   English

使用 python 将文件上传到 slack 时,如何从 None KeyError: [SLACK_BOT_TOKEN_HERE]` 解决 `raise KeyError(key)`?

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

Here is my code to send a pdf file to my slack workspace.这是我将 pdf 文件发送到我的松弛工作区的代码。 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从 None KeyError 引发 KeyError(key): SLACK_BOT_TOKEN_HERE

Thanks in advance for help !预先感谢您的帮助!

You better use getenv with a default (if it makes sense).您最好将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)

You are trying to refer to a variable SLACK_BOT_TOKEN but your code does not define a variable with this name.您正在尝试引用变量SLACK_BOT_TOKEN但您的代码未定义具有此名称的变量。

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).可能您的意思是token=os.environ["SLACK_BOT_TOKEN"]在环境中查找文字字符串SLACK_BOT_TOKEN (因此您应该有一个具有此名称的环境变量,现在您正在查找它)。

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.一个常见的安排是将令牌存储在一个没有保存在你的代码中的地方(因此远离你的git存储库等),并要求你在运行 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.这在 Windows 上的工作方式类似(虽然不完全相同),但通常具有不同的语法和奇怪的极端情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM