LoginSignup
3

More than 3 years have passed since last update.

C#でSlackへWebSocket接続(RTM)

Posted at

Slack Platform: Community | Slackでリンクされている
Inumedia/SlackAPI: .NET Implementation of the Slack team communication platform API.
を使う。

.nugetはzipなのでそのまま解凍して.dllを取得できる。(GitHubのリリースよりあたらしいみたい)

OAuthトークンはアプリを作った画面のもので良い。

https://api.slack.com/apps
で見れる・作れるアプリにBotを追加して、
https://api.slack.com/apps/{AppsID}/bots
のトークンを使う。

有象無象のアプリには使わないので、URLを使ったcodeの取得や認証は必要なし。(というかそれで取得した結果が設定画面上で見れるOAuth Tokenと一緒)

メッセージをPostするならSlack APIが使うNewtonsoft.Json.dll を取得してリンクする必要があるが、
バージョンをあわせるために現時点での最新の12ではなく9(9.0.1)のdllを取得する。 GitHubから。

サンプルのコードが非常に罠で、


        SlackSocketClient client = new SlackSocketClient("tokeen");
        client.Connect((connected) =>{
            Console.WriteLine("cone");
            // This is called once the client has emitted the RTM start command
            //clientReady.Set();

        }, () =>{
            Console.WriteLine("cone2");
            // This is called once the RTM client has connected to the end point
        });

と書いてもコールバックに入らない。
つまりはWebSocketの通信が確立されない。

これはSlackSocketClientのbaseのSlackClientConnectを実行しているからで、
Websocketのための通信には

client.ConnectSocket(() => {
    Console.WriteLine("ConnectSocket");
});

こっちを使う。

client.OnMessageReceivedなどはConnectSocketによって得られるSlackSocket underlyingSocket;で行われる。

…が、Windows 7では.Net FrameworkがWebSocketにデフォルト対応していないので、結局使えないのである。

System.Net.WebSocketsはWindows 7では動かない - はつねの日記

延長サポートの終了こそ2020年1月14日ということでまだ先ですが

半年切りました…

使いたいなら自分でWebsocket用ライブラリに差し替えるコードを書いてビルドするしかないかなあ。

参考

SlackでOAuth2を利用したときのメモ - Qiita

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
3