Quickstart: Add Chat to your App

Get started with Azure Communication Services by using the Communication Services Chat SDK to add real-time chat to your application. In this quickstart, we'll use the Chat SDK to create chat threads that allow users to have conversations with one another. To learn more about Chat concepts, visit the chat conceptual documentation.

Prerequisites

Before you get started, make sure to:

  • Create an Azure account with an active subscription. For details, see Create an account for free.
  • Install Node.js Active LTS and Maintenance LTS versions.
  • Create an Azure Communication Services resource. For details, see Create an Azure Communication Resource. You'll need to record your resource endpoint for this quickstart.
  • Create three ACS Users and issue them a user access token User Access Token. Be sure to set the scope to chat, and note the token string as well as the userId string. The full demo creates a thread with two initial participants and then adds a third participant to the thread.

Setting up

Create a new web application

First, open your terminal or command window create a new directory for your app, and navigate to it.

mkdir chat-quickstart && cd chat-quickstart

Run npm init -y to create a package.json file with default settings.

npm init -y

Install the packages

Use the npm install command to install the below Communication Services SDKs for JavaScript.

npm install @azure/communication-common --save

npm install @azure/communication-identity --save

npm install @azure/communication-signaling --save

npm install @azure/communication-chat --save

The --save option lists the library as a dependency in your package.json file.

Set up the app framework

This quickstart uses webpack to bundle the application assets. Run the following command to install the webpack, webpack-cli and webpack-dev-server npm packages and list them as development dependencies in your package.json:

npm install webpack webpack-cli webpack-dev-server --save-dev

Create a webpack.config.js file in the root directory. Copy the following configuration into this file:

module.exports = {
  entry: "./client.js",
  output: {
    filename: "bundle.js"
  },
  devtool: "inline-source-map",
  mode: "development"
}

Add a start script to your package.json, we will use this for running the app. Inside the scripts section of package.json add the following:

"scripts": {
  "start": "webpack serve --config ./webpack.config.js"
}

Create an index.html file in the root directory of your project. We'll use this file as a template to add chat capability using the Azure Communication Chat SDK for JavaScript.

<!DOCTYPE html>
<html>
  <head>
    <title>Communication Client - Chat Sample</title>
  </head>
  <body>
    <h4>Azure Communication Services</h4>
    <h1>Chat Quickstart</h1>
    <script src="./bundle.js"></script>
  </body>
</html>

Create a file in the root directory of your project called client.js to contain the application logic for this quickstart.

Create a chat client

To create a chat client in your web app, you'll use the Communications Service endpoint and the access token that was generated as part of prerequisite steps.

User access tokens enable you to build client applications that directly authenticate to Azure Communication Services. This quickstart does not cover creating a service tier to manage tokens for your chat application. See chat concepts for more information about chat architecture, and user access tokens for more information about access tokens.

Inside client.js use the endpoint and access token in the code below to add chat capability using the Azure Communication Chat SDK for JavaScript.


import { ChatClient } from '@azure/communication-chat';
import { AzureCommunicationTokenCredential } from '@azure/communication-common';

// Your unique Azure Communication service endpoint
let endpointUrl = 'https://<RESOURCE_NAME>.communication.azure.com';
// The user access token generated as part of the pre-requisites
let userAccessToken = '<USER_ACCESS_TOKEN>';

let chatClient = new ChatClient(endpointUrl, new AzureCommunicationTokenCredential(userAccessToken));
console.log('Azure Communication Chat client created!');
  • Replace endpointUrl with the Communication Services resource endpoint, see Create an Azure Communication Resource if you have not already done so.
  • Replace userAccessToken with the token that you issued.

Run the code

Run the following command to bundle application host in on a local webserver:

npm run start

Open your browser and navigate to http://localhost:8080/. In the developer tools console within your browser you should see following:

Azure Communication Chat client created!

Object model

The following classes and interfaces handle some of the major features of the Azure Communication Services Chat SDK for JavaScript.

Name Description
ChatClient This class is needed for the Chat functionality. You instantiate it with your subscription information, and use it to create, get and delete threads.
ChatThreadClient This class is needed for the Chat Thread functionality. You obtain an instance via the ChatClient, and use it to send/receive/update/delete messages, add/remove/get users, send typing notifications and read receipts, subscribe chat events.

Start a chat thread

Use the createThread method to create a chat thread.

createThreadRequest is used to describe the thread request:

  • Use topic to give a topic to this chat. Topics can be updated after the chat thread is created using the UpdateThread function.
  • Use participants to list the participants to be added to the chat thread.

When resolved, createChatThread method returns a CreateChatThreadResult. This model contains a chatThread property where you can access the id of the newly created thread. You can then use the id to get an instance of a ChatThreadClient. The ChatThreadClient can then be used to perform operation within the thread such as sending messages or listing participants.

async function createChatThread() {
  const createChatThreadRequest = {
    topic: "Hello, World!"
  };
  const createChatThreadOptions = {
    participants: [
      {
        id: '<USER_ID>',
        displayName: '<USER_DISPLAY_NAME>'
      }
    ]
  };
  const createChatTtreadResult = await chatClient.createChatThread(
    createChatThreadRequest,
    createChatThreadOptions
  );
  const threadId = createChatThreadResult.chatThread.id;
  return threadId;
}

createChatThread().then(async threadId => {
  console.log(`Thread created:${threadId}`);
  // PLACEHOLDERS
  // <CREATE CHAT THREAD CLIENT>
  // <RECEIVE A CHAT MESSAGE FROM A CHAT THREAD>
  // <SEND MESSAGE TO A CHAT THREAD>
  // <LIST MESSAGES IN A CHAT THREAD>
  // <ADD NEW PARTICIPANT TO THREAD>
  // <LIST PARTICIPANTS IN A THREAD>
  // <REMOVE PARTICIPANT FROM THREAD>
  });

When you refresh your browser tab you should see the following in the console:

Thread created: <thread_id>

Get a chat thread client

The getChatThreadClient method returns a chatThreadClient for a thread that already exists. It can be used for performing operations on the created thread: add participants, send message, etc. threadId is the unique ID of the existing chat thread.

let chatThreadClient = chatClient.getChatThreadClient(threadId);
console.log(`Chat Thread client for threadId:${threadId}`);

Add this code in place of the <CREATE CHAT THREAD CLIENT> comment in client.js, refresh your browser tab and check the console, you should see:

Chat Thread client for threadId: <threadId>

List all chat threads

The listChatThreads method returns a PagedAsyncIterableIterator of type ChatThreadItem. It can be used for listing all chat threads. An iterator of [ChatThreadItem] is the response returned from listing threads

const threads = chatClient.listChatThreads();
for await (const thread of threads) {
   // your code here
}

Send a message to a chat thread

Use sendMessage method to sends a message to a thread identified by threadId.

sendMessageRequest is used to describe the message request:

  • Use content to provide the chat message content;

sendMessageOptions is used to describe the operation optional params:

  • Use senderDisplayName to specify the display name of the sender;
  • Use type to specify the message type, such as 'text' or 'html' ;

SendChatMessageResult is the response returned from sending a message, it contains an ID, which is the unique ID of the message.

