【问题标题】:How to post Slack formated message with local attachment?如何使用本地附件发布 Slack 格式的消息?
【发布时间】:2019-01-02 10:41:48
【问题描述】:

基本上我想将本地图像文件发布到 slack 中。该方法只接受 URL 参数,但我想传递文件的路径。有没有办法使用格式化的消息来实现这一点? 顺便说一下,我有这个网站的例子:

 public class SlackAttachment
    {
        public string fallback { get; set; }
...
        public string author_name { get; set; }
        public string image_url { get; set; }

    } 
public static void SendMessageToSlack()
        {

            string token= "myTokenHere";


            var sampleAttachment = new SlackAttachment[]

            {
                new SlackAttachment {

                    fallback = "this did not work",
                    text = "text here",
                    color = "0b7c1e",
                    pretext = "",
                    author_name = "myName",
                    author_icon =  @"https://i.imgur.com/02sddfQMt9p.png",
                    author_link = "",
                    title = "no title",
                    title_link = "Title link here",
                  //image_url = @"https://i.imgur.com/U9S0CDG.png",
                  // cannot replace this with 
                  //   C:\Users\Public\image.png

                    thumb_url = @"",
                    footer = "footer here",
                    footer_icon =  migrationIcon

                             },
        };

            var attachmentsJson = JsonConvert.SerializeObject(sampleAttachment);
            var data = new NameValueCollection();
            data["token"] = token;
            data["channel"] = channelName;
            data["as_user"] = "true";          
            data["text"] = "";
            data["attachments"] = attachmentsJson;

            var client = new WebClient();
            var response = client.UploadValues("https://slack.com/api/chat.postMessage", "POST", data);
            string responseInString = Encoding.UTF8.GetString(response);
            Console.WriteLine(responseInString);
        }

【问题讨论】:

    标签: c# image post slack slack-api


    【解决方案1】:

    要将本地图像文件附加到消息中,您需要先上传它,以便获得公共 URL。然后,您可以在邮件附件中使用该 URL。

    这适用于任何公共图像服务(例如imgur.com),您还可以使用任何 Slack 工作区作为公共图像文件的主机。

    查看this answer 了解详细信息,包括 C# 中的完整示例。

    【讨论】:

    • 谢谢。我对第一个示例更熟悉(聊天帖子消息)但是我在运行时收到此错误: System.NullReferenceException: 'Object reference not set to an instance of an object.' UploaderMessenger.SlackExample.SlackFileResponse.file.get 返回 null 这是产生错误的行: String imageUrl = fileResponse2.file.permalink_public;
    • 好吧至少有办法使用第二种方法只上传图片并获取url而不发布?
    • 当然。如果您不提供带有 file.upload 的频道,它将不会发布
    • 谢谢。当我尝试这样做时,您是否知道我为什么会收到此错误?见img:i.imgur.com/RalifhT.png
    • 至于错误处理程序我当然会添加它们。我只是在测试。非常感谢 。你真是个懒散的英雄!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 2016-03-29
    相关资源
    最近更新 更多