【问题标题】:Send Message to Slack Message to Slack Channel through Slack Chat.Post Message API?通过 Slack Chat.Post Message API 将消息发送到 Slack 消息到 Slack 频道?
【发布时间】:2022-01-12 19:05:22
【问题描述】:

尽管有人问过这个问题。我正在尝试通过 slack chat.post 消息 api this link 向 slack 频道发送消息 但是消息没有发送到频道,我正在收到

successfully completed post_reports_to_slack and status code 200

代码是:

import requests
def post_image():
    url="https://slack.com/api/chat.postMessage"
    data = {

        "token": "xoxb-7701412070-tooken",
        "channels": ['#channel_name'],
        "text":"Message to send", 
    }

    response = requests.post(
         url=url, data=data,
         headers={"Content-Type": "application/json"})

    #response = requests.post(url=url, data=payload, params=data, files=file_upload)
    if response.status_code == 200:
        print("successfully completed post_reports_to_slack "
                      "and status code %s" % response.status_code)
    else:
        print("Failed to post report on slack channel "
                      "and status code %s" % response.status_code)


post_image()

我也尝试使用 post file api 发送文件,它工作正常。使用 webhooks 也工作正常。但我想通过 chat.post 消息 API 发送消息。

【问题讨论】:

    标签: python api slack slack-api


    【解决方案1】:

    我建议使用 Slack SDK。 Slack 有一个适用于 Python here 的 SDK。我在您的代码中注意到的第一件事是键 channels 应该是 channel 并且它应该是一个字符串。经过一些测试,Slack 似乎总是返回 200 并可能出现错误。最终代码应该是:

    import requests
    def post_image():
        url="https://slack.com/api/chat.postMessage"
        data = {
    
            "token": "xoxb-7701412070-tooken",
            "channel": 'C1234567890',
            "text": "Message to send", 
        }
    
        response = requests.post(
             url=url, data=data,
             headers={"Content-Type": "application/x-www-form-urlencoded"})
    
        #response = requests.post(url=url, data=payload, params=data, files=file_upload)
        if response.status_code == 200:
            print("successfully completed post_reports_to_slack "
                          "and status code %s" % response.text)
        else:
            print("Failed to post report on slack channel "
                          "and status code %s" % response.status_code)
    
    
    post_image()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-20
      • 1970-01-01
      • 2021-11-08
      • 2020-08-15
      • 2018-12-30
      • 2016-05-04
      • 1970-01-01
      • 2019-09-28
      相关资源
      最近更新 更多