# Send outbound messages via SMS, WhatsApp, and other Channels

> \[!NOTE]
>
> This guide is for Flex UI 1.x.x and channels that use Programmable Chat and Proxy. Programmable Chat for Flex will reach end of life on June 1, 2026. If you're new to Flex or currently using Programmable Chat, [build with Flex Conversations](/docs/flex/conversations) or [migrate](/docs/flex/developer/conversations/programmable-chat-to-flex-conversations).

Flex allows your agents to initiate conversations with your customers using any Twilio Messaging Channel, including SMS, WhatsApp, and Facebook Messenger.

Currently, outbound messages require additional development work. This page outlines some of the work you'll need to do for the backend but outbound messages will also require a Flex UI Plugin to expose the functionality in the Flex interface.

## Managing Task creation

There are two ways to handle Task creation for outbound messages: [when the agent messages the customer](#create-task-when-agent-messages-customer) (immediately) or when the [customer responds to the outbound message](#create-task-when-customer-responds) (delayed).

> \[!NOTE]
>
> Outbound messages require a Flex Flow `ChannelType` of `sms`, `whatsapp`, `facebook`, or `custom.`

## Create Task when agent messages customer

The following steps will create a Task when you send an outbound message to your customer.

### Step 1: Define a Flex Flow

First, define an outbound Flex Flow with an Integration type of `task`. You only need to do this once. Ensure you are also defining your Flex Flow to use a Messaging capable Task Channel such as `sms` or `chat`. If you already have a Flex Flow that's using Studio, set the `enabled` parameter to `false`.

Strategy 1: Create a Flex Flow

```js
// Download the helper library from https://www.twilio.com/docs/node/install
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);

async function createFlexFlow() {
  const flexFlow = await client.flexApi.v1.flexFlow.create({
    channelType: "sms",
    chatServiceSid: "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXNone",
    contactIdentity: "+12XXXXXXXXX",
    enabled: false,
    friendlyName: "Outbound SMS",
    "integration.channel": "TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "integration.workflowSid": "WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "integration.workspaceSid": "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    integrationType: "task",
  });

  console.log(flexFlow.accountSid);
}

createFlexFlow();
```

```python
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
client = Client(account_sid, auth_token)

flex_flow = client.flex_api.v1.flex_flow.create(
    contact_identity="+12XXXXXXXXX",
    channel_type="sms",
    chat_service_sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXNone",
    integration_type="task",
    integration_workflow_sid="WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    integration_workspace_sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    integration_channel="TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    friendly_name="Outbound SMS",
    enabled=False,
)

print(flex_flow.account_sid)
```

```csharp
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.FlexApi.V1;
using System.Threading.Tasks;

class Program {
    public static async Task Main(string[] args) {
        // Find your Account SID and Auth Token at twilio.com/console
        // and set the environment variables. See http://twil.io/secure
        string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        TwilioClient.Init(accountSid, authToken);

        var flexFlow = await FlexFlowResource.CreateAsync(
            contactIdentity: "+12XXXXXXXXX",
            channelType: FlexFlowResource.ChannelTypeEnum.Sms,
            chatServiceSid: "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXNone",
            integrationType: FlexFlowResource.IntegrationTypeEnum.Task,
            integrationWorkflowSid: "WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            integrationWorkspaceSid: "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            integrationChannel: "TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            friendlyName: "Outbound SMS",
            enabled: false);

        Console.WriteLine(flexFlow.AccountSid);
    }
}
```

```java
// Install the Java helper library from twilio.com/docs/java/install

import com.twilio.Twilio;
import com.twilio.rest.flexapi.v1.FlexFlow;

public class Example {
    // Find your Account SID and Auth Token at twilio.com/console
    // and set the environment variables. See http://twil.io/secure
    public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
    public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
        FlexFlow flexFlow =
            FlexFlow.creator("Outbound SMS", "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXNone", FlexFlow.ChannelType.SMS)
                .setContactIdentity("+12XXXXXXXXX")
                .setIntegrationType(FlexFlow.IntegrationType.TASK)
                .setIntegrationWorkflowSid("WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                .setIntegrationWorkspaceSid("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                .setIntegrationChannel("TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                .setEnabled(false)
                .create();

        System.out.println(flexFlow.getAccountSid());
    }
}
```

```go
// Download the helper library from https://www.twilio.com/docs/go/install
package main

import (
	"fmt"
	"github.com/twilio/twilio-go"
	flex "github.com/twilio/twilio-go/rest/flex/v1"
	"os"
)

func main() {
	// Find your Account SID and Auth Token at twilio.com/console
	// and set the environment variables. See http://twil.io/secure
	// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment
	client := twilio.NewRestClient()

	params := &flex.CreateFlexFlowParams{}
	params.SetContactIdentity("+12XXXXXXXXX")
	params.SetChannelType("sms")
	params.SetChatServiceSid("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXNone")
	params.SetIntegrationType("task")
	params.SetIntegrationWorkflowSid("WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
	params.SetIntegrationWorkspaceSid("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
	params.SetIntegrationChannel("TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
	params.SetFriendlyName("Outbound SMS")
	params.SetEnabled(false)

	resp, err := client.FlexV1.CreateFlexFlow(params)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		if resp.AccountSid != nil {
			fmt.Println(*resp.AccountSid)
		} else {
			fmt.Println(resp.AccountSid)
		}
	}
}
```

```php
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "/path/to/vendor/autoload.php";

use Twilio\Rest\Client;

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = getenv("TWILIO_ACCOUNT_SID");
$token = getenv("TWILIO_AUTH_TOKEN");
$twilio = new Client($sid, $token);

$flex_flow = $twilio->flexApi->v1->flexFlow->create(
    "Outbound SMS", // FriendlyName
    "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXNone", // ChatServiceSid
    "sms", // ChannelType
    [
        "contactIdentity" => "+12XXXXXXXXX",
        "integrationType" => "task",
        "integrationWorkflowSid" => "WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
        "integrationWorkspaceSid" => "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
        "integrationChannel" => "TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
        "enabled" => false,
    ]
);

print $flex_flow->accountSid;
```

```ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'twilio-ruby'

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)

flex_flow = @client
            .flex_api
            .v1
            .flex_flow
            .create(
              contact_identity: '+12XXXXXXXXX',
              channel_type: 'sms',
              chat_service_sid: 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXNone',
              integration_type: 'task',
              integration_workflow_sid: 'WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
              integration_workspace_sid: 'WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
              integration_channel: 'TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
              friendly_name: 'Outbound SMS',
              enabled: false
            )

puts flex_flow.account_sid
```

```bash
# Install the twilio-cli from https://twil.io/cli

twilio api:flex:v1:flex-flows:create \
   --contact-identity +12XXXXXXXXX \
   --channel-type sms \
   --chat-service-sid ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXNone \
   --integration-type task \
   --integration.workflow-sid WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \
   --integration.workspace-sid WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \
   --integration.channel TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \
   --friendly-name "Outbound SMS"
```

```bash
curl -X POST "https://flex-api.twilio.com/v1/FlexFlows" \
--data-urlencode "ContactIdentity=+12XXXXXXXXX" \
--data-urlencode "ChannelType=sms" \
--data-urlencode "ChatServiceSid=ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXNone" \
--data-urlencode "IntegrationType=task" \
--data-urlencode "Integration.WorkflowSid=WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
--data-urlencode "Integration.WorkspaceSid=WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
--data-urlencode "Integration.Channel=TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
--data-urlencode "FriendlyName=Outbound SMS" \
--data-urlencode "Enabled=false" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
```

```json
{
  "sid": "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "date_created": "2016-08-01T22:10:40Z",
  "date_updated": "2016-08-01T22:10:40Z",
  "friendly_name": "Outbound SMS",
  "chat_service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXNone",
  "channel_type": "sms",
  "contact_identity": "+12XXXXXXXXX",
  "enabled": false,
  "integration_type": "task",
  "integration": {
    "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "retry_count": 1
  },
  "long_lived": true,
  "janitor_enabled": true,
  "url": "https://flex-api.twilio.com/v1/FlexFlows/FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
```

### Step 2: Create a Flex Chat Channel

Next, create a Chat Channel using the Flex API to initiate messaging with the customer. In this example, the API call also adds Task attributes, which will allow the channel to route the Task to a specific agent (using the `targetWorker` Workflow expression).

Make sure to save the Chat Channel SID, as you'll need it later.

Outbound Flex Channel with TaskRouter integration

```js
// Download the helper library from https://www.twilio.com/docs/node/install
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);

async function createChannel() {
  const channel = await client.flexApi.v1.channel.create({
    chatFriendlyName: "Outbound Chat with John",
    chatUserFriendlyName: "ChatUserFriendlyName",
    flexFlowSid: "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    identity: "sms_18001231234",
    target: "+18001231234",
    taskAttributes: JSON.stringify({
      to: "+18001231234",
      direction: "outbound",
      name: "John",
      from: "+18005555555",
      targetWorker: "reference_worker_attribute_contact_uri_here",
      autoAnswer: "true",
    }),
  });

  console.log(channel.accountSid);
}

createChannel();
```

```python
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client
import json

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
client = Client(account_sid, auth_token)

channel = client.flex_api.v1.channel.create(
    identity="sms_18001231234",
    target="+18001231234",
    chat_friendly_name="Outbound Chat with John",
    task_attributes=json.dumps(
        {
            "to": "+18001231234",
            "direction": "outbound",
            "name": "John",
            "from": "+18005555555",
            "targetWorker": "reference_worker_attribute_contact_uri_here",
            "autoAnswer": "true",
        }
    ),
    flex_flow_sid="FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    chat_user_friendly_name="ChatUserFriendlyName",
)

print(channel.account_sid)
```

```csharp
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.FlexApi.V1;
using System.Threading.Tasks;
using System.Collections.Generic;
using Newtonsoft.Json;

class Program {
    public static async Task Main(string[] args) {
        // Find your Account SID and Auth Token at twilio.com/console
        // and set the environment variables. See http://twil.io/secure
        string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        TwilioClient.Init(accountSid, authToken);

        var channel = await ChannelResource.CreateAsync(
            identity: "sms_18001231234",
            target: "+18001231234",
            chatFriendlyName: "Outbound Chat with John",
            taskAttributes: JsonConvert.SerializeObject(
                new Dictionary<string, Object>() {
                    { "to", "+18001231234" },
                    { "direction", "outbound" },
                    { "name", "John" },
                    { "from", "+18005555555" },
                    { "targetWorker", "reference_worker_attribute_contact_uri_here" },
                    { "autoAnswer", "true" }
                },
                Formatting.Indented),
            flexFlowSid: "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            chatUserFriendlyName: "ChatUserFriendlyName");

        Console.WriteLine(channel.AccountSid);
    }
}
```

```java
// Install the Java helper library from twilio.com/docs/java/install

import java.util.HashMap;
import com.twilio.Twilio;
import com.twilio.rest.flexapi.v1.Channel;
import org.json.JSONObject;

public class Example {
    // Find your Account SID and Auth Token at twilio.com/console
    // and set the environment variables. See http://twil.io/secure
    public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
    public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
        Channel channel = Channel
                              .creator("FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                                  "sms_18001231234",
                                  "ChatUserFriendlyName",
                                  "Outbound Chat with John")
                              .setTarget("+18001231234")
                              .setTaskAttributes(new JSONObject(new HashMap<String, Object>() {
                                  {
                                      put("to", "+18001231234");
                                      put("direction", "outbound");
                                      put("name", "John");
                                      put("from", "+18005555555");
                                      put("targetWorker", "reference_worker_attribute_contact_uri_here");
                                      put("autoAnswer", "true");
                                  }
                              }).toString())
                              .create();

        System.out.println(channel.getAccountSid());
    }
}
```

```go
// Download the helper library from https://www.twilio.com/docs/go/install
package main

import (
	"encoding/json"
	"fmt"
	"github.com/twilio/twilio-go"
	flex "github.com/twilio/twilio-go/rest/flex/v1"
	"os"
)

func main() {
	// Find your Account SID and Auth Token at twilio.com/console
	// and set the environment variables. See http://twil.io/secure
	// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment
	client := twilio.NewRestClient()

	TaskAttributes, TaskAttributesError := json.Marshal(map[string]interface{}{
		"to":           "+18001231234",
		"direction":    "outbound",
		"name":         "John",
		"from":         "+18005555555",
		"targetWorker": "reference_worker_attribute_contact_uri_here",
		"autoAnswer":   "true",
	})

	if TaskAttributesError != nil {
		fmt.Println(TaskAttributesError)
		os.Exit(1)
	}

	params := &flex.CreateChannelParams{}
	params.SetIdentity("sms_18001231234")
	params.SetTarget("+18001231234")
	params.SetChatFriendlyName("Outbound Chat with John")
	params.SetTaskAttributes(string(TaskAttributes))
	params.SetFlexFlowSid("FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
	params.SetChatUserFriendlyName("ChatUserFriendlyName")

	resp, err := client.FlexV1.CreateChannel(params)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		if resp.AccountSid != nil {
			fmt.Println(*resp.AccountSid)
		} else {
			fmt.Println(resp.AccountSid)
		}
	}
}
```

```php
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "/path/to/vendor/autoload.php";

use Twilio\Rest\Client;

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = getenv("TWILIO_ACCOUNT_SID");
$token = getenv("TWILIO_AUTH_TOKEN");
$twilio = new Client($sid, $token);

$channel = $twilio->flexApi->v1->channel->create(
    "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // FlexFlowSid
    "sms_18001231234", // Identity
    "ChatUserFriendlyName", // ChatUserFriendlyName
    "Outbound Chat with John", // ChatFriendlyName
    [
        "target" => "+18001231234",
        "taskAttributes" => json_encode([
            "to" => "+18001231234",
            "direction" => "outbound",
            "name" => "John",
            "from" => "+18005555555",
            "targetWorker" => "reference_worker_attribute_contact_uri_here",
            "autoAnswer" => "true",
        ]),
    ]
);

print $channel->accountSid;
```

```ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'twilio-ruby'

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)

channel = @client
          .flex_api
          .v1
          .channel
          .create(
            identity: 'sms_18001231234',
            target: '+18001231234',
            chat_friendly_name: 'Outbound Chat with John',
            task_attributes: {
                'to' => '+18001231234',
                'direction' => 'outbound',
                'name' => 'John',
                'from' => '+18005555555',
                'targetWorker' => 'reference_worker_attribute_contact_uri_here',
                'autoAnswer' => 'true'
              }.to_json,
            flex_flow_sid: 'FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
            chat_user_friendly_name: 'ChatUserFriendlyName'
          )

puts channel.account_sid
```

```bash
# Install the twilio-cli from https://twil.io/cli

twilio api:flex:v1:channels:create \
   --identity sms_18001231234 \
   --target +18001231234 \
   --chat-friendly-name "Outbound Chat with John" \
   --task-attributes "{ \"to\": \"+18001231234\", \"direction\": \"outbound\", \"name\": \"John\", \"from\": \"+18005555555\", \"targetWorker\": \"reference_worker_attribute_contact_uri_here\", \"autoAnswer\": \"true\" }" \
   --flex-flow-sid FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \
   --chat-user-friendly-name ChatUserFriendlyName
```

```bash
TASK_ATTRIBUTES_OBJ=$(cat << EOF
{
  "to": "+18001231234",
  "direction": "outbound",
  "name": "John",
  "from": "+18005555555",
  "targetWorker": "reference_worker_attribute_contact_uri_here",
  "autoAnswer": "true"
}
EOF
)
curl -X POST "https://flex-api.twilio.com/v1/Channels" \
--data-urlencode "Identity=sms_18001231234" \
--data-urlencode "Target=+18001231234" \
--data-urlencode "ChatFriendlyName=Outbound Chat with John" \
--data-urlencode "TaskAttributes=$TASK_ATTRIBUTES_OBJ" \
--data-urlencode "FlexFlowSid=FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \
--data-urlencode "ChatUserFriendlyName=ChatUserFriendlyName" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
```

```json
{
  "flex_flow_sid": "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "task_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "date_created": "2016-08-01T22:10:40Z",
  "date_updated": "2016-08-01T22:10:40Z",
  "url": "https://flex-api.twilio.com/v1/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
```

Once the Flex Channel API is executed successfully, two things happen:

* A new chat channel is created
* A new task is created and assigned to the worker specified in `targetWorker`

Then, if you open the Flex UI for `targetWorker`, you should see the following new reservation:

### Step 3: Set up a Twilio Proxy session

Now that you have a channel, you'll want to associate it with a Proxy Session. Sessions offer a useful layer of state and metadata that Flex uses to ensure that your customers' messages stay properly threaded as they are processed by bots, TaskRouter and agents.

You'll need to make two requests:

The first creates the Proxy Session, and includes the person you're trying to reach.

The second request adds the chat channel to the session and maps it to the Contact Center number.

> \[!NOTE]
>
> Consider enabling the Channel Janitor to help manage any stale chat sessions.

Strategy 1: Create a Proxy Session for Chat Channel

```js
// Download the helper library from https://www.twilio.com/docs/node/install
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);

async function createSession() {
  const session = await client.proxy.v1
    .services("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    .sessions.create({
      mode: "message-only",
      participants: [
        {
          Identifier: "CUSTOMER_NUMBER",
        },
      ],
      uniqueName: "SID_FROM_CHANNELS_API",
    });

  console.log(session.sid);
}

createSession();
```

```python
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
client = Client(account_sid, auth_token)

session = client.proxy.v1.services(
    "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
).sessions.create(
    unique_name="SID_FROM_CHANNELS_API",
    mode="message-only",
    participants=[{"Identifier": "CUSTOMER_NUMBER"}],
)

print(session.sid)
```

```csharp
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Proxy.V1.Service;
using System.Threading.Tasks;
using System.Collections.Generic;

class Program {
    public static async Task Main(string[] args) {
        // Find your Account SID and Auth Token at twilio.com/console
        // and set the environment variables. See http://twil.io/secure
        string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        TwilioClient.Init(accountSid, authToken);

        var session = await SessionResource.CreateAsync(
            uniqueName: "SID_FROM_CHANNELS_API",
            mode: SessionResource.ModeEnum.MessageOnly,
            participants: new List<Object> { new Dictionary<string, Object>() {
                { "Identifier", "CUSTOMER_NUMBER" }
            } },
            pathServiceSid: "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");

        Console.WriteLine(session.Sid);
    }
}
```

```java
// Install the Java helper library from twilio.com/docs/java/install

import java.util.Arrays;
import java.util.HashMap;
import com.twilio.Twilio;
import com.twilio.rest.proxy.v1.service.Session;

public class Example {
    // Find your Account SID and Auth Token at twilio.com/console
    // and set the environment variables. See http://twil.io/secure
    public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
    public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
        Session session = Session.creator("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
                              .setUniqueName("SID_FROM_CHANNELS_API")
                              .setMode(Session.Mode.MESSAGE_ONLY)
                              .setParticipants(Arrays.asList(new HashMap<String, Object>() {
                                  {
                                      put("Identifier", "CUSTOMER_NUMBER");
                                  }
                              }))
                              .create();

        System.out.println(session.getSid());
    }
}
```

```go
// Download the helper library from https://www.twilio.com/docs/go/install
package main

import (
	"fmt"
	"github.com/twilio/twilio-go"
	proxy "github.com/twilio/twilio-go/rest/proxy/v1"
	"os"
)

func main() {
	// Find your Account SID and Auth Token at twilio.com/console
	// and set the environment variables. See http://twil.io/secure
	// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment
	client := twilio.NewRestClient()

	params := &proxy.CreateSessionParams{}
	params.SetUniqueName("SID_FROM_CHANNELS_API")
	params.SetMode("message-only")
	params.SetParticipants([]interface{}{
		map[string]interface{}{
			"Identifier": "CUSTOMER_NUMBER",
		},
	})

	resp, err := client.ProxyV1.CreateSession("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
		params)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		if resp.Sid != nil {
			fmt.Println(*resp.Sid)
		} else {
			fmt.Println(resp.Sid)
		}
	}
}
```

```php
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "/path/to/vendor/autoload.php";

use Twilio\Rest\Client;

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = getenv("TWILIO_ACCOUNT_SID");
$token = getenv("TWILIO_AUTH_TOKEN");
$twilio = new Client($sid, $token);

$session = $twilio->proxy->v1
    ->services("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    ->sessions->create([
        "uniqueName" => "SID_FROM_CHANNELS_API",
        "mode" => "message-only",
        "participants" => [
            [
                "Identifier" => "CUSTOMER_NUMBER",
            ],
        ],
    ]);

print $session->sid;
```

```ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'twilio-ruby'

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)

session = @client
          .proxy
          .v1
          .services('KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
          .sessions
          .create(
            unique_name: 'SID_FROM_CHANNELS_API',
            mode: 'message-only',
            participants: [
              {
                'Identifier' => 'CUSTOMER_NUMBER'
              }
            ]
          )

puts session.sid
```

```bash
# Install the twilio-cli from https://twil.io/cli

twilio api:proxy:v1:services:sessions:create \
   --service-sid KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \
   --unique-name SID_FROM_CHANNELS_API \
   --mode message-only \
   --participants "{\"Identifier\":\"CUSTOMER_NUMBER\"}"
```

```bash
curl -X POST "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions" \
--data-urlencode "UniqueName=SID_FROM_CHANNELS_API" \
--data-urlencode "Mode=message-only" \
--data-urlencode "Participants={\"Identifier\":\"CUSTOMER_NUMBER\"}" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
```

```json
{
  "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "status": "open",
  "unique_name": "SID_FROM_CHANNELS_API",
  "date_started": "2015-07-30T20:00:00Z",
  "date_ended": "2015-07-30T20:00:00Z",
  "date_last_interaction": "2015-07-30T20:00:00Z",
  "date_expiry": "2015-07-30T20:00:00Z",
  "ttl": 3600,
  "mode": "message-only",
  "closed_reason": "",
  "sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "date_updated": "2015-07-30T20:00:00Z",
  "date_created": "2015-07-30T20:00:00Z",
  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "links": {
    "interactions": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Interactions",
    "participants": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants"
  }
}
```

In the sample code, you need to replace:

| Attribute                   | Description                                                                                                                         |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `{{CUSTOMER_NUMBER}}`       | The phone number of the customer you are trying to reach                                                                            |
| `{{SID_FROM_CHANNELS_API}}` | The Chat Channel SID created in Step 2. Here, it is being used as a name for the Proxy Session, which helps you (and Flex) find it. |

You'll also need to add the agent to the Proxy Session, using their Chat Channel SID as their identifier and the Contact Center number as their Proxy identifier, since messages from the agent should look like they're coming from the Contact Center.

Finally, if you want the agent to see the Customer's number when they respond to the chat, make the Agent's friendly name the customer's number.

Strategy 1: Add the Agent to the Proxy Session

```js
// Download the helper library from https://www.twilio.com/docs/node/install
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);

async function createParticipant() {
  const participant = await client.proxy.v1
    .services("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    .sessions("KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    .participants.create({
      friendlyName: "CUSTOMER_NUMBER",
      identifier: "CHAT_CHANNEL_SID",
      proxyIdentifier: "CONTACT_CENTER_NUMBER",
    });

  console.log(participant.sid);
}

createParticipant();
```

```python
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
client = Client(account_sid, auth_token)

participant = (
    client.proxy.v1.services("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    .sessions("KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    .participants.create(
        identifier="CHAT_CHANNEL_SID",
        proxy_identifier="CONTACT_CENTER_NUMBER",
        friendly_name="CUSTOMER_NUMBER",
    )
)

print(participant.sid)
```

```csharp
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Proxy.V1.Service.Session;
using System.Threading.Tasks;

class Program {
    public static async Task Main(string[] args) {
        // Find your Account SID and Auth Token at twilio.com/console
        // and set the environment variables. See http://twil.io/secure
        string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        TwilioClient.Init(accountSid, authToken);

        var participant = await ParticipantResource.CreateAsync(
            identifier: "CHAT_CHANNEL_SID",
            proxyIdentifier: "CONTACT_CENTER_NUMBER",
            friendlyName: "CUSTOMER_NUMBER",
            pathServiceSid: "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            pathSessionSid: "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");

        Console.WriteLine(participant.Sid);
    }
}
```

```java
// Install the Java helper library from twilio.com/docs/java/install

import com.twilio.Twilio;
import com.twilio.rest.proxy.v1.service.session.Participant;

public class Example {
    // Find your Account SID and Auth Token at twilio.com/console
    // and set the environment variables. See http://twil.io/secure
    public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
    public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
        Participant participant =
            Participant
                .creator("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "CHAT_CHANNEL_SID")
                .setProxyIdentifier("CONTACT_CENTER_NUMBER")
                .setFriendlyName("CUSTOMER_NUMBER")
                .create();

        System.out.println(participant.getSid());
    }
}
```

```go
// Download the helper library from https://www.twilio.com/docs/go/install
package main

import (
	"fmt"
	"github.com/twilio/twilio-go"
	proxy "github.com/twilio/twilio-go/rest/proxy/v1"
	"os"
)

func main() {
	// Find your Account SID and Auth Token at twilio.com/console
	// and set the environment variables. See http://twil.io/secure
	// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment
	client := twilio.NewRestClient()

	params := &proxy.CreateParticipantParams{}
	params.SetIdentifier("CHAT_CHANNEL_SID")
	params.SetProxyIdentifier("CONTACT_CENTER_NUMBER")
	params.SetFriendlyName("CUSTOMER_NUMBER")

	resp, err := client.ProxyV1.CreateParticipant("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
		"KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
		params)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		if resp.Sid != nil {
			fmt.Println(*resp.Sid)
		} else {
			fmt.Println(resp.Sid)
		}
	}
}
```

```php
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "/path/to/vendor/autoload.php";

use Twilio\Rest\Client;

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = getenv("TWILIO_ACCOUNT_SID");
$token = getenv("TWILIO_AUTH_TOKEN");
$twilio = new Client($sid, $token);

$participant = $twilio->proxy->v1
    ->services("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    ->sessions("KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    ->participants->create(
        "CHAT_CHANNEL_SID", // Identifier
        [
            "proxyIdentifier" => "CONTACT_CENTER_NUMBER",
            "friendlyName" => "CUSTOMER_NUMBER",
        ]
    );

print $participant->sid;
```

```ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'twilio-ruby'

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)

participant = @client
              .proxy
              .v1
              .services('KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
              .sessions('KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
              .participants
              .create(
                identifier: 'CHAT_CHANNEL_SID',
                proxy_identifier: 'CONTACT_CENTER_NUMBER',
                friendly_name: 'CUSTOMER_NUMBER'
              )

puts participant.sid
```

```bash
# Install the twilio-cli from https://twil.io/cli

twilio api:proxy:v1:services:sessions:participants:create \
   --service-sid KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \
   --session-sid KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \
   --identifier CHAT_CHANNEL_SID \
   --proxy-identifier CONTACT_CENTER_NUMBER \
   --friendly-name CUSTOMER_NUMBER
```

```bash
curl -X POST "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants" \
--data-urlencode "Identifier=CHAT_CHANNEL_SID" \
--data-urlencode "ProxyIdentifier=CONTACT_CENTER_NUMBER" \
--data-urlencode "FriendlyName=CUSTOMER_NUMBER" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
```

```json
{
  "sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "session_sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "identifier": "CHAT_CHANNEL_SID",
  "proxy_identifier": "CONTACT_CENTER_NUMBER",
  "proxy_identifier_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "friendly_name": "CUSTOMER_NUMBER",
  "date_deleted": "2015-07-30T20:00:00Z",
  "date_updated": "2015-07-30T20:00:00Z",
  "date_created": "2015-07-30T20:00:00Z",
  "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "links": {
    "message_interactions": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessageInteractions"
  }
}
```

In the sample code, you need to replace:

| `CONTACT_CENTER_NUMBER` | This is the contact center phone number, channel number, or agent number from which the message will be sent. This is likely the same number you used as `contactIdentity` when you created the Flex Flow. |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `CHAT_CHANNEL_SID`      | The Chat Channel SID you created using the Channel API in Step 2. This tells Proxy that the agent will be sending messages over this channel.                                                              |

### Step 4: Update the Chat Channel attributes

Update the Chat Channel `attributes` to include the Proxy Session SID you created in Step 3 if it's not already there. The chat channel attributes should be a JSON string:

`{proxySession: "KCXXXXXXXXXXXXXXXXXXXXXXXX"}`

Make sure that you retrieve the existing attributes object, add the `proxySession` key, and then update the parameter as a string.

Node.js Example:

```javascript
.then(
    attributes => {
        return Object.assign(JSON.parse(attributes.attributes), { proxySession: proxySession.sid })
    }
))
```

Strategy 1: Update Chat Channel Attributes

```js
// Download the helper library from https://www.twilio.com/docs/node/install
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);

async function updateChannel() {
  const channel = await client.chat.v2
    .services("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    .channels("Sid")
    .update({
      attributes: JSON.stringify({
        proxySession: "KCXXXXXXXXXXXXXXXXXXXXXXXX",
      }),
    });

  console.log(channel.sid);
}

updateChannel();
```

```python
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client
import json

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
client = Client(account_sid, auth_token)

channel = (
    client.chat.v2.services("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    .channels("Sid")
    .update(
        attributes=json.dumps({"proxySession": "KCXXXXXXXXXXXXXXXXXXXXXXXX"})
    )
)

print(channel.sid)
```

```csharp
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Chat.V2.Service;
using System.Threading.Tasks;
using System.Collections.Generic;
using Newtonsoft.Json;

class Program {
    public static async Task Main(string[] args) {
        // Find your Account SID and Auth Token at twilio.com/console
        // and set the environment variables. See http://twil.io/secure
        string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        TwilioClient.Init(accountSid, authToken);

        var channel = await ChannelResource.UpdateAsync(
            attributes: JsonConvert.SerializeObject(
                new Dictionary<string, Object>() {
                    { "proxySession", "KCXXXXXXXXXXXXXXXXXXXXXXXX" }
                },
                Formatting.Indented),
            pathServiceSid: "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            pathSid: "Sid");

        Console.WriteLine(channel.Sid);
    }
}
```

```java
// Install the Java helper library from twilio.com/docs/java/install

import java.util.HashMap;
import com.twilio.Twilio;
import com.twilio.rest.chat.v2.service.Channel;
import org.json.JSONObject;

public class Example {
    // Find your Account SID and Auth Token at twilio.com/console
    // and set the environment variables. See http://twil.io/secure
    public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
    public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
        Channel channel = Channel.updater("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "Sid")
                              .setAttributes(new JSONObject(new HashMap<String, Object>() {
                                  {
                                      put("proxySession", "KCXXXXXXXXXXXXXXXXXXXXXXXX");
                                  }
                              }).toString())
                              .update();

        System.out.println(channel.getSid());
    }
}
```

```go
// Download the helper library from https://www.twilio.com/docs/go/install
package main

import (
	"encoding/json"
	"fmt"
	"github.com/twilio/twilio-go"
	chat "github.com/twilio/twilio-go/rest/chat/v2"
	"os"
)

func main() {
	// Find your Account SID and Auth Token at twilio.com/console
	// and set the environment variables. See http://twil.io/secure
	// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment
	client := twilio.NewRestClient()

	Attributes, AttributesError := json.Marshal(map[string]interface{}{
		"proxySession": "KCXXXXXXXXXXXXXXXXXXXXXXXX",
	})

	if AttributesError != nil {
		fmt.Println(AttributesError)
		os.Exit(1)
	}

	params := &chat.UpdateChannelParams{}
	params.SetAttributes(string(Attributes))

	resp, err := client.ChatV2.UpdateChannel("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
		"Sid",
		params)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		if resp.Sid != nil {
			fmt.Println(*resp.Sid)
		} else {
			fmt.Println(resp.Sid)
		}
	}
}
```

```php
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "/path/to/vendor/autoload.php";

use Twilio\Rest\Client;

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = getenv("TWILIO_ACCOUNT_SID");
$token = getenv("TWILIO_AUTH_TOKEN");
$twilio = new Client($sid, $token);

$channel = $twilio->chat->v2
    ->services("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    ->channels("Sid")
    ->update([
        "attributes" => json_encode([
            "proxySession" => "KCXXXXXXXXXXXXXXXXXXXXXXXX",
        ]),
    ]);

print $channel->sid;
```

```ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'twilio-ruby'

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)

channel = @client
          .chat
          .v2
          .services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
          .channels('Sid')
          .update(
            attributes: {
                'proxySession' => 'KCXXXXXXXXXXXXXXXXXXXXXXXX'
              }.to_json
          )

puts channel.sid
```

```bash
# Install the twilio-cli from https://twil.io/cli

twilio api:chat:v2:services:channels:update \
   --service-sid ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \
   --sid Sid \
   --attributes "{\"proxySession\": \"KCXXXXXXXXXXXXXXXXXXXXXXXX\"}"
```

```bash
ATTRIBUTES_OBJ=$(cat << EOF
{
  "proxySession": "KCXXXXXXXXXXXXXXXXXXXXXXXX"
}
EOF
)
curl -X POST "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/Sid" \
--data-urlencode "Attributes=$ATTRIBUTES_OBJ" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
```

```json
{
  "sid": "Sid",
  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "friendly_name": "friendly_name",
  "unique_name": "unique_name",
  "attributes": "{\"proxySession\": \"KCXXXXXXXXXXXXXXXXXXXXXXXX\"}",
  "type": "public",
  "date_created": "2015-12-16T22:18:37Z",
  "date_updated": "2015-12-16T22:18:38Z",
  "created_by": "username",
  "members_count": 0,
  "messages_count": 0,
  "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "links": {
    "members": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members",
    "messages": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages",
    "invites": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites",
    "webhooks": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks",
    "last_message": null
  }
}
```

### Step 5: Start chatting

Now, go back to Flex and accept the reservation. Your agent can directly message into the Chat interface, and messages are routed to the customer on their Twilio Channel.

## Create Task when customer responds

The following steps outline an alternate architecture for sending a message to the customer. When the customer responds, the inbound message handler will create a Task and forward it to an agent.

### Step 1: Configure inbound messages

Make sure you set up an inbound message handler, and that it's configured to create a Task. This will handle the customer's response to the outbound message. Please ensure you are also defining your Flex Flow to use a Messaging capable Task Channel such as `sms` or `chat`.

If you already handle inbound messages and want to use that logic, you can use the code sample below to retrieve all Flex Flows on the account. Choose the SID of the one associated with your current message handler for your desired channel (for example, the SMS message handler).

Strategy 2: Retrieve all Flex Flows on Account

```js
// Download the helper library from https://www.twilio.com/docs/node/install
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);

async function listFlexFlow() {
  const flexFlows = await client.flexApi.v1.flexFlow.list({ limit: 20 });

  flexFlows.forEach((f) => console.log(f.accountSid));
}

listFlexFlow();
```

```python
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
client = Client(account_sid, auth_token)

flex_flows = client.flex_api.v1.flex_flow.list(limit=20)

for record in flex_flows:
    print(record.account_sid)
```

```csharp
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.FlexApi.V1;
using System.Threading.Tasks;

class Program {
    public static async Task Main(string[] args) {
        // Find your Account SID and Auth Token at twilio.com/console
        // and set the environment variables. See http://twil.io/secure
        string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        TwilioClient.Init(accountSid, authToken);

        var flexFlows = await FlexFlowResource.ReadAsync(limit: 20);

        foreach (var record in flexFlows) {
            Console.WriteLine(record.AccountSid);
        }
    }
}
```

```java
// Install the Java helper library from twilio.com/docs/java/install

import com.twilio.Twilio;
import com.twilio.rest.flexapi.v1.FlexFlow;
import com.twilio.base.ResourceSet;

public class Example {
    // Find your Account SID and Auth Token at twilio.com/console
    // and set the environment variables. See http://twil.io/secure
    public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
    public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
        ResourceSet<FlexFlow> flexFlows = FlexFlow.reader().limit(20).read();

        for (FlexFlow record : flexFlows) {
            System.out.println(record.getAccountSid());
        }
    }
}
```

```go
// Download the helper library from https://www.twilio.com/docs/go/install
package main

import (
	"fmt"
	"github.com/twilio/twilio-go"
	flex "github.com/twilio/twilio-go/rest/flex/v1"
	"os"
)

func main() {
	// Find your Account SID and Auth Token at twilio.com/console
	// and set the environment variables. See http://twil.io/secure
	// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment
	client := twilio.NewRestClient()

	params := &flex.ListFlexFlowParams{}
	params.SetLimit(20)

	resp, err := client.FlexV1.ListFlexFlow(params)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		for record := range resp {
			if resp[record].AccountSid != nil {
				fmt.Println(*resp[record].AccountSid)
			} else {
				fmt.Println(resp[record].AccountSid)
			}
		}
	}
}
```

```php
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "/path/to/vendor/autoload.php";

use Twilio\Rest\Client;

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = getenv("TWILIO_ACCOUNT_SID");
$token = getenv("TWILIO_AUTH_TOKEN");
$twilio = new Client($sid, $token);

$flexFlows = $twilio->flexApi->v1->flexFlow->read([], 20);

foreach ($flexFlows as $record) {
    print $record->accountSid;
}
```

```ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'twilio-ruby'

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)

flex_flows = @client
             .flex_api
             .v1
             .flex_flow
             .list(limit: 20)

flex_flows.each do |record|
   puts record.account_sid
end
```

```bash
# Install the twilio-cli from https://twil.io/cli

twilio api:flex:v1:flex-flows:list
```

```bash
curl -X GET "https://flex-api.twilio.com/v1/FlexFlows?PageSize=20" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
```

```json
{
  "meta": {
    "page": 0,
    "page_size": 50,
    "first_page_url": "https://flex-api.twilio.com/v1/FlexFlows?PageSize=50&Page=0",
    "previous_page_url": null,
    "url": "https://flex-api.twilio.com/v1/FlexFlows?PageSize=50&Page=0",
    "next_page_url": null,
    "key": "flex_flows"
  },
  "flex_flows": [
    {
      "sid": "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      "date_created": "2016-08-01T22:10:40Z",
      "date_updated": "2016-08-01T22:10:40Z",
      "friendly_name": "friendly_name",
      "chat_service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      "channel_type": "sms",
      "contact_identity": "12345",
      "enabled": true,
      "integration_type": "studio",
      "integration": {
        "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        "retry_count": 1
      },
      "long_lived": true,
      "janitor_enabled": true,
      "url": "https://flex-api.twilio.com/v1/FlexFlows/FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    }
  ]
}
```

### Step 2: Create a Channel

Create a chat channel using the Flex Channel Resource. You'll need the Flex Flow for outbound messages. You'll need a new channel for each interaction.

> \[!NOTE]
>
> You may see multiple SIDs associated with a Flow - some might be for Twilio Studio. You need to use a Flex Flow SID, which will begin with the letters `FO`.

Create an outbound message handler without a task

```js
// Download the helper library from https://www.twilio.com/docs/node/install
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);

async function createChannel() {
  const channel = await client.flexApi.v1.channel.create({
    chatFriendlyName: "Chat with Jane",
    chatUserFriendlyName: "Jane",
    flexFlowSid: "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    identity: "sms_18001231234",
    target: "+18001231234",
  });

  console.log(channel.accountSid);
}

createChannel();
```

```python
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
client = Client(account_sid, auth_token)

channel = client.flex_api.v1.channel.create(
    identity="sms_18001231234",
    target="+18001231234",
    chat_user_friendly_name="Jane",
    chat_friendly_name="Chat with Jane",
    flex_flow_sid="FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
)

print(channel.account_sid)
```

```csharp
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.FlexApi.V1;
using System.Threading.Tasks;

class Program {
    public static async Task Main(string[] args) {
        // Find your Account SID and Auth Token at twilio.com/console
        // and set the environment variables. See http://twil.io/secure
        string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        TwilioClient.Init(accountSid, authToken);

        var channel = await ChannelResource.CreateAsync(
            identity: "sms_18001231234",
            target: "+18001231234",
            chatUserFriendlyName: "Jane",
            chatFriendlyName: "Chat with Jane",
            flexFlowSid: "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");

        Console.WriteLine(channel.AccountSid);
    }
}
```

```java
// Install the Java helper library from twilio.com/docs/java/install

import com.twilio.Twilio;
import com.twilio.rest.flexapi.v1.Channel;

public class Example {
    // Find your Account SID and Auth Token at twilio.com/console
    // and set the environment variables. See http://twil.io/secure
    public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
    public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
        Channel channel =
            Channel.creator("FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "sms_18001231234", "Jane", "Chat with Jane")
                .setTarget("+18001231234")
                .create();

        System.out.println(channel.getAccountSid());
    }
}
```

```go
// Download the helper library from https://www.twilio.com/docs/go/install
package main

import (
	"fmt"
	"github.com/twilio/twilio-go"
	flex "github.com/twilio/twilio-go/rest/flex/v1"
	"os"
)

func main() {
	// Find your Account SID and Auth Token at twilio.com/console
	// and set the environment variables. See http://twil.io/secure
	// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment
	client := twilio.NewRestClient()

	params := &flex.CreateChannelParams{}
	params.SetIdentity("sms_18001231234")
	params.SetTarget("+18001231234")
	params.SetChatUserFriendlyName("Jane")
	params.SetChatFriendlyName("Chat with Jane")
	params.SetFlexFlowSid("FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")

	resp, err := client.FlexV1.CreateChannel(params)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		if resp.AccountSid != nil {
			fmt.Println(*resp.AccountSid)
		} else {
			fmt.Println(resp.AccountSid)
		}
	}
}
```

```php
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "/path/to/vendor/autoload.php";

use Twilio\Rest\Client;

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = getenv("TWILIO_ACCOUNT_SID");
$token = getenv("TWILIO_AUTH_TOKEN");
$twilio = new Client($sid, $token);

$channel = $twilio->flexApi->v1->channel->create(
    "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // FlexFlowSid
    "sms_18001231234", // Identity
    "Jane", // ChatUserFriendlyName
    "Chat with Jane", // ChatFriendlyName
    ["target" => "+18001231234"]
);

print $channel->accountSid;
```

```ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'twilio-ruby'

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)

channel = @client
          .flex_api
          .v1
          .channel
          .create(
            identity: 'sms_18001231234',
            target: '+18001231234',
            chat_user_friendly_name: 'Jane',
            chat_friendly_name: 'Chat with Jane',
            flex_flow_sid: 'FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
          )

puts channel.account_sid
```

```bash
# Install the twilio-cli from https://twil.io/cli

twilio api:flex:v1:channels:create \
   --identity sms_18001231234 \
   --target +18001231234 \
   --chat-user-friendly-name Jane \
   --chat-friendly-name "Chat with Jane" \
   --flex-flow-sid FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
```

```bash
curl -X POST "https://flex-api.twilio.com/v1/Channels" \
--data-urlencode "Identity=sms_18001231234" \
--data-urlencode "Target=+18001231234" \
--data-urlencode "ChatUserFriendlyName=Jane" \
--data-urlencode "ChatFriendlyName=Chat with Jane" \
--data-urlencode "FlexFlowSid=FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
```

```json
{
  "flex_flow_sid": "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "task_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "date_created": "2016-08-01T22:10:40Z",
  "date_updated": "2016-08-01T22:10:40Z",
  "url": "https://flex-api.twilio.com/v1/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
```

### Step 3: Create a Proxy Session

Now you'll need to create a Proxy Session in order to associate the Chat Channel and the Customer's Phone number together. Sessions offer a useful layer of state and metadata that Flex uses to ensure that your customers' messages stay properly threaded as they are processed by bots, TaskRouter and agents. It will help tell Flex that, when the customer responds, they should be talking to this Agent over this Channel. Pass the channel you created in Step 2 as the Unique Name of the Session.

Make sure that you included the 'FriendlyName' in the participants array.

In the sample code, you need to replace:

| Attribute                   | Description                                                                                                                                                                                                                                       |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `{{CHAT_CHANNEL_SID}}`      | The chat channel that the agent will be using to respond to the customer, which you created in Step 2.                                                                                                                                            |
| `{{CONTACT_CENTER_NUMBER}}` | The contact center/agent ID (the number the SMS will be sent from). This is the same number you used as `contactIdentity` when you created the Flex Flow. This could be a WhatsApp Number, or any other identifier for another messaging channel. |
| `{{FRIENDLY_NAME}}`         | The friendly name needs to be included in the participants in order to correctly create the proxy session. We recommend including the customer number ( `{{CUSTOMER_NUMBER }}`) as the friendly name.                                             |

Create a Proxy Session

```js
// Download the helper library from https://www.twilio.com/docs/node/install
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);

async function createSession() {
  const session = await client.proxy.v1
    .services("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    .sessions.create({
      mode: "message-only",
      participants: [
        {
          identifier: "CHAT_CHANNEL_SID",
          proxyIdentifier: "CONTACT_CENTER_NUMBER",
          friendlyName: "SOME_FRIENDLY_NAME_<CUSTOMER_NUMBER>",
        },
      ],
      uniqueName: "CHXXXXXXXXXXXXXXXXXXXXXXXXX",
    });

  console.log(session.sid);
}

createSession();
```

```python
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
client = Client(account_sid, auth_token)

session = client.proxy.v1.services(
    "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
).sessions.create(
    unique_name="CHXXXXXXXXXXXXXXXXXXXXXXXXX",
    participants=[
        {
            "identifier": "CHAT_CHANNEL_SID",
            "proxyIdentifier": "CONTACT_CENTER_NUMBER",
            "friendlyName": "SOME_FRIENDLY_NAME_<CUSTOMER_NUMBER>",
        }
    ],
    mode="message-only",
)

print(session.sid)
```

```csharp
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Proxy.V1.Service;
using System.Threading.Tasks;
using System.Collections.Generic;

class Program {
    public static async Task Main(string[] args) {
        // Find your Account SID and Auth Token at twilio.com/console
        // and set the environment variables. See http://twil.io/secure
        string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        TwilioClient.Init(accountSid, authToken);

        var session = await SessionResource.CreateAsync(
            uniqueName: "CHXXXXXXXXXXXXXXXXXXXXXXXXX",
            participants: new List<Object> { new Dictionary<string, Object>() {
                { "identifier", "CHAT_CHANNEL_SID" },
                { "proxyIdentifier", "CONTACT_CENTER_NUMBER" },
                { "friendlyName", "SOME_FRIENDLY_NAME_<CUSTOMER_NUMBER>" }
            } },
            mode: SessionResource.ModeEnum.MessageOnly,
            pathServiceSid: "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");

        Console.WriteLine(session.Sid);
    }
}
```

```java
// Install the Java helper library from twilio.com/docs/java/install

import java.util.Arrays;
import java.util.HashMap;
import com.twilio.Twilio;
import com.twilio.rest.proxy.v1.service.Session;

public class Example {
    // Find your Account SID and Auth Token at twilio.com/console
    // and set the environment variables. See http://twil.io/secure
    public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
    public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
        Session session = Session.creator("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
                              .setUniqueName("CHXXXXXXXXXXXXXXXXXXXXXXXXX")
                              .setParticipants(Arrays.asList(new HashMap<String, Object>() {
                                  {
                                      put("identifier", "CHAT_CHANNEL_SID");
                                      put("proxyIdentifier", "CONTACT_CENTER_NUMBER");
                                      put("friendlyName", "SOME_FRIENDLY_NAME_<CUSTOMER_NUMBER>");
                                  }
                              }))
                              .setMode(Session.Mode.MESSAGE_ONLY)
                              .create();

        System.out.println(session.getSid());
    }
}
```

```go
// Download the helper library from https://www.twilio.com/docs/go/install
package main

import (
	"fmt"
	"github.com/twilio/twilio-go"
	proxy "github.com/twilio/twilio-go/rest/proxy/v1"
	"os"
)

func main() {
	// Find your Account SID and Auth Token at twilio.com/console
	// and set the environment variables. See http://twil.io/secure
	// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment
	client := twilio.NewRestClient()

	params := &proxy.CreateSessionParams{}
	params.SetUniqueName("CHXXXXXXXXXXXXXXXXXXXXXXXXX")
	params.SetParticipants([]interface{}{
		map[string]interface{}{
			"identifier":      "CHAT_CHANNEL_SID",
			"proxyIdentifier": "CONTACT_CENTER_NUMBER",
			"friendlyName":    "SOME_FRIENDLY_NAME_<CUSTOMER_NUMBER>",
		},
	})
	params.SetMode("message-only")

	resp, err := client.ProxyV1.CreateSession("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
		params)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		if resp.Sid != nil {
			fmt.Println(*resp.Sid)
		} else {
			fmt.Println(resp.Sid)
		}
	}
}
```

```php
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "/path/to/vendor/autoload.php";

use Twilio\Rest\Client;

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = getenv("TWILIO_ACCOUNT_SID");
$token = getenv("TWILIO_AUTH_TOKEN");
$twilio = new Client($sid, $token);

$session = $twilio->proxy->v1
    ->services("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    ->sessions->create([
        "uniqueName" => "CHXXXXXXXXXXXXXXXXXXXXXXXXX",
        "participants" => [
            [
                "identifier" => "CHAT_CHANNEL_SID",
                "proxyIdentifier" => "CONTACT_CENTER_NUMBER",
                "friendlyName" => "SOME_FRIENDLY_NAME_<CUSTOMER_NUMBER>",
            ],
        ],
        "mode" => "message-only",
    ]);

print $session->sid;
```

```ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'twilio-ruby'

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)

session = @client
          .proxy
          .v1
          .services('KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
          .sessions
          .create(
            unique_name: 'CHXXXXXXXXXXXXXXXXXXXXXXXXX',
            participants: [
              {
                'identifier' => 'CHAT_CHANNEL_SID',
                'proxyIdentifier' => 'CONTACT_CENTER_NUMBER',
                'friendlyName' => 'SOME_FRIENDLY_NAME_<CUSTOMER_NUMBER>'
              }
            ],
            mode: 'message-only'
          )

puts session.sid
```

```bash
# Install the twilio-cli from https://twil.io/cli

twilio api:proxy:v1:services:sessions:create \
   --service-sid KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \
   --unique-name CHXXXXXXXXXXXXXXXXXXXXXXXXX \
   --participants "{\"identifier\":\"CHAT_CHANNEL_SID\",\"proxyIdentifier\":\"CONTACT_CENTER_NUMBER\",\"friendlyName\":\"SOME_FRIENDLY_NAME_<CUSTOMER_NUMBER>\"}" \
   --mode message-only
```

```bash
curl -X POST "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions" \
--data-urlencode "UniqueName=CHXXXXXXXXXXXXXXXXXXXXXXXXX" \
--data-urlencode "Participants={\"identifier\":\"CHAT_CHANNEL_SID\",\"proxyIdentifier\":\"CONTACT_CENTER_NUMBER\",\"friendlyName\":\"SOME_FRIENDLY_NAME_<CUSTOMER_NUMBER>\"}" \
--data-urlencode "Mode=message-only" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
```

```json
{
  "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "status": "open",
  "unique_name": "CHXXXXXXXXXXXXXXXXXXXXXXXXX",
  "date_started": "2015-07-30T20:00:00Z",
  "date_ended": "2015-07-30T20:00:00Z",
  "date_last_interaction": "2015-07-30T20:00:00Z",
  "date_expiry": "2015-07-30T20:00:00Z",
  "ttl": 3600,
  "mode": "message-only",
  "closed_reason": "",
  "sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "date_updated": "2015-07-30T20:00:00Z",
  "date_created": "2015-07-30T20:00:00Z",
  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "links": {
    "interactions": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Interactions",
    "participants": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants"
  }
}
```

Use another request to add the customer, using their number as the identifier. Proxy can use its own logic to select the Proxy identifier.

Add Customer

```js
// Download the helper library from https://www.twilio.com/docs/node/install
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);

async function createParticipant() {
  const participant = await client.proxy.v1
    .services("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    .sessions("KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    .participants.create({
      friendlyName: "This is the Customer",
      identifier: "CUSTOMER_NUMBER",
    });

  console.log(participant.sid);
}

createParticipant();
```

```python
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
client = Client(account_sid, auth_token)

participant = (
    client.proxy.v1.services("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    .sessions("KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    .participants.create(
        identifier="CUSTOMER_NUMBER", friendly_name="This is the Customer"
    )
)

print(participant.sid)
```

```csharp
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Proxy.V1.Service.Session;
using System.Threading.Tasks;

class Program {
    public static async Task Main(string[] args) {
        // Find your Account SID and Auth Token at twilio.com/console
        // and set the environment variables. See http://twil.io/secure
        string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        TwilioClient.Init(accountSid, authToken);

        var participant = await ParticipantResource.CreateAsync(
            identifier: "CUSTOMER_NUMBER",
            friendlyName: "This is the Customer",
            pathServiceSid: "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            pathSessionSid: "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");

        Console.WriteLine(participant.Sid);
    }
}
```

```java
// Install the Java helper library from twilio.com/docs/java/install

import com.twilio.Twilio;
import com.twilio.rest.proxy.v1.service.session.Participant;

public class Example {
    // Find your Account SID and Auth Token at twilio.com/console
    // and set the environment variables. See http://twil.io/secure
    public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
    public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
        Participant participant =
            Participant
                .creator("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "CUSTOMER_NUMBER")
                .setFriendlyName("This is the Customer")
                .create();

        System.out.println(participant.getSid());
    }
}
```

```go
// Download the helper library from https://www.twilio.com/docs/go/install
package main

import (
	"fmt"
	"github.com/twilio/twilio-go"
	proxy "github.com/twilio/twilio-go/rest/proxy/v1"
	"os"
)

func main() {
	// Find your Account SID and Auth Token at twilio.com/console
	// and set the environment variables. See http://twil.io/secure
	// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment
	client := twilio.NewRestClient()

	params := &proxy.CreateParticipantParams{}
	params.SetIdentifier("CUSTOMER_NUMBER")
	params.SetFriendlyName("This is the Customer")

	resp, err := client.ProxyV1.CreateParticipant("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
		"KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
		params)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		if resp.Sid != nil {
			fmt.Println(*resp.Sid)
		} else {
			fmt.Println(resp.Sid)
		}
	}
}
```

```php
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "/path/to/vendor/autoload.php";

use Twilio\Rest\Client;

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = getenv("TWILIO_ACCOUNT_SID");
$token = getenv("TWILIO_AUTH_TOKEN");
$twilio = new Client($sid, $token);

$participant = $twilio->proxy->v1
    ->services("KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    ->sessions("KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    ->participants->create(
        "CUSTOMER_NUMBER", // Identifier
        ["friendlyName" => "This is the Customer"]
    );

print $participant->sid;
```

```ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'twilio-ruby'

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)

participant = @client
              .proxy
              .v1
              .services('KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
              .sessions('KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
              .participants
              .create(
                identifier: 'CUSTOMER_NUMBER',
                friendly_name: 'This is the Customer'
              )

puts participant.sid
```

```bash
# Install the twilio-cli from https://twil.io/cli

twilio api:proxy:v1:services:sessions:participants:create \
   --service-sid KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \
   --session-sid KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \
   --identifier CUSTOMER_NUMBER \
   --friendly-name "This is the Customer"
```

```bash
curl -X POST "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants" \
--data-urlencode "Identifier=CUSTOMER_NUMBER" \
--data-urlencode "FriendlyName=This is the Customer" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
```

```json
{
  "sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "session_sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "identifier": "CUSTOMER_NUMBER",
  "proxy_identifier": "+14155559999",
  "proxy_identifier_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "friendly_name": "This is the Customer",
  "date_deleted": "2015-07-30T20:00:00Z",
  "date_updated": "2015-07-30T20:00:00Z",
  "date_created": "2015-07-30T20:00:00Z",
  "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "links": {
    "message_interactions": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessageInteractions"
  }
}
```

### Step 4: Update the Chat Channel Attributes

Update the Chat Channel `attributes` to include the Proxy Session SID you created in Step 3 if it's not already there. The chat channel attributes should be a JSON string:

`{proxySession: "KCXXXXXXXXXXXXXXXXXXXXXXXX"}`

Make sure that you retrieve the existing attributes object, add the `proxySession` key, and then update the parameter as a string.

Update Chat Channel Attributes

```js
// Download the helper library from https://www.twilio.com/docs/node/install
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);

async function updateChannel() {
  const channel = await client.chat.v2
    .services("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    .channels("Sid")
    .update({
      attributes: JSON.stringify({
        proxySession: "KCXXXXXXXXXXXXXXXXXXXXXXXX",
      }),
    });

  console.log(channel.sid);
}

updateChannel();
```

```python
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client
import json

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
client = Client(account_sid, auth_token)

channel = (
    client.chat.v2.services("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    .channels("Sid")
    .update(
        attributes=json.dumps({"proxySession": "KCXXXXXXXXXXXXXXXXXXXXXXXX"})
    )
)

print(channel.sid)
```

```csharp
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Chat.V2.Service;
using System.Threading.Tasks;
using System.Collections.Generic;
using Newtonsoft.Json;

class Program {
    public static async Task Main(string[] args) {
        // Find your Account SID and Auth Token at twilio.com/console
        // and set the environment variables. See http://twil.io/secure
        string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        TwilioClient.Init(accountSid, authToken);

        var channel = await ChannelResource.UpdateAsync(
            attributes: JsonConvert.SerializeObject(
                new Dictionary<string, Object>() {
                    { "proxySession", "KCXXXXXXXXXXXXXXXXXXXXXXXX" }
                },
                Formatting.Indented),
            pathServiceSid: "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            pathSid: "Sid");

        Console.WriteLine(channel.Sid);
    }
}
```

```java
// Install the Java helper library from twilio.com/docs/java/install

import java.util.HashMap;
import com.twilio.Twilio;
import com.twilio.rest.chat.v2.service.Channel;
import org.json.JSONObject;

public class Example {
    // Find your Account SID and Auth Token at twilio.com/console
    // and set the environment variables. See http://twil.io/secure
    public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
    public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
        Channel channel = Channel.updater("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "Sid")
                              .setAttributes(new JSONObject(new HashMap<String, Object>() {
                                  {
                                      put("proxySession", "KCXXXXXXXXXXXXXXXXXXXXXXXX");
                                  }
                              }).toString())
                              .update();

        System.out.println(channel.getSid());
    }
}
```

```go
// Download the helper library from https://www.twilio.com/docs/go/install
package main

import (
	"encoding/json"
	"fmt"
	"github.com/twilio/twilio-go"
	chat "github.com/twilio/twilio-go/rest/chat/v2"
	"os"
)

func main() {
	// Find your Account SID and Auth Token at twilio.com/console
	// and set the environment variables. See http://twil.io/secure
	// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment
	client := twilio.NewRestClient()

	Attributes, AttributesError := json.Marshal(map[string]interface{}{
		"proxySession": "KCXXXXXXXXXXXXXXXXXXXXXXXX",
	})

	if AttributesError != nil {
		fmt.Println(AttributesError)
		os.Exit(1)
	}

	params := &chat.UpdateChannelParams{}
	params.SetAttributes(string(Attributes))

	resp, err := client.ChatV2.UpdateChannel("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
		"Sid",
		params)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		if resp.Sid != nil {
			fmt.Println(*resp.Sid)
		} else {
			fmt.Println(resp.Sid)
		}
	}
}
```

```php
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "/path/to/vendor/autoload.php";

use Twilio\Rest\Client;

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = getenv("TWILIO_ACCOUNT_SID");
$token = getenv("TWILIO_AUTH_TOKEN");
$twilio = new Client($sid, $token);

$channel = $twilio->chat->v2
    ->services("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    ->channels("Sid")
    ->update([
        "attributes" => json_encode([
            "proxySession" => "KCXXXXXXXXXXXXXXXXXXXXXXXX",
        ]),
    ]);

print $channel->sid;
```

```ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'twilio-ruby'

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)

channel = @client
          .chat
          .v2
          .services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
          .channels('Sid')
          .update(
            attributes: {
                'proxySession' => 'KCXXXXXXXXXXXXXXXXXXXXXXXX'
              }.to_json
          )

puts channel.sid
```

```bash
# Install the twilio-cli from https://twil.io/cli

twilio api:chat:v2:services:channels:update \
   --service-sid ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \
   --sid Sid \
   --attributes "{\"proxySession\": \"KCXXXXXXXXXXXXXXXXXXXXXXXX\"}"
```

```bash
ATTRIBUTES_OBJ=$(cat << EOF
{
  "proxySession": "KCXXXXXXXXXXXXXXXXXXXXXXXX"
}
EOF
)
curl -X POST "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/Sid" \
--data-urlencode "Attributes=$ATTRIBUTES_OBJ" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
```

```json
{
  "sid": "Sid",
  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "friendly_name": "friendly_name",
  "unique_name": "unique_name",
  "attributes": "{\"proxySession\": \"KCXXXXXXXXXXXXXXXXXXXXXXXX\"}",
  "type": "public",
  "date_created": "2015-12-16T22:18:37Z",
  "date_updated": "2015-12-16T22:18:38Z",
  "created_by": "username",
  "members_count": 0,
  "messages_count": 0,
  "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "links": {
    "members": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members",
    "messages": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages",
    "invites": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites",
    "webhooks": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks",
    "last_message": null
  }
}
```

### Step 5: Send the message

Now you can manually send your outbound message through the chat channel. This will trigger a post-event webhook, creating the proxy interaction or the outbound message. For example, if you're using Studio, then it will trigger the Studio Flow as an outbound message to your customer.

We advise you to [send the message through the channel SID](#send-the-message-to-the-chat-channel) as opposed to the Proxy SID to keep a full record of the chat interaction.

| `chatServiceSid` | The [Service](/docs/chat/rest/service-resource) associated with your Chat Channel.                                                                                                                    |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `channelSid`     | The Chat Channel for the Flex Channel Resource. This will tell the Channel to send a message from the Agent to the Customer using the identifiers stored in Proxy.                                    |
| `from`           | The contact center/agent ID (the number the SMS will be sent from).                                                                                                                                   |
| `messageText`    | This is the message content that you can send in the message. Note that this content may not appear if you're using a Studio Flow that doesn't use the Trigger widget's `body` property, for example. |

#### Send the message to the chat channel

```javascript
const sendMessage = async function(channelSid, chatServiceSid, client, from, messageText){
  try {
    console.log("Send Message Function")
    return client
      .chat
      .services(chatServiceSid)
      .channels(channelSid)
      .messages
      .create({
        body : messageText,
        from : from
      })
  } catch(error) {
    console.log(error);
  }
}

```

Your customer should now receive a message. When they respond, a Task will be created, and you can route it to an agent who can accept and handle the response.