const sendMessageRequest =
{
  content: 'Hello Geeta! Can you share the deck for the conference?'
};
let sendMessageOptions =
{
  senderDisplayName : 'Jack',
  type: 'text'
};
const sendChatMessageResult = await chatThreadClient.sendMessage(sendMessageRequest, sendMessageOptions);
const messageId = sendChatMessageResult.id;

Add this code in place of the <SEND MESSAGE TO A CHAT THREAD> comment in client.js, refresh your browser tab and check the console.

Message sent!, message id:<number>

Receive chat messages from a chat thread

With real-time signaling, you can subscribe to listen for new incoming messages and update the current messages in memory accordingly. Azure Communication Services supports a list of events that you can subscribe to.

// open notifications channel
await chatClient.startRealtimeNotifications();
// subscribe to new notification
chatClient.on("chatMessageReceived", (e) => {
  console.log("Notification chatMessageReceived!");
  // your code here
});

Add this code in place of <RECEIVE A CHAT MESSAGE FROM A CHAT THREAD> comment in client.js. Refresh your browser tab, you should see in the console a message Notification chatMessageReceived;

Alternatively you can retrieve chat messages by polling the listMessages method at specified intervals.


const messages = chatThreadClient.listMessages();
for await (const message of messages) {
   // your code here
}

Add this code in place of the <LIST MESSAGES IN A CHAT THREAD> comment in client.js. Refresh your tab, in the console you should find the list of messages sent in this chat thread.

listMessages returns different types of messages which can be identified by chatMessage.type.

For more details, see Message Types.

Add a user as a participant to the chat thread

Once a chat thread is created, you can then add and remove users from it. By adding users, you give them access to send messages to the chat thread, and add/remove other participants.

Before calling the addParticipants method, ensure that you have acquired a new access token and identity for that user. The user will need that access token in order to initialize their chat client.

addParticipantsRequest describes the request object wherein participants lists the participants to be added to the chat thread;

  • id, required, is the communication identifier to be added to the chat thread.
  • displayName, optional, is the display name for the thread participant.
  • shareHistoryTime, optional, is the time from which the chat history is shared with the participant. To share history since the inception of the chat thread, set this property to any date equal to, or less than the thread creation time. To share no history previous to when the participant was added, set it to the current date. To share partial history, set it to the date of your choice.

const addParticipantsRequest =
{
  participants: [
    {
      id: { communicationUserId: '<NEW_PARTICIPANT_USER_ID>' },
      displayName: 'Jane'
    }
  ]
};

await chatThreadClient.addParticipants(addParticipantsRequest);

Replace NEW_PARTICIPANT_USER_ID with a new user ID Add this code in place of the <ADD NEW PARTICIPANT TO THREAD> comment in client.js

List users in a chat thread

const participants = chatThreadClient.listParticipants();
for await (const participant of participants) {
   // your code here
}

Add this code in place of the <LIST PARTICIPANTS IN A THREAD> comment in client.js, refresh your browser tab and check the console, you should see information about users in a thread.

Remove user from a chat thread

Similar to adding a participant, you can remove participants from a chat thread. In order to remove, you'll need to track the IDs of the participants you have added.

Use removeParticipant method where participant is the communication user to be removed from the thread.


await chatThreadClient.removeParticipant({ communicationUserId: <PARTICIPANT_ID> });
await listParticipants();

Replace PARTICIPANT_ID with a User ID used in the previous step (<NEW_PARTICIPANT_USER_ID>). Add this code in place of the <REMOVE PARTICIPANT FROM THREAD> comment in client.js,

Important

The Azure Communication Services Android, Python, and iOS Chat SDKs are currently in public preview. This preview version is provided without a service-level agreement, and it's not recommended for production workloads. Certain features might not be supported or might have constrained capabilities. For more information, see Supplemental Terms of Use for Microsoft Azure Previews.

Prerequisites

Before you get started, make sure to:

Setting up

Create a new Python application

Open your terminal or command window create a new directory for your app, and navigate to it.

mkdir chat-quickstart && cd chat-quickstart

Use a text editor to create a file called start-chat.py in the project root directory and add the structure for the program, including basic exception handling. You'll add all the source code for this quickstart to this file in the following sections.

import os
# Add required SDK components from quickstart here

try:
    print('Azure Communication Services - Chat Quickstart')
    # Quickstart code goes here
except Exception as ex:
    print('Exception:')
    print(ex)

Install SDK


pip install azure-communication-chat

Object model

The following classes and interfaces handle some of the major features of the Azure Communication Services Chat SDK for Python.

Name Description
ChatClient This class is needed for the Chat functionality. You instantiate it with your subscription information, and use it to create, get and delete threads.
ChatThreadClient This class is needed for the Chat Thread functionality. You obtain an instance via the ChatClient, and use it to send/receive/update/delete messages, add/remove/get users, send typing notifications and read receipts.

Create a chat client

To create a chat client, you'll use Communications Service endpoint and the Access Token that was generated as part of pre-requisite steps. Learn more about User Access Tokens.

This quickstart does not cover creating a service tier to manage tokens for your chat application, although it is recommended. See the following documentation for more detail Chat Architecture

pip install azure-communication-identity
from azure.communication.chat import ChatClient, CommunicationTokenCredential

endpoint = "https://<RESOURCE_NAME>.communication.azure.com"
chat_client = ChatClient(endpoint, CommunicationTokenCredential("<Access Token>"))

Start a chat thread

Use the create_chat_thread method to create a chat thread.

  • Use topic to give a thread topic; Topic can be updated after the chat thread is created using the update_thread function.
  • Use thread_participants to list the ChatParticipant to be added to the chat thread, the ChatParticipant takes CommunicationUserIdentifier type as user, which is what you got after you created by Create a user

CreateChatThreadResult is the result returned from creating a thread, you can use it to fetch the id of the chat thread that got created. This id can then be used to fetch a ChatThreadClient object using the get_chat_thread_client method. ChatThreadClient can be used to perform other chat operations to this chat thread.

topic="test topic"

create_chat_thread_result = chat_client.create_chat_thread(topic)
chat_thread_client = chat_client.get_chat_thread_client(create_chat_thread_result.chat_thread.id)

Get a chat thread client

The get_chat_thread_client method returns a thread client for a thread that already exists. It can be used for performing operations on the created thread: add participants, send message, etc. thread_id is the unique ID of the existing chat thread.

ChatThreadClient can be used to perform other chat operations to this chat thread.

thread_id = create_chat_thread_result.chat_thread.id
chat_thread_client = chat_client.get_chat_thread_client(thread_id)

List all chat threads

The list_chat_threads method returns a iterator of type ChatThreadItem. It can be used for listing all chat threads.

  • Use start_time to specify the earliest point in time to get chat threads up to.
  • Use results_per_page to specify the maximum number of chat threads returned per page.

An iterator of [ChatThreadItem] is the response returned from listing threads

from datetime import datetime, timedelta

start_time = datetime.utcnow() - timedelta(days=2)

chat_threads = chat_client.list_chat_threads(results_per_page=5, start_time=start_time)
for chat_thread_item_page in chat_threads.by_page():
    for chat_thread_item in chat_thread_item_page:
        print(chat_thread_item)
        print('Chat Thread Id: ', chat_thread_item.id)

Send a message to a chat thread

