Node.jsとExpressを使用したChat
As the Programmable Chat API is set to sunset in 2022, we will no longer maintain these chat tutorials.
Please see our Conversations API QuickStart to start building robust virtual spaces for conversation.
Programmable Chat will no longer be available or supported after July 25, 2022. Instead, we'll be focusing on the next generation of chat: Twilio Conversations. Find out more about the EOL process here.
If you're starting a new project, please visit the Conversations Docs to begin. If you've already built on Programmable Chat, please visit our Migration Guide to learn about how to switch.
Ready to implement a chat application using Twilio Programmable Chat Client, Node.js and Express?
This application allow users to exchange messages through different channels, using the Twilio Programmable Chat API. On this example, we'll show how to use this API capabilities to manage channels and their usages.
Properatiは不動産の買い手と売り手をリアルタイムにつなぐ手助けをするモバイルメッセージングAppを構築しました。 さらに詳しく。
For your convenience, we consolidated the source code for this tutorial in a single GitHub repository. Feel free to clone it and tweak as required.
トークンの生成
In order to create a Twilio Programmable Chat client, you will need an access token. This token holds information about your Twilio Account and Programmable Chat API keys.
新規AccessToken
を作成し、これにChatGrant
を与えることでこのトークンを作成します。 お使いのTwilio資格情報を使用して新しいAccessTokenオブジェクトが作成されます。
We can generate a token, now we need a way for the chat app to get it.
トークン生成コントローラー
On our controller we expose the endpoint for token generation. This endpoint is responsible for providing a valid token when passed this parameter:
identity
:ユーザー自身を識別します。
tokenService
オブジェクトを使用して、トークンを生成したら、AccessToken のメソッドを token.toJwt()
として使用して、文字列としてトークンを取得できます。次に、トークンを JSON エンコード済み文字列として返します。
Now that we have a route that generates JWT tokens on demand, let's use this route to initialize our Twilio Chat Client.
Programmable Chatクライアントを初期化する
Our client fetches a new Token by making a POST request to our endpoint when it calls the fetchAccessToken
method.
With the token we can then instantiate Twilio.Chat.Client
in connectMessagingClient
.
Now that we've instantiated our Chat Client, lets see how we can get a list of channels.
Channel一覧を取得する
クライアントの初期化後、そのgetPublicChannelDescriptors
メソッドを使用してすべての可視チャネルを取得します。 このメソッドは取得されるChannelの一覧をUI上で表示するのに使用するプロミスを返します。
Next, we need a default channel.
一般チャンネルに参加する
このアプリケーションは、起動時に「General Channel」という名前のChannelに参加しようとします。 このChannelが存在しない場合、その名前でChannelを作成します。 このチャンネルが存在しない場合は、その名前でチャンネルを 1 つ作成します。このサンプルアプリケーションでは、公開チャネルの挙動を紹介していますが、ChannelクライアントではプライベートChannelを作成して招待の処理を行ったりといったことも可能です。
アプリケーションを起動するたびに一般チャンネルを新たに作成したいわけではないので、一般チャンネルに一意の名前を設定します。
ここで、Channelイベントをいくつかリッスンしてみましょう。
チャンネルイベントをリスニングする
続いて、Channelイベントをリッスンします。 今回は、以下のイベントにリスナーを設定します:
messageAdded
:接続しているチャンネルに他のメンバーがメッセージを送信する場合。typingStarted
:接続しているチャンネルで他のメンバーがメッセージを入力している場合。typingEnded
:接続しているチャンネルで他のメンバーがメッセージの入力を中止した場合。memberJoined
:接続しているチャンネルに他のメンバーが参加する場合。memberLeft
:接続しているチャンネルから他のメンバーが退出する場合。
個々のイベントを処理するためにそれぞれの関数を登録します。
クライアントも同様にイベントを生成します。 このイベントを同様にリッスンできるようにする方法を見ていきましょう。
クライアントイベントをリスニングする
チャンネルと同様に、クライアントでイベントのハンドラーを登録できます。
channelAdded
:チャンネルがクライアントに表示されるようになった場合。channelRemoved
:チャンネルがクライアントに表示されなくなった場合。tokenExpired
:提供されたトークンの有効期限が切れた場合。
クライアントイベントの完全なリスト
ここで実際のチャットアプリケーションが用意できましたが、複数Channelを使用してもっと面白いものを作ってみましょう。
チャンネルを作成する
ユーザーが「+ Channel」リンクをクリックすると、新規のChannel名を入力できるテキストフィールドが表示されます。 Channelの作成は、friendlyName
キーを持つオブジェクトでcreateChannel
を呼び出すだけで簡単に行えます。 Programmable ChatドキュメントのChannelセクションで一覧されている追加のオプションを伴ってChannelを作成できます。
続いて、Channel間を切り替える方法を見ていきましょう。
他のChannelに参加する
サイドバーからチャンネルの名前をタップすると、そのチャンネルが selectedChannel
として設定されます。selectChannel
メソッドは選択したチャンネルへの参加および selectedChannel
の設定を行います。
いつか、ユーザーはChannelを削除したいと思うでしょう。 これを行う方法を見ていきましょう。
チャンネルを削除する
Channelの削除は、追加よりも簡単です。 アプリケーションは、"delete current channel"リンクによって、ユーザーにChannelを削除できるようにします。Twilioから実際にChannelを削除するのに必要なことは、削除しようとしているChannelのdelete
メソッドを呼ぶことだけです。 Channel
オブジェクトの他のメソッドと同様、successハンドラーを設定できるプロミスを返します。
一丁あがり! Express を使用して Node.js の簡単なチャットアプリケーションを実装できました。
次はどこでしょうか?
Twilio を使う Node 開発者であれば、他のチュートリアルも調べてみてください。
ウェブページのボタンを押して、電話を介して訪問者をライブサポートまたはセールス担当者に接続します。
音声通話または SMS テキストメッセージを介して調査を実施し、ユーザーから構造化データを迅速に収集します。
これは役に立ちましたか?
このチュートリアルをお読みいただき、ありがとうございます。ご意見やご感想などございましたら、ぜひお聞かせください。@twilio へツイートいただき、ご意見をお知らせください。
ヘルプが必要ですか?
We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Stack Overflow Collective or browsing the Twilio tag on Stack Overflow.