LoginSignup
17

More than 5 years have passed since last update.

UnityからSlack投稿する

Last updated at Posted at 2017-04-03

こんな感じでUnityからSlackに投稿することができます。

おおまかな流れは次の通りです。

  • Webhook URLを取得する
  • Unity上でURLにJSON形式の文字列を投げる

Webhook URLを取得する

Slack API (Incoming Webhooks) が簡単すぎた

この記事を参考にして、Webhook URLを取得してください。簡単にできます。

Unity上でURLにJSON形式の文字列を投げる

以下のようなコードを書いてください

UnityでGET, POST通信(+JSON)を参考にしました。

SlackTest.cs

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text;

public class SlackTest : MonoBehaviour {
    string url = "Webhook URLをこぴぺしてください";

    public static SlackTest Instance = null;

    void Awake ()
    {
        if (Instance == null) {
            Instance = this;
            DontDestroyOnLoad(this.gameObject);
        } else {
            Destroy(this.gameObject);
        }
    }

    // 文字を投稿する
    public void PostText (string input)
    {
        Post-date data = new PostData ();
        data.text = input;
        data.username = "username";
        string json_data = JsonUtility.ToJson(data);
        StartCoroutine(Post(url,json_data));
    }

    IEnumerator Post (string url,string json_data) {

        Dictionary<string,string> header = new Dictionary<string,string>();
        // jsonでリクエストを送るのへッダ例
        header.Add ("Content-Type", "application/json; charset=UTF-8");

        byte[] postBytes = Encoding.UTF8.GetBytes (json_data);

        // 送信開始
        WWW www = new WWW (url, postBytes, header);
        yield return www;

        // 成功
        if (www.error == null) {
            Debug.Log("Post Success");
        }
        // 失敗
        else{
            Debug.Log("Post Failure");          
        }
    }

}

// レスポンスのJSONを格納するクラス
[Serializable]
class PostData{
    public string text; // 投稿内容
    public string username; // user名
}

あとは、好きな場所で

SlackTest.Instance.PostText("送信したい文字");

とコードを書けば送信できます!

参考Webサイト

Slack API (Incoming Webhooks) が簡単すぎた

UnityでGET, POST通信(+JSON)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17