Use send_message method to send a message to a chat thread you just created, identified by thread_id.

  • Use content to provide the chat message content;
  • Use chat_message_type to specify the message content type. Possible values are 'text' and 'html'; if not specified default value of 'text' is assigned.
  • Use sender_display_name to specify the display name of the sender;

SendChatMessageResult is the response returned from sending a message, it contains an ID, which is the unique ID of the message.

from azure.communication.chat import ChatMessageType

topic = "test topic"
create_chat_thread_result = chat_client.create_chat_thread(topic)
thread_id = create_chat_thread_result.chat_thread.id
chat_thread_client = chat_client.get_chat_thread_client(create_chat_thread_result.chat_thread.id)


content='hello world'
sender_display_name='sender name'

# specify chat message type with pre-built enumerations
send_message_result_w_enum = chat_thread_client.send_message(content=content, sender_display_name=sender_display_name, chat_message_type=ChatMessageType.TEXT)
print("Message sent: id: ", send_message_result_w_enum.id)

Receive chat messages from a chat thread

You can retrieve chat messages by polling the list_messages method at specified intervals.

  • Use results_per_page to specify the maximum number of messages to be returned per page.
  • Use start_time to specify the earliest point in time to get messages up to.

An iterator of [ChatMessage] is the response returned from listing messages

from datetime import datetime, timedelta

start_time = datetime.utcnow() - timedelta(days=1)

chat_messages = chat_thread_client.list_messages(results_per_page=1, start_time=start_time)
for chat_message_page in chat_messages.by_page():
    for chat_message in chat_message_page:
        print("ChatMessage: Id=", chat_message.id, "; Content=", chat_message.content.message)

list_messages returns the latest version of the message, including any edits or deletes that happened to the message using update_message and delete_message. For deleted messages ChatMessage.deleted_on returns a datetime value indicating when that message was deleted. For edited messages, ChatMessage.edited_on returns a datetime indicating when the message was edited. The original time of message creation can be accessed using ChatMessage.created_on which can be used for ordering the messages.

list_messages returns different types of messages which can be identified by ChatMessage.type.

Read more about Message Types here: Message Types.

Send read receipt

The send_read_receipt method can be used to posts a read receipt event to a thread, on behalf of a user.

  • Use message_id to specify the ID of the latest message read by current user.
content='hello world'

send_message_result = chat_thread_client.send_message(content)
chat_thread_client.send_read_receipt(message_id=send_message_result.id)

Add a user as a participant to the chat thread

Once a chat thread is created, you can then add and remove users from it. By adding users, you give them access to be able to send messages to the chat thread, and add/remove other participants. Before calling add_participants method, ensure that you have acquired a new access token and identity for that user. The user will need that access token in order to initialize their chat client.

One or more users can be added to the chat thread using the add_participants method, provided new access token and identify is available for all users.

A list(tuple(ChatParticipant, CommunicationError)) is returned. When participant is successfully added, an empty list is expected. In case of an error encountered while adding participant, the list is populated with the failed participants along with the error that was encountered.

from azure.communication.identity import CommunicationIdentityClient
from azure.communication.chat import ChatParticipant
from datetime import datetime

# create 2 users
identity_client = CommunicationIdentityClient.from_connection_string('<connection_string>')
new_users = [identity_client.create_user() for i in range(2)]

# # conversely, you can also add an existing user to a chat thread; provided the user_id is known
# from azure.communication.identity import CommunicationUserIdentifier
#
# user_id = 'some user id'
# user_display_name = "Wilma Flinstone"
# new_user = CommunicationUserIdentifier(user_id)
# participant = ChatParticipant(
#     user=new_user,
#     display_name=user_display_name,
#     share_history_time=datetime.utcnow())

participants = []
for _user in new_users:
  chat_thread_participant = ChatParticipant(
    user=_user,
    display_name='Fred Flinstone',
    share_history_time=datetime.utcnow()
  ) 
  participants.append(chat_thread_participant) 

response = chat_thread_client.add_participants(participants)

def decide_to_retry(error, **kwargs):
    """
    Insert some custom logic to decide if retry is applicable based on error
    """
    return True

# verify if all users has been successfully added or not
# in case of partial failures, you can retry to add all the failed participants 
retry = [p for p, e in response if decide_to_retry(e)]
if retry:
    chat_thread_client.add_participants(retry)

List thread participants in a chat thread

Similar to adding a participant, you can also list participants from a thread.

Use list_participants to retrieve the participants of the thread.

  • Use results_per_page, optional, The maximum number of participants to be returned per page.
  • Use skip, optional, to skips participants up to a specified position in response.

An iterator of [ChatParticipant] is the response returned from listing participants

chat_thread_participants = chat_thread_client.list_participants()
for chat_thread_participant_page in chat_thread_participants.by_page():
    for chat_thread_participant in chat_thread_participant_page:
        print("ChatParticipant: ", chat_thread_participant)

Run the code

Run the application from your application directory with the python command.

python start-chat.py

Prerequisites

Setting up

Create a new Java application

Open your terminal or command window and navigate to the directory where you would like to create your Java application. Run the command below to generate the Java project from the maven-archetype-quickstart template.

mvn archetype:generate -DgroupId=com.communication.quickstart -DartifactId=communication-quickstart -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false

You'll notice that the 'generate' goal created a directory with the same name as the artifactId. Under this directory, the src/main/java directory contains the project source code, the src/test/java directory contains the test source, and the pom.xml file is the project's Project Object Model, or POM.

Update your application's POM file to use Java 8 or higher:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

Add the package references for the Chat SDK

In your POM file, reference the azure-communication-chat package with the Chat APIs:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-chat</artifactId>
    <version>1.0.0</version>
</dependency>

For authentication, your client needs to reference the azure-communication-common package:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-common</artifactId>
    <version>1.0.0</version>
</dependency>

Object model

The following classes and interfaces handle some of the major features of the Azure Communication Services Chat SDK for Java.

Name Description
ChatClient This class is needed for the Chat functionality. You instantiate it with your subscription information, and use it to create, get and delete threads.
ChatAsyncClient This class is needed for the asynchronous Chat functionality. You instantiate it with your subscription information, and use it to create, get and delete threads.
ChatThreadClient This class is needed for the Chat Thread functionality. You obtain an instance via the ChatClient, and use it to send/receive/update/delete messages, add/remove/get users, send typing notifications and read receipts.
ChatThreadAsyncClient This class is needed for the asynchronous Chat Thread functionality. You obtain an instance via the ChatAsyncClient, and use it to send/receive/update/delete messages, add/remove/get users, send typing notifications and read receipts.

Create a chat client

To create a chat client, you'll use the Communications Service endpoint and the access token that was generated as part of pre-requisite steps. User access tokens enable you to build client applications that directly authenticate to Azure Communication Services. Once you generate these tokens on your server, pass them back to a client device. You need to use the CommunicationTokenCredential class from the Common SDK to pass the token to your chat client.

Learn more about Chat Architecture

When adding the import statements, be sure to only add imports from the com.azure.communication.chat and com.azure.communication.chat.models namespaces, and not from the com.azure.communication.chat.implementation namespace. In the App.java file that was generated via Maven, you can use the following code to begin with:

package com.communication.quickstart;

