うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】Unity から Slack にスニペットを投稿する

hacchi-man.hatenablog.com

で画像投稿について書いてますが、スニペットは文字列を投げるだけなのでお手軽で、フォームに content を追加して送るだけです

using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
 
public static class SlackUtility
{
    public static IEnumerator PostSnippet(string token, string channelId, string snippet, string comment = "", string title = "")
    {
        var form = new WWWForm();
        form.AddField("token", token);
        form.AddField("channels", channelId);
        form.AddField("content", snippet);
        form.AddField("filename", "screenshot.png");
        form.AddField("filetype", "png");
        
        if (!string.IsNullOrEmpty(title)) 
            form.AddField("title", "title");
        if (!string.IsNullOrEmpty(comment)) 
            form.AddField("initial_comment", comment);
 
        var url = "https://slack.com/api/files.upload";
 
        var request = UnityWebRequest.Post(url, form);
        request.SendWebRequest();
         
        yield return new WaitUntil(() => request.isDone);
 
        if (request.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError(request.error);
            yield break;
        }
 
        var text = request.downloadHandler.text;
        // エラーでもJsonが返ってくるので中身を確認する
        var index = text.IndexOf("\"error\":", StringComparison.Ordinal);
        if (index > 0)
        {
            Debug.LogError(text);    
            yield break;
        }
         
        Debug.Log(text);
    }
}

実行結果

このように投稿できます