LoginSignup
5
4

More than 5 years have passed since last update.

RailsでTypetalkのbotから通知を受け取る方法

Last updated at Posted at 2017-07-11

RailsでTypetalkから通知を受け取る

Typetalkというチャットアプリからトピックの全ての発言をbotを通じてサーバー側に送信します。
Typetalkのapiは、トピックの先頭200件とか投稿を取得できないので、botを設置することで全件抜け漏れなく投稿情報を取得できます。
botは各トピックごとに設置します。

botの設置

スクリーンショット 2017-07-12 0.16.47.png

上記のように設定をおこない、webhookの使用をチェック
webhook先のurlはドメイン/receiveにしておく
これで、誰かがトピックで発言したら、webhook先にjsonデータが送信されます。
受信するjsonの形式は、公式リファレンスを参考ください。

webhookについて
https://developer.nulab-inc.com/ja/docs/typetalk/webhook/

ソースコード

controllerには、下記のように書きます。

topics_controller.rb
def receive
    # 読み込み時に一度パースが必要
    json_request = JSON.parse(request.body.read)

    # コンソールに受信したjsonを表示
    p "json_request => #{json_request}"

    p "messageのid:#{post["post"]["id"].to_s}"
    p "message本文:#{post["post"]["message"].to_s}"
    p "accountの登録ネーム:#{post["post"]["account"]["name"].to_s}"
    p "accountの実際の表示ネーム:#{post["post"]["account"]["fullName"].to_s}"
    p "messageの投稿時間:#{post["post"]["account"]["createdAt"].to_s}"
  end

ついでにroutes.rbも追加しておきましょう

routes.rb
  post 'receive', to: 'topics#receive'

結果

投稿

実際に投稿したら、こんな感じです。
スクリーンショット 2017-07-12 0.40.17.png

Typetalkからbotを通じて、webhookが実行します。
下記が投稿時のログです。

"json_request => {\"topic\"=>{\"id\"=>41429, \"name\"=>\"api test全体\", \"isDirectMessage\"=>false, \"lastPostedAt\"=>\"2017-07-11T15:34:13Z\", \"createdAt\"=>\"2017-04-12T11:35:25Z\", \"updatedAt\"=>\"2017-04-12T11:35:25Z\"}, \"post\"=>{\"id\"=>10019445, \"topicId\"=>41429, \"replyTo\"=>nil, \"message\"=>\"testです\", \"account\"=>{\"id\"=>47124, \"name\"=>\"leokun0210\", \"fullName\"=>\"テストアカウント2\", \"suggestion\"=>\"テストアカウント2\", \"imageUrl\"=>\"https://typetalk.in/accounts/47124/profile_image.png?t=1499596169245\", \"isBot\"=>false, \"createdAt\"=>\"2017-07-09T10:20:04Z\", \"updatedAt\"=>\"2017-07-11T15:04:03Z\"}, \"mention\"=>nil, \"attachments\"=>[], \"likes\"=>[], \"talks\"=>[], \"links\"=>[], \"createdAt\"=>\"2017-07-11T15:34:13Z\", \"updatedAt\"=>\"2017-07-11T15:34:13Z\"}, \"mentions\"=>[], \"exceedsAttachmentLimit\"=>false, \"directMessage\"=>nil}"
"messageのid:10019445"
"message本文:testです"
"accountの登録ネーム:leokun0210"
"accountの実際の表示ネーム:テストアカウント2"
"messageの投稿時間:2017-07-09T10:20:04Z"

最後

需要はなさそうな記事だなぁ。。。

5
4
0

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
5
4