import com.azure.communication.chat.*;
import com.azure.communication.chat.models.*;
import com.azure.communication.common.*;
import com.azure.core.http.rest.PagedIterable;

import java.io.*;
import java.util.*;

public class App
{
    public static void main( String[] args ) throws IOException
    {
        System.out.println("Azure Communication Services - Chat Quickstart");

        // Your unique Azure Communication service endpoint
        String endpoint = "https://<RESOURCE_NAME>.communication.azure.com";

        // User access token fetched from your trusted service
        String userAccessToken = "<USER_ACCESS_TOKEN>";

        // Create a CommunicationTokenCredential with the given access token, which is only valid until the token is valid
        CommunicationTokenCredential userCredential = new CommunicationTokenCredential(userAccessToken);

        // Initialize the chat client
        final ChatClientBuilder builder = new ChatClientBuilder();
        builder.endpoint(endpoint)
            .credential(userCredential);
        ChatClient chatClient = builder.buildClient();
    }
}

Start a chat thread

Use the createChatThread method to create a chat thread. createChatThreadOptions is used to describe the thread request.

  • Use the topic parameter of the constructor to give a topic to this chat; Topic can be updated after the chat thread is created using the UpdateThread function.
  • Use participants to list the thread participants to be added to the thread. ChatParticipant takes the user you created in the User Access Token quickstart.

CreateChatThreadResult is the response returned from creating a chat thread. It contains a getChatThread() method which returns the ChatThread object that can be used to get the thread client from which you can get the ChatThreadClient for performing operations on the created thread: add participants, send message, etc. The ChatThread object also contains the getId() method which retrieves the unique ID of the thread.

CommunicationUserIdentifier identity1 = new CommunicationUserIdentifier("<USER_1_ID>");
CommunicationUserIdentifier identity2 = new CommunicationUserIdentifier("<USER_2_ID>");

ChatParticipant firstThreadParticipant = new ChatParticipant()
    .setCommunicationIdentifier(identity1)
    .setDisplayName("Participant Display Name 1");

ChatParticipant secondThreadParticipant = new ChatParticipant()
    .setCommunicationIdentifier(identity2)
    .setDisplayName("Participant Display Name 2");

CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions("Topic")
    .addParticipant(firstThreadParticipant)
    .addParticipant(secondThreadParticipant);

CreateChatThreadResult result = chatClient.createChatThread(createChatThreadOptions);
String chatThreadId = result.getChatThread().getId();

List chat threads

Use the listChatThreads method to retrieve a list of existing chat threads.

PagedIterable<ChatThreadItem> chatThreads = chatClient.listChatThreads();

chatThreads.forEach(chatThread -> {
    System.out.printf("ChatThread id is %s.\n", chatThread.getId());
});

Get a chat thread client

The getChatThreadClient method returns a thread client for a thread that already exists. It can be used for performing operations on the created thread: add participants, send message, etc. chatThreadId is the unique ID of the existing chat thread.

ChatThreadClient chatThreadClient = chatClient.getChatThreadClient(chatThreadId);

Send a message to a chat thread

Use the sendMessage method to send a message to the thread you just created, identified by chatThreadId. sendChatMessageOptions is used to describe the chat message request.

  • Use content to provide the chat message content.
  • Use type to specify the chat message content type, TEXT or HTML.
  • Use senderDisplayName to specify the display name of the sender.

The response sendChatMessageResult contains an id, which is the unique ID of the message.

SendChatMessageOptions sendChatMessageOptions = new SendChatMessageOptions()
    .setContent("Message content")
    .setType(ChatMessageType.TEXT)
    .setSenderDisplayName("Sender Display Name");

SendChatMessageResult sendChatMessageResult = chatThreadClient.sendMessage(sendChatMessageOptions);
String chatMessageId = sendChatMessageResult.getId();

Receive chat messages from a chat thread

You can retrieve chat messages by polling the listMessages method on the chat thread client at specified intervals.

chatThreadClient.listMessages().forEach(message -> {
    System.out.printf("Message id is %s.\n", message.getId());
});

listMessages returns the latest version of the message, including any edits or deletes that happened to the message using .editMessage() and .deleteMessage(). For deleted messages, chatMessage.getDeletedOn() returns a datetime value indicating when that message was deleted. For edited messages, chatMessage.getEditedOn() returns a datetime indicating when the message was edited. The original time of message creation can be accessed using chatMessage.getCreatedOn(), and it can be used for ordering the messages.

Read more about message types here: Message Types.

Send read receipt

Use the sendReadReceipt method to post a read receipt event to a chat thread, on behalf of a user. chatMessageId is the unique ID of the chat message that was read.

String chatMessageId = message.getId();
chatThreadClient.sendReadReceipt(chatMessageId);

List chat participants

Use listParticipants to retrieve a paged collection containing the participants of the chat thread identified by chatThreadId.

PagedIterable<ChatParticipant> chatParticipantsResponse = chatThreadClient.listParticipants();
chatParticipantsResponse.forEach(chatParticipant -> {
    System.out.printf("Participant id is %s.\n", ((CommunicationUserIdentifier) chatParticipant.getCommunicationIdentifier()).getId());
});

Add a user as participant to the chat thread

Once a chat thread is created, you can then add and remove users from it. By adding users, you give them access to send messages to the chat thread, and add/remove other participants. You'll need to start by getting a new access token and identity for that user. Before calling addParticipants method, ensure that you have acquired a new access token and identity for that user. The user will need that access token in order to initialize their chat client.

Use the addParticipants method to add participants to the thread.

  • communicationIdentifier, required, is the CommunicationIdentifier you've created by the CommunicationIdentityClient in the User Access Token quickstart.
  • displayName, optional, is the display name for the thread participant.
  • shareHistoryTime, optional, is the time from which the chat history is shared with the participant. To share history since the inception of the chat thread, set this property to any date equal to, or less than the thread creation time. To share no history previous to when the participant was added, set it to the current date. To share partial history, set it to the required date.
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();

CommunicationUserIdentifier identity3 = new CommunicationUserIdentifier("<USER_3_ID>");
CommunicationUserIdentifier identity4 = new CommunicationUserIdentifier("<USER_4_ID>");

ChatParticipant thirdThreadParticipant = new ChatParticipant()
    .setCommunicationIdentifier(identity3)
    .setDisplayName("Display Name 3");

ChatParticipant fourthThreadParticipant = new ChatParticipant()
    .setCommunicationIdentifier(identity4)
    .setDisplayName("Display Name 4");

participants.add(thirdThreadParticipant);
participants.add(fourthThreadParticipant);

chatThreadClient.addParticipants(participants);

Run the code

Navigate to the directory containing the pom.xml file and compile the project by using the following mvn command.

mvn compile

Then, build the package.

mvn package

Run the following mvn command to execute the app.

mvn exec:java -Dexec.mainClass="com.communication.quickstart.App" -Dexec.cleanupDaemonThreads=false

Important

The Azure Communication Services Android, Python, and iOS Chat SDKs are currently in public preview. This preview version is provided without a service-level agreement, and it's not recommended for production workloads. Certain features might not be supported or might have constrained capabilities. For more information, see Supplemental Terms of Use for Microsoft Azure Previews.

Prerequisites

