memomem

備忘録・メモ置き場

Slack bots RTMを使用してUnityと連携

github.com

Examples · Inumedia/SlackAPI Wiki · GitHub

ManualResetEventSlim clientReady = new ManualResetEventSlim(false);
SlackSocketClient client = new SlackSocketClient(YOUR_AUTH_TOKEN);
client.Connect((connected) =>{
    // This is called once the client has emitted the RTM start command
    clientReady.Set();
}, () =>{
    // This is called once the RTM client has connected to the end point
});
client.OnMessageReceived += (message) =>
{
    // Handle each message as you receive them
};
clientReady.Wait();

サンプルそのままUnityへ持ってきでうごく。

つまずいたところとして、Slackのbotの設定。

初めはSlack appのbotを試していたが、RTMは廃止されるようで動かない。

Add Apps to Slack | Apps and Integrations | Slack App Directory より「bots」を検索すると、「Connect a bot to the Slack Real Time Messaging API.」の文字が。これを使用すると上記のSlackAPI で問題なく動作。

動作としてはtokenで接続し成功するとwebsocketのwssアドレスが返ってくる。それを用いてwebsocket通信を行っている。

public void SendMessage(Action<MessageReceived> onSent, string channelId, string textData, string userName = null)

でUnityからSlackへの投稿もできるようだが、channelId はチャンネル名ではなく、ブラウザ等で表示される時のIDとなる。

とはいえ、投稿のみであれば

light11.hatenadiary.com

を使う方が簡単。

参考

Slack Botの種類と大まかな作り方 - Qiita

RTMは廃止されEvent APIが推奨されていくようだが、応答用のサーバーが必要になるので個人的には使いにくい。

Slack App を作る際の参考

Slack で自動返信するサーバレスBOTを作りました - Qiita

api.slack.com

qiita.com

qiita.com

シンプルなSlash Commandというのもある。(コマンドを受けて任意のサーバーへ送信を行う)

qiita.com