SlackIntegration.cs 1.94 KB
using UnityEngine;
using System.Collections;
using WebKit;

public class SlackIntegration : MonoBehaviour
{
    // Incoming WebHook url. Get this by configuring a new Incoming WebHook integration in the slack services page of their site
    public string webhookUrl;
    // Optional notification
    public string optionalMessage;

    void Awake()
    {
        Application.logMessageReceived += Application_logMessageReceived;
        DontDestroyOnLoad(this);
	}

    void Application_logMessageReceived(string condition, string stackTrace, LogType type)
    {
        if (condition.Contains("CMSRequest")) return;

        if (type == LogType.Error || type == LogType.Exception)
            Post(type.ToString() + ": "  + condition + "\n" + stackTrace, type);
    }

    private void Post(string message, LogType type)
    {
        Request request = new Request();
        request.url = webhookUrl;
        request.method = RequestMethod.POST;
        
        string emoji = ":impressed:";
        string botname = "Information";
        switch (type)
        {
            case LogType.Error:
                botname = "Error";
                emoji = ":cold_sweat:";
                break;
            case LogType.Exception:
                botname = "Exception";
                emoji = ":scream:";
                break;
        }

        string postMessage = "Message recieved from app:\n*" + Application.companyName + " - " + Application.productName + "*\n" + message;
        if (!string.IsNullOrEmpty(optionalMessage))
            postMessage = optionalMessage + "\n" + postMessage;

        var postData = new System.Collections.Generic.Dictionary<string, object>()
        {
            {"username", botname},
            {"icon_emoji",emoji},
            {"text", postMessage},
        };

        request.data = postData;
        request.Send();
    }

    void OnDestroy()
    {
        Application.logMessageReceived -= Application_logMessageReceived;
    }
}