Before you get started, make sure to:

  • Create an Azure account with an active subscription. For details, see Create an account for free.
  • Install Android Studio, we will be using Android Studio to create an Android application for the quickstart to install dependencies.
  • Create an Azure Communication Services resource. For details, see Create an Azure Communication Resource. You'll need to record your resource endpoint for this quickstart.
  • Create two Communication Services Users and issue them a user access token User Access Token. Be sure to set the scope to chat, and note the token string and the userId string. In this quickstart, we will create a thread with an initial participant and then add a second participant to the thread.

Setting up

Create a new android application

  1. Open Android Studio and select Create a new project.
  2. On the next window, select Empty Activity as the project template.
  3. When choosing options, enter ChatQuickstart as the project name.
  4. Click next and choose the directory where you want the project to be created.

Install the libraries

We'll use Gradle to install the necessary Communication Services dependencies. From the command line, navigate inside the root directory of the ChatQuickstart project. Open the app's build.gradle file and add the following dependencies to the ChatQuickstart target:

implementation 'com.azure.android:azure-communication-common:1.0.0-beta.8'
implementation 'com.azure.android:azure-communication-chat:1.0.0-beta.8'

Exclude meta files in packaging options in root build.gradle

android {
   ...
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/license'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/notice'
        exclude 'META-INF/ASL2.0'
        exclude("META-INF/*.md")
        exclude("META-INF/*.txt")
        exclude("META-INF/*.kotlin_module")
    }
}

(Alternative) To install libraries through Maven

To import the library into your project using the Maven build system, add it to the dependencies section of your app's pom.xml file, specifying its artifact ID and the version you wish to use:

<dependency>
  <groupId>com.azure.android</groupId>
  <artifactId>azure-communication-chat</artifactId>
  <version>1.0.0-beta.8</version>
</dependency>

Setup the placeholders

Open and edit the file MainActivity.java. In this Quickstart, we'll add our code to MainActivity, and view the output in the console. This quickstart does not address building a UI. At the top of file, import the Communication common and Communication chat libraries:

import com.azure.android.communication.chat.*;
import com.azure.android.communication.common.*;

