我正在尝试创建一个简单的 Slack 机器人。但是,在测试机器人是否可以工作时,我收到 SSL 证书错误。如果我将解决方法硬编码到脚本中,我就可以完成这项工作,但理想情况下我希望它准备好投入生产。
代码和错误代码如下。
代码
import os
import slack
import ssl
# Function to load environment variables from .env file
def load_env():
with open('.env', 'r') as file:
for line in file.readlines():
if line.startswith('SLACK_BOT_TOKEN'):
key, value = line.strip().split('=')
os.environ[key] = value
# Load environment variables
load_env()
token = os.getenv("SLACK_BOT_TOKEN")
# Function to post a message to Slack
def post_message():
try:
# Create a WebClient using the given token
client = slack.WebClient(token)
# Post a message to the 'test' channel
response = client.chat_postMessage(channel='test', text="Hello World!")
# Print the response
print(response)
except ssl.SSLCertVerificationError as e:
print("SSL Certificate Verification Failed:")
print(e)
# Optional: Add code here to send an alert or log the error for further investigation.
except Exception as e:
print("An unexpected error occurred:")
print(e)
# Check if the token is available
if token:
post_message()
else:
print("Token not found.")
错误代码
<urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1002)>
我已经更新了我的电脑,安装了证书,进入我的互联网设置并检查了 SSL 和 TSL 是否已启用;但仍然没有积极的结果。
我认为你需要在通话中使用 ssl 上下文
见 https://stackoverflow.com/a/70853605/22187484
import ssl
import certifi
ssl_context = ssl.create_default_context(cafile=certifi.where())
client = slack.WebClient(token=token, ssl=ssl_context)
我的谷歌搜索是
python slack.WebClient ssl