Python Slack bot只有在从Crontab运行时才被授权发布到通道

2024-05-23 13:37:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我已成功设置Slack bot,用于特定于消息的公共频道。但是,它只是拒绝在Linux crontab上工作,因为它显然是未经授权的(,尽管在crontab之外运行时获得了授权)

出于测试目的,我设置了一个非常简单的裸体脚本:

import sys
import os
from slack.web.client import WebClient

sys.stderr = open("slackbot_errorinfo.txt", "w")
sys.stout = open("slackbot_output.txt", "w")

print("Slackbot test printed info")
slack_client = WebClient(os.environ.get("SLACK_BOT_TOKEN"))
response = slack_client.chat_postMessage(channel="testing", text="slackbot test message")
print(response)

当我直接在终端中执行此脚本时,消息将成功传递到所需的空闲通道。例如,像这样:

python3 /home/Username/Desktop/slacktest.py

但是,我随后在crontab中使用完全相同的命令进行测试,例如:

33 12 03 01 * python3 /home/Username/Desktop/slacktest.py

在上述情况下,消息无法传递,我在"slackbot_errorinfo.txt"标准错误文件中收到以下错误:

"/home/Username/Desktop/slacktest.py", line 10, in <module>
    response = slack_client.chat_postMessage(channel="testing", text="slackbot test message")   File
"/home/Username/.local/lib/python3.6/site-packages/slack/web/client.py",
line 1077, in chat_postMessage
    return self.api_call("chat.postMessage", json=kwargs)   File "/home/Username/.local/lib/python3.6/site-packages/slack/web/base_client.py",
line 150, in api_call
    return self._sync_send(api_url=api_url, req_args=req_args)   File "/home/Username/.local/lib/python3.6/site-packages/slack/web/base_client.py",
line 248, in _sync_send
    additional_headers=headers,   File "/home/Username/.local/lib/python3.6/site-packages/slack/web/base_client.py",
line 377, in _urllib_api_call
    use_sync_aiohttp=False,   File "/home/Username/.local/lib/python3.6/site-packages/slack/web/slack_response.py",
line 194, in validate
    raise e.SlackApiError(message=msg, response=self) slack.errors.SlackApiError: The request to the Slack API failed. The
server responded with: {'ok': False, 'error': 'not_authed'}```

我不明白在普通命令行中执行脚本时如何授权bot,但在crontab中使用相同的脚本时,而不是

我已经证实:

  • 在这两种情况下使用的Python解释器/可执行文件是相同的(在普通命令行和crontab中都是/usr/bin/python3
  • os.environ.get("SLACK_BOT_TOKEN")的输出在这两种情况下给出相同的键

如果有人能够帮助解释这一点,我们将不胜感激


Tags: inpyclientwebhomeresponseliblocal