Copy the following code into the file MainActivity:

    private String secondUserId = "<second_user_id>";
    private String threadId = "<thread_id>";
    private String chatMessageId = "<chat_message_id>";
    private final String sdkVersion = "1.0.0-beta.8";
    private static final String APPLICATION_ID = "Chat Quickstart App";
    private static final String SDK_NAME = "azure-communication-com.azure.android.communication.chat";
    private static final String TAG = "--------------Chat Quickstart App-------------";

    private void log(String msg) {
        Log.i(TAG, msg);
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
    
   @Override
    protected void onStart() {
        super.onStart();
        try {
            // <CREATE A CHAT CLIENT>

            // <CREATE A CHAT THREAD>

            // <CREATE A CHAT THREAD CLIENT>

            // <SEND A MESSAGE>

            // <ADD A USER>

            // <LIST USERS>

            // <REMOVE A USER>
            
            // <<SEND A TYPING NOTIFICATION>>
            
            // <<SEND A READ RECEIPT>>
               
            // <<LIST READ RECEIPTS>>
        } catch (Exception e){
            System.out.println("Quickstart failed: " + e.getMessage());
        }
    }

In following steps, we'll replace the placeholders with sample code using the Azure Communication Services Chat library.

Create a chat client

Replace the comment <CREATE A CHAT CLIENT> with the following code (put the import statements at top of the file):

import com.azure.android.communication.chat.ChatAsyncClient;
import com.azure.android.communication.chat.ChatClientBuilder;
import com.azure.android.core.credential.AccessToken;
import com.azure.android.core.http.HttpHeader;
import com.azure.android.core.http.okhttp.OkHttpAsyncClientProvider;
import com.azure.android.core.http.policy.BearerTokenAuthenticationPolicy;
import com.azure.android.core.http.policy.UserAgentPolicy;

final String endpoint = "https://<resource>.communication.azure.com";
final String userAccessToken = "<user_access_token>";

ChatAsyncClient chatAsyncClient = new ChatClientBuilder()
    .endpoint(endpoint)
    .credentialPolicy(new BearerTokenAuthenticationPolicy((request, callback) ->
        callback.onSuccess(new AccessToken(userAccessToken, OffsetDateTime.now().plusDays(1)))))
    .addPolicy(new UserAgentPolicy(APPLICATION_ID, SDK_NAME, sdkVersion))
    .httpClient(new OkHttpAsyncClientProvider().createInstance())
    .buildAsyncClient();

  1. Use the ChatClientBuilder to configure and create an instance of ChatAsyncClient.
  2. Replace <resource> with your Communication Services resource.
  3. Replace <user_access_token> with a valid Communication Services access token.

Object model

The following classes and interfaces handle some of the major features of the Azure Communication Services Chat SDK for JavaScript.

Name Description
ChatClient/ChatAsyncClient This class is needed for the Chat functionality. You instantiate it with your subscription information, and use it to create, get, and delete threads.
ChatThreadClient/ChatThreadAsyncClient This class is needed for the Chat Thread functionality. You obtain an instance via the ChatClient, and use it to send/receive/update/delete messages, add/remove/get users, send typing notifications and read receipts, subscribe chat events.

Start a chat thread

We'll use our ChatAsyncClient to create a new thread with an initial user.

Replace the comment <CREATE A CHAT THREAD> with the following code:

// A list of ChatParticipant to start the thread with.
List<ChatParticipant> participants = new ArrayList<>();
// The communication user ID you created before, required.
String id = "<user_id>";
// The display name for the thread participant.
String displayName = "initial participant";
participants.add(new ChatParticipant()
    .setCommunicationIdentifier(new CommunicationUserIdentifier(id))
    .setDisplayName(displayName));

// The topic for the thread.
final String topic = "General";
// Optional, set a repeat request ID.
final String repeatabilityRequestID = "";
// Options to pass to the create method.
CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions()
    .setTopic(topic)
    .setParticipants(participants)
    .setIdempotencyToken(repeatabilityRequestID);

CreateChatThreadResult createChatThreadResult =
    chatAsyncClient.createChatThread(createChatThreadOptions).get();
ChatThreadProperties chatThreadProperties = createChatThreadResult.getChatThreadProperties();
threadId = chatThreadProperties.getId();

Replace <user_id> with a valid Communication Services user ID. We'll use the threadId from the response returned to the completion handler in later steps, so replace the <thread_id> in the class with the threadId we get from this request and re-run the app.

Get a chat thread client

Now that we've created a Chat thread we'll obtain a ChatThreadAsyncClient to perform operations within the thread. Replace the comment <CREATE A CHAT THREAD CLIENT> with the following code:

ChatThreadAsyncClient chatThreadAsyncClient = new ChatThreadClientBuilder()
    .endpoint(endpoint)
    .credentialPolicy(new BearerTokenAuthenticationPolicy((request, callback) ->
        callback.onSuccess(new AccessToken(userAccessToken, OffsetDateTime.now().plusDays(1)))))
    .addPolicy(new UserAgentPolicy(APPLICATION_ID, SDK_NAME, sdkVersion))
    .httpClient(new OkHttpAsyncClientProvider().createInstance())
    .chatThreadId(threadId)
    .buildAsyncClient();

Send a message to a chat thread

Make sure we have replaced <thread_id> with a valid thread ID, we will send message to that thread now.

Replace the comment <SEND A MESSAGE> with the following code:

// The chat message content, required.
final String content = "Test message 1";
// The display name of the sender, if null (i.e. not specified), an empty name will be set.
final String senderDisplayName = "An important person";
SendChatMessageOptions chatMessageOptions = new SendChatMessageOptions()
    .setType(ChatMessageType.TEXT)
    .setContent(content)
    .setSenderDisplayName(senderDisplayName);

// A string is the response returned from sending a message, it is an id, which is the unique ID of the message.
chatMessageId = chatThreadAsyncClient.sendMessage(chatMessageOptions).get().getId();

After we get chatMessageId, we can replace <chat_message_id> with chatMessageId for later method usage in quickstart and re-run the app.

Add a user as a participant to the chat thread

Replace the comment <ADD A USER> with the following code:

// The display name for the thread participant.
displayName = "a new participant";
ChatParticipant participant = new ChatParticipant()
    .setCommunicationIdentifier(new CommunicationUserIdentifier(secondUserId))
    .setDisplayName(secondUserDisplayName);
        
chatThreadAsyncClient.addParticipant(participant);

Replace <second_user_id> in the class with the Communication Services user ID of the user to be added.

List users in a thread

Replace the <LIST USERS> comment with the following code:

// The maximum number of participants to be returned per page, optional.
final int maxPageSize = 10;

// Skips participants up to a specified position in response.
final int skip = 0;

// Options to pass to the list method.
ListParticipantsOptions listParticipantsOptions = new ListParticipantsOptions()
    .setMaxPageSize(maxPageSize)
    .setSkip(skip);

PagedResponse<ChatParticipant> firstPageWithResponse =
    chatThreadAsyncClient.getParticipantsFirstPageWithResponse(listParticipantsOptions, Context.NONE).get();

for (ChatParticipant participant : firstPageWithResponse.getValue()) {
    // You code to handle participant
}

listParticipantsNextPage(firstPageWithResponse.getContinuationToken(), 2);

Put the following helper method into the class:

void listParticipantsNextPage(String continuationToken, int pageNumber) {
if (continuationToken != null) {
    PagedResponse<ChatParticipant> nextPageWithResponse =
        chatThreadAsyncClient.getParticipantsNextPageWithResponse(continuationToken, Context.NONE).get();
        for (ChatParticipant participant : nextPageWithResponse.getValue()) {
            // You code to handle participant
        }
            
        listParticipantsNextPage(nextPageWithResponse.getContinuationToken(), ++pageNumber);
    }
}

Remove user from a chat thread

Make sure to replace <second_user_id> to a valid user ID, we will remove second user from the thread now.

Replace the <REMOVE A USER> comment with the following code:

// Using the unique ID of the participant.
chatThreadAsyncClient.removeParticipant(new CommunicationUserIdentifier(secondUserId)).get();

Send a typing notification

Replace the <SEND A TYPING NOTIFICATION> comment with the following code:

chatThreadAsyncClient.sendTypingNotification().get();

Send a read receipt

Make sure to replace <chat_message_id> with a valid chat message ID, we will send read receipt for this message now.

Replace the <SEND A READ RECEIPT> comment with the following code:

chatThreadAsyncClient.sendReadReceipt(chatMessageId).get();

List read receipts

Replace the <READ RECEIPTS> comment with the following code:

// The maximum number of participants to be returned per page, optional.
maxPageSize = 10;
// Skips participants up to a specified position in response.
skip = 0;
// Options to pass to the list method.
ListReadReceiptOptions listReadReceiptOptions = new ListReadReceiptOptions()
    .setMaxPageSize(maxPageSize)
    .setSkip(skip);

PagedResponse<ChatMessageReadReceipt> firstPageWithResponse =
    chatThreadAsyncClient.getReadReceiptsFirstPageWithResponse(listReadReceiptOptions, Context.NONE).get();

for (ChatMessageReadReceipt readReceipt : firstPageWithResponse.getValue()) {
    // You code to handle readReceipt
}

listReadReceiptsNextPage(firstPageWithResponse.getContinuationToken(), 2);

Put the following helper method into the class:

void listReadReceiptsNextPage(String continuationToken, int pageNumber) {
    if (continuationToken != null) {
        PagedResponse<ChatMessageReadReceipt> nextPageWithResponse =
            chatThreadAsyncClient.getReadReceiptsNextPageWithResponse(continuationToken, Context.NONE).get();

        for (ChatMessageReadReceipt readReceipt : nextPageWithResponse.getValue()) {
            // You code to handle readReceipt
        }

        listParticipantsNextPage(nextPageWithResponse.getContinuationToken(), ++pageNumber);
    }
}

Run the code

In Android Studio, hit the Run button to build and run the project. In the console, you can view the output from the code and the logger output from the ChatClient.

Prerequisites

Before you get started, make sure to:

Setting up

Create a new C# application

In a console window (such as cmd, PowerShell, or Bash), use the dotnet new command to create a new console app with the name ChatQuickstart. This command creates a simple "Hello World" C# project with a single source file: Program.cs.

dotnet new console -o ChatQuickstart

Change your directory to the newly created app folder and use the dotnet build command to compile your application.

cd ChatQuickstart
dotnet build

Install the package

Install the Azure Communication Chat SDK for .NET

dotnet add package Azure.Communication.Chat --version 1.0.0

Object model

The following classes handle some of the major features of the Azure Communication Services Chat SDK for C#.

Name Description
ChatClient This class is needed for the Chat functionality. You instantiate it with your subscription information, and use it to create, get and delete threads.
ChatThreadClient This class is needed for the Chat Thread functionality. You obtain an instance via the ChatClient, and use it to send/receive/update/delete messages, add/remove/get participants, send typing notifications and read receipts.

Create a chat client

To create a chat client, you'll use your Communication Services endpoint and the access token that was generated as part of the prerequisite steps. You need to use the CommunicationIdentityClient class from the Identity SDK to create a user and issue a token to pass to your chat client.

Learn more about User Access Tokens.

This quickstart does not cover creating a service tier to manage tokens for your chat application, although it is recommended. Learn more about Chat Architecture

Copy the following code snippets and paste into source file: Program.cs

using Azure;
using Azure.Communication;
using Azure.Communication.Chat;
using System;

namespace ChatQuickstart
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            // Your unique Azure Communication service endpoint
            Uri endpoint = new Uri("https://<RESOURCE_NAME>.communication.azure.com");

            CommunicationTokenCredential communicationTokenCredential = new CommunicationTokenCredential(<Access_Token>);
            ChatClient chatClient = new ChatClient(endpoint, communicationTokenCredential);
        }
    }
}

Start a chat thread

Use the createChatThread method on the chatClient to create a chat thread

  • Use topic to give a topic to this chat; Topic can be updated after the chat thread is created using the UpdateTopic function.
  • Use participants property to pass a list of ChatParticipant objects to be added to the chat thread. The ChatParticipant object is initialized with a CommunicationIdentifier object. CommunicationIdentifier could be of type CommunicationUserIdentifier, MicrosoftTeamsUserIdentifier or PhoneNumberIdentifier. For example, to get a CommunicationIdentifier object, you will need to pass an Access ID which you created by following instruction to Create a user

The response object from the createChatThread method contains the chatThread details. To interact with the chat thread operations such as adding participants, sending a message, deleting a message, etc., a chatThreadClient client instance needs to instantiated using the GetChatThreadClient method on the ChatClient client.

var chatParticipant = new ChatParticipant(identifier: new CommunicationUserIdentifier(id: "<Access_ID>"))
{
    DisplayName = "UserDisplayName"
};
CreateChatThreadResult createChatThreadResult = await chatClient.CreateChatThreadAsync(topic: "Hello world!", participants: new[] { chatParticipant });
ChatThreadClient chatThreadClient = chatClient.GetChatThreadClient(threadId: createChatThreadResult.ChatThread.Id);
string threadId = chatThreadClient.Id;

Get a chat thread client

The GetChatThreadClient method returns a thread client for a thread that already exists. It can be used for performing operations on the created thread: add members, send message, etc. threadId is the unique ID of the existing chat thread.

string threadId = "<THREAD_ID>";
ChatThreadClient chatThreadClient = chatClient.GetChatThreadClient(threadId: threadId);

List all chat threads

Use GetChatThreads to retrieve all the chat threads that the user is part of.

AsyncPageable<ChatThreadItem> chatThreadItems = chatClient.GetChatThreadsAsync();
await foreach (ChatThreadItem chatThreadItem in chatThreadItems)
{
    Console.WriteLine($"{ chatThreadItem.Id}");
}

Send a message to a chat thread

Use SendMessage to send a message to a thread.

  • Use content to provide the content for the message, it is required.
  • Use type for the content type of the message such as 'Text' or 'Html'. If not specified, 'Text' will be set.
  • Use senderDisplayName to specify the display name of the sender. If not specified, empty string will be set.
SendChatMessageResult sendChatMessageResult = await chatThreadClient.SendMessageAsync(content:"hello world", type: ChatMessageType.Text);
string messageId = sendChatMessageResult.Id;

Receive chat messages from a chat thread

You can retrieve chat messages by polling the GetMessages method on the chat thread client at specified intervals.

AsyncPageable<ChatMessage> allMessages = chatThreadClient.GetMessagesAsync();
await foreach (ChatMessage message in allMessages)
{
    Console.WriteLine($"{message.Id}:{message.Content.Message}");
}

GetMessages takes an optional DateTimeOffset parameter. If that offset is specified, you will receive messages that were received, updated or deleted after it. Note that messages received before the offset time but edited or removed after it will also be returned.

GetMessages returns the latest version of the message, including any edits or deletes that happened to the message using UpdateMessage and DeleteMessage. For deleted messages, chatMessage.DeletedOn returns a datetime value indicating when that message was deleted. For edited messages, chatMessage.EditedOn returns a datetime indicating when the message was edited. The original time of message creation can be accessed using chatMessage.CreatedOn, and it can be used for ordering the messages.

GetMessages returns different types of messages which can be identified by chatMessage.Type. These types are:

  • Text: Regular chat message sent by a thread member.

  • Html: A formatted text message. Note that Communication Services users currently can't send RichText messages. This message type is supported by messages sent from Teams users to Communication Services users in Teams Interop scenarios.

  • TopicUpdated: System message that indicates the topic has been updated. (readonly)

  • ParticipantAdded: System message that indicates one or more participants have been added to the chat thread.(readonly)

  • ParticipantRemoved: System message that indicates a participant has been removed from the chat thread.

For more details, see Message Types.

Add a user as a participant to the chat thread

Once a thread is created, you can then add and remove users from it. By adding users, you give them access to be able to send messages to the thread, and add/remove other participant. Before calling AddParticipants, ensure that you have acquired a new access token and identity for that user. The user will need that access token in order to initialize their chat client.

Use AddParticipants to add one or more participants to the chat thread. The following are the supported attributes for each thread participant(s):

  • communicationUser, required, is the identity of the thread participant.
  • displayName, optional, is the display name for the thread participant.
  • shareHistoryTime, optional, time from which the chat history is shared with the participant.
var josh = new CommunicationUserIdentifier(id: "<Access_ID_For_Josh>");
var gloria = new CommunicationUserIdentifier(id: "<Access_ID_For_Gloria>");
var amy = new CommunicationUserIdentifier(id: "<Access_ID_For_Amy>");

var participants = new[]
{
    new ChatParticipant(josh) { DisplayName = "Josh" },
    new ChatParticipant(gloria) { DisplayName = "Gloria" },
    new ChatParticipant(amy) { DisplayName = "Amy" }
};

await chatThreadClient.AddParticipantsAsync(participants: participants);

Get thread participants

Use GetParticipants to retrieve the participants of the chat thread.

AsyncPageable<ChatParticipant> allParticipants = chatThreadClient.GetParticipantsAsync();
await foreach (ChatParticipant participant in allParticipants)
{
    Console.WriteLine($"{((CommunicationUserIdentifier)participant.User).Id}:{participant.DisplayName}:{participant.ShareHistoryTime}");
}

Send read receipt

Use SendReadReceipt to notify other participants that the message is read by the user.

await chatThreadClient.SendReadReceiptAsync(messageId: messageId);

Run the code

Run the application from your application directory with the dotnet run command.

dotnet run

Important

The Azure Communication Services Android, Python, and iOS Chat SDKs are currently in public preview. This preview version is provided without a service-level agreement, and it's not recommended for production workloads. Certain features might not be supported or might have constrained capabilities. For more information, see Supplemental Terms of Use for Microsoft Azure Previews.

Prerequisites

Before you get started, make sure to:

  • Create an Azure account with an active subscription. For details, see Create an account for free.
  • Install Xcode and CocoaPods. You use Xcode to create an iOS application for the quickstart, and CocoaPods to install dependencies.
  • Create an Azure Communication Services resource. For details, see Quickstart: Create and manage Communication Services resources. For this quickstart, you need to record your resource endpoint.
  • Create two users in Azure Communication Services, and issue them a user access token. Be sure to set the scope to chat, and note the token string as well as the userId string. In this quickstart, you create a thread with an initial participant, and then add a second participant to the thread.

Setting up

Create a new iOS application

Open Xcode and select Create a new Xcode project. Then select iOS as the platform and App for the template.

For the project name, enter ChatQuickstart. Then select Storyboard as the interface, UIKit App Delegate as the life cycle, and Swift as the language.

Select Next, and choose the directory where you want the project to be created.

Install the libraries

Use CocoaPods to install the necessary Communication Services dependencies.

From the command line, go inside the root directory of the ChatQuickstart iOS project. Create a Podfile with the following command: pod init.

Open the Podfile, and add the following dependencies to the ChatQuickstart target:

pod 'AzureCommunication', '~> 1.0.0-beta.11'
pod 'AzureCommunicationChat', '~> 1.0.0-beta.11'

Install the dependencies with the following command: pod install. Note that this also creates an Xcode workspace.

After running pod install, re-open the project in Xcode by selecting the newly created .xcworkspace.

Set up the placeholders

Open the workspace ChatQuickstart.xcworkspace in Xcode, and then open ViewController.swift.

In this quickstart, you add your code to viewController, and view the output in the Xcode console. This quickstart doesn't address building a user interface in iOS.

At the top of viewController.swift, import the AzureCommunication and AzureCommunicatonChat libraries:

import AzureCommunication
import AzureCommunicationChat

Copy the following code into the viewDidLoad() method of ViewController:

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let semaphore = DispatchSemaphore(value: 0)
        DispatchQueue.global(qos: .background).async {
            do {
                // <CREATE A CHAT CLIENT>
                
                // <CREATE A CHAT THREAD>

                // <LIST ALL CHAT THREADS>

                // <GET A CHAT THREAD CLIENT>

                // <SEND A MESSAGE>

                // <SEND A READ RECEIPT >

                // <RECEIVE MESSAGES>

                // <ADD A USER>
                
                // <LIST USERS>
            } catch {
                print("Quickstart failed: \(error.localizedDescription)")
            }
        }
    }

For demonstration purposes, we'll use a semaphore to synchronize your code. In following steps, you replace the placeholders with sample code by using the Azure Communication Services Chat library.

Create a chat client

Replace the comment <CREATE A CHAT CLIENT> with the following code:

let endpoint = "<ACS_RESOURCE_ENDPOINT>"
let credential =
try CommunicationTokenCredential(
    token: "<ACCESS_TOKEN>"
)
let options = AzureCommunicationChatClientOptions()

let chatClient = try ChatClient(
    endpoint: endpoint,
    credential: credential,
    withOptions: options
)

Replace <ACS_RESOURCE_ENDPOINT> with the endpoint of your Azure Communication Services resource. Replace <ACCESS_TOKEN> with a valid Communication Services access token.

This quickstart doesn't cover creating a service tier to manage tokens for your chat application, but that's recommended. For more information, see the "Chat architecture" section of Chat concepts.

For more information about user access tokens, see Quickstart: Create and manage access tokens.

Object model

The following classes and interfaces handle some of the major features of the Azure Communication Services Chat SDK for JavaScript.

Name Description
ChatClient This class is needed for the chat functionality. You instantiate it with your subscription information, and use it to create, get, and delete threads.
ChatThreadClient This class is needed for the chat thread functionality. You obtain an instance via ChatClient, and use it to send, receive, update, and delete messages. You can also use it to add, remove, and get users, send typing notifications and read receipts, and subscribe to chat events.

Start a chat thread

Now you use your ChatClient to create a new thread with an initial user.

Replace the comment <CREATE A CHAT THREAD> with the following code:

let request = CreateChatThreadRequest(
    topic: "Quickstart",
    participants: [
        ChatParticipant(
            id: CommunicationUserIdentifier("<USER_ID>"),
            displayName: "Jack"
        )
    ]
)

var threadId: String?
chatClient.create(thread: request) { result, _ in
    switch result {
    case let .success(result):
        threadId = result.chatThread?.id

    case .failure:
        fatalError("Failed to create thread.")
    }
    semaphore.signal()
}
semaphore.wait()

Replace <USER_ID> with a valid Communication Services user ID.

You're using a semaphore here to wait for the completion handler before continuing. In later steps, you'll use the threadId from the response returned to the completion handler.

List all chat threads

After creating a chat thread we can list all chat threads by calling the listChatThreads method on ChatClient. Replace the comment <LIST ALL CHAT THREADS> with the following code:

chatClient.listThreads { result, _ in
    switch result {
    case let .success(chatThreadItems):
        var iterator = chatThreadItems.syncIterator
            while let chatThreadItem = iterator.next() {
                print("Thread id: \(chatThreadItem.id)")
            }
    case .failure:
        print("Failed to list threads")
    }
    semaphore.signal()
}
semaphore.wait()

Get a chat thread client

Now that you've created a chat thread, you can obtain a ChatThreadClient to perform operations within the thread.

Replace the comment <GET A CHAT THREAD CLIENT> with the following code:

let chatThreadClient = try chatClient.createClient(forThread: threadId!)

Send a message to a chat thread

Replace the comment <SEND A MESSAGE> with the following code:

let message = SendChatMessageRequest(
    content: "Hello!",
    senderDisplayName: "Jack"
)

var messageId: String?

chatThreadClient.send(message: message) { result, _ in
    switch result {
    case let .success(result):
        print("Message sent, message id: \(result.id)")
        messageId = result.id
    case .failure:
        print("Failed to send message")
    }
    semaphore.signal()
}
semaphore.wait()

First, you construct the SendChatMessageRequest, which contains the content and sender's display name. This request can also contain the share history time, if you want to include it. The response returned to the completion handler contains the ID of the message that was sent.

Send a read receipt

You can send a read receipt for a particular message by calling ChatThreadClients sendReadReceipt method. Replace the comment <SEND A READ RECEIPT> with the following code:

if let id = messageId {
    chatThreadClient.sendReadReceipt(forMessage: id) { result, _ in
        switch result {
        case .success:
            print("Read receipt sent")
        case .failure:
            print("Failed to send read receipt")
        }
        semaphore.signal()
    }
    semaphore.wait()
} else {
    print("Cannot send read receipt without a message id")
}

Receive chat messages from a chat thread

You can receive messages from a chat thread by calling the listMessages() method from ChatThreadClient. List messages includes system messages as well as user sent messages. For more information on the types of messages you can receive see Message Types

Replace the comment <RECEIVE MESSAGES> with the following code:

chatThreadClient.listMessages { result, _ in
    switch result {
    case let .success(messages):
        var iterator = messages.syncIterator
        while let message = iterator.next() {
            print("Received message of type \(message.type)")
        }

    case .failure:
        print("Failed to receive messages")
    }
    semaphore.signal()
}
semaphore.wait()

Add a user as a participant to the chat thread

Replace the comment <ADD A USER> with the following code:

let user = ChatParticipant(
    id: CommunicationUserIdentifier("<USER_ID>"),
    displayName: "Jane"
)

chatThreadClient.add(participants: [user]) { result, _ in
    switch result {
    case let .success(result):
        (result.invalidParticipants != nil) ? print("Added participant") : print("Error adding participant")
    case .failure:
        print("Failed to add the participant")
    }
    semaphore.signal()
}
semaphore.wait()

Replace <USER_ID> with the Communication Services user ID of the user to be added.

When you're adding a participant to a thread, the response returned might contain errors. These errors represent failure to add particular participants.

List users in a thread

Replace the <LIST USERS> comment with the following code:

chatThreadClient.listParticipants { result, _ in
    switch result {
    case let .success(participants):
        var iterator = participants.syncIterator
        while let participant = iterator.next() {
            let user = participant.id as! CommunicationUserIdentifier
            print("User with id: \(user.identifier)")
        }
    case .failure:
        print("Failed to list participants")
    }
    semaphore.signal()
}
semaphore.wait()

Run the code

In Xcode hit the Run button to build and run the project. In the console you can view the output from the code and the logger output from the ChatClient.

Clean up resources

If you want to clean up and remove a Communication Services subscription, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it. Learn more about cleaning up resources.

Next steps

In this quickstart you learned how to:

  • Create a chat client
  • Create a thread with two users
  • Send a message to the thread
  • Receive messages from a thread
  • Remove Users from a thread

You may also want to: