---
url: https://talkjs.com/docs/Guides/Reassign_Chat/
title: "Reassign a chat | Guides | TalkJS Docs"
---

For AI agents: Find a documentation index at https://talkjs.com/llms.txt (full content at https://talkjs.com/llms-full.txt). Get a markdown version of any page by appending .md to its URL path.

# Reassign a chat

Preserve chat history when assigning a booking or job to a new provider.

On a platform where customers book services from providers, or where workers are assigned to jobs, changing the assignment also changes who should have access to the chat. This guide shows how to remove the current assignee's access and add the new provider, preserving the full conversation history without any input from the customer.

We'll use a home-cleaning booking platform as an example. Customers chat with the cleaner assigned to their visit. If the customer has already sent messages explaining how to enter the property, the new cleaner needs to see those messages when the booking is reassigned.

## Update chat when the assignment changes

Call `reassignChat` from the backend code that handles reassignment in your app, passing the booking's conversation ID and the two cleaners' TalkJS user IDs. The function removes the previous cleaner from the conversation, then adds the new cleaner.

The `setParticipant` function adds or removes a user and retries temporary failures. Its implementation is shown in the next section.

**NodeJS**

```javascript
async function reassignChat(conversationId, oldUserId, newUserId) {
  if (oldUserId === newUserId) {
    return;
  }

  await setParticipant(conversationId, oldUserId, false);
  await setParticipant(conversationId, newUserId, true);
}
```

**NodeJS (TS)**

```typescript
async function reassignChat(
  conversationId: string,
  oldUserId: string,
  newUserId: string
): Promise<void> {
  if (oldUserId === newUserId) {
    return;
  }

  await setParticipant(conversationId, oldUserId, false);
  await setParticipant(conversationId, newUserId, true);
}
```

**Python**

```python
def reassign_chat(conversation_id, old_user_id, new_user_id):
    if old_user_id == new_user_id:
        return

    set_participant(conversation_id, old_user_id, False)
    set_participant(conversation_id, new_user_id, True)
```

**PHP**

```php
function reassignChat(string $conversationId, string $oldUserId, string $newUserId): void
{
    if ($oldUserId === $newUserId) {
        return;
    }

    setParticipant($conversationId, $oldUserId, false);
    setParticipant($conversationId, $newUserId, true);
}
```

**Ruby**

```ruby
def reassign_chat(conversation_id, old_user_id, new_user_id)
  return if old_user_id == new_user_id

  set_participant(conversation_id, old_user_id, false)
  set_participant(conversation_id, new_user_id, true)
end
```

**Java**

```clike
static void reassignChat(String conversationId, String oldUserId, String newUserId)
    throws Exception {
    if (oldUserId.equals(newUserId)) {
        return;
    }

    setParticipant(conversationId, oldUserId, false);
    setParticipant(conversationId, newUserId, true);
}
```

**C#**

```clike
using System;
using System.Threading.Tasks;

static async Task ReassignChat(string conversationId, string oldUserId, string newUserId)
{
    if (oldUserId == newUserId) {
        return;
    }

    await SetParticipant(conversationId, oldUserId, false);
    await SetParticipant(conversationId, newUserId, true);
}
```

**Go**

```go
func reassignChat(conversationID, oldUserID, newUserID string) error {
    if oldUserID == newUserID {
        return nil
    }

    if err := setParticipant(conversationID, oldUserID, false); err != nil {
        return err
    }
    return setParticipant(conversationID, newUserID, true)
}
```

**Elixir**

```elixir
def reassign_chat(conversation_id, old_user_id, new_user_id) do
  if old_user_id == new_user_id do
    :ok
  else
    set_participant(conversation_id, old_user_id, false)
    set_participant(conversation_id, new_user_id, true)
  end
end
```

**Dart**

```dart
Future<void> reassignChat(String conversationId, String oldUserId, String newUserId) async {
  if (oldUserId == newUserId) {
    return;
  }

  await setParticipant(conversationId, oldUserId, false);
  await setParticipant(conversationId, newUserId, true);
}
```

The new cleaner can read the customer's entry instructions and reply in the same chat. The previous cleaner loses access. The customer keeps the chat and doesn't need to resend anything.

## Handle failed requests

If a request fails because of a connection problem, a timeout, a rate limit or a server error, the code tries again after one second, then two seconds, then four seconds. If it still fails, the error goes back to the code that called `reassignChat`. Other request errors, such as invalid credentials, don't get retried.

If the update fails after removing the previous cleaner, the customer keeps the conversation and its history. Your app can retry `reassignChat` with the same IDs to finish the update.

**NodeJS**

```javascript
// Your app ID from the TalkJS Dashboard.
const appId = '<APP_ID>';

async function setParticipant(conversationId, userId, shouldBeParticipant) {
  const url = `https://api.talkjs.com/v1/${appId}/conversations/${encodeURIComponent(conversationId)}/participants/${encodeURIComponent(userId)}`;

  // How long to wait before retrying failed requests (doubles each time)
  let delay = 1000;

  for (let attempt = 0; attempt < 4; attempt++) {
    // Reuse your existing Admin JWT generation code
    // Example: https://talkjs.com/docs/REST_API/#authentication
    const token = generateAdminJwt();

    const response = await fetch(url, {
      method: shouldBeParticipant ? 'PUT' : 'DELETE',
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    }).then(async (response) => {
      await response.text();
      return response;
    }).catch((error) => {
      if (attempt === 3) {
        throw error;
      }
      return null;
    });

    if (response) {
      if (response.status === 200) {
        return;
      }

      // When removing, 404 means the user is already not a participant.
      if (!shouldBeParticipant && response.status === 404) {
        return;
      }

      // A 404 while adding is an error. Only retry 429 or 5xx, up to four attempts.
      if ((response.status !== 429 && response.status < 500) || attempt === 3) {
        throw new Error(`TalkJS returned HTTP ${response.status}`);
      }
    }
    await new Promise((resolve) => {
      setTimeout(resolve, delay);
    });
    delay = delay * 2;
  }
}
```

**NodeJS (TS)**

```typescript
// Your app ID from the TalkJS Dashboard.
const appId = '<APP_ID>';

async function setParticipant(
  conversationId: string,
  userId: string,
  shouldBeParticipant: boolean
): Promise<void> {
  const url = `https://api.talkjs.com/v1/${appId}/conversations/${encodeURIComponent(conversationId)}/participants/${encodeURIComponent(userId)}`;

  // How long to wait before retrying failed requests (doubles each time)
  let delay = 1000;

  for (let attempt = 0; attempt < 4; attempt++) {
    // Reuse your existing Admin JWT generation code
    // Example: https://talkjs.com/docs/REST_API/#authentication
    const token = generateAdminJwt();

    const response = await fetch(url, {
      method: shouldBeParticipant ? 'PUT' : 'DELETE',
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    }).then(async (response) => {
      await response.text();
      return response;
    }).catch((error) => {
      if (attempt === 3) {
        throw error;
      }
      return null;
    });

    if (response) {
      if (response.status === 200) {
        return;
      }

      // When removing, 404 means the user is already not a participant.
      if (!shouldBeParticipant && response.status === 404) {
        return;
      }

      // A 404 while adding is an error. Only retry 429 or 5xx, up to four attempts.
      if ((response.status !== 429 && response.status < 500) || attempt === 3) {
        throw new Error(`TalkJS returned HTTP ${response.status}`);
      }
    }
    await new Promise((resolve) => {
      setTimeout(resolve, delay);
    });
    delay = delay * 2;
  }
}
```

**Python**

```python
import time
import requests
from urllib.parse import quote

# Your app ID from the TalkJS Dashboard.
APP_ID = '<APP_ID>'

def set_participant(conversation_id, user_id, should_be_participant):
    url = f'https://api.talkjs.com/v1/{APP_ID}/conversations/{quote(conversation_id, safe="")}/participants/{quote(user_id, safe="")}'
    method = 'PUT' if should_be_participant else 'DELETE'

    # How long to wait before retrying failed requests (doubles each time)
    delay = 1

    for attempt in range(4):
        # Reuse your existing Admin JWT generation code
        # Example: https://talkjs.com/docs/REST_API/#authentication
        token = generate_admin_jwt()

        try:
            response = requests.request(method, url, headers={
                'Authorization': f'Bearer {token}',
                'Content-Type': 'application/json'
            })
        except requests.RequestException:
            if attempt == 3:
                raise
            time.sleep(delay)
            delay = delay * 2
            continue

        if response.status_code == 200:
            return

        # When removing, 404 means the user is already not a participant.
        if not should_be_participant and response.status_code == 404:
            return

        # A 404 while adding is an error. Only retry 429 or 5xx, up to four attempts.
        if (response.status_code != 429 and response.status_code < 500) or attempt == 3:
            raise RuntimeError(f'TalkJS returned HTTP {response.status_code}')
        time.sleep(delay)
        delay = delay * 2
```

**PHP**

```php
use GuzzleHttp\Client;
use GuzzleHttp\Exception\TransferException;

// Your app ID from the TalkJS Dashboard.
const TALKJS_APP_ID = '<APP_ID>';

function setParticipant(string $conversationId, string $userId, bool $shouldBeParticipant): void
{
    $url = 'https://api.talkjs.com/v1/' . TALKJS_APP_ID . '/conversations/' . rawurlencode($conversationId) . '/participants/' . rawurlencode($userId);
    $method = $shouldBeParticipant ? 'PUT' : 'DELETE';
    $client = new Client(['http_errors' => false]);

    // How long to wait before retrying failed requests (doubles each time)
    $delay = 1;

    for ($attempt = 0; $attempt < 4; $attempt++) {
        // Reuse your existing Admin JWT generation code
        // Example: https://talkjs.com/docs/REST_API/#authentication
        $token = generateAdminJwt();

        try {
            $response = $client->request($method, $url, ['headers' => [
                'Authorization' => 'Bearer ' . $token,
                'Content-Type' => 'application/json',
            ]]);
            $status = $response->getStatusCode();
            if ($status === 200) {
                return;
            }

            // When removing, 404 means the user is already not a participant.
            if (!$shouldBeParticipant && $status === 404) {
                return;
            }

            // A 404 while adding is an error. Only retry 429 or 5xx, up to four attempts.
            if (($status !== 429 && $status < 500) || $attempt === 3) {
                throw new RuntimeException('TalkJS returned HTTP ' . $status);
            }
        } catch (TransferException $error) {
            if ($attempt === 3) {
                throw $error;
            }
        }
        sleep($delay);
        $delay = $delay * 2;
    }
}
```

**Ruby**

```ruby
require 'net/http'
require 'erb'

# Your app ID from the TalkJS Dashboard.
TALKJS_APP_ID = '<APP_ID>'

def set_participant(conversation_id, user_id, should_be_participant)
  uri = URI("https://api.talkjs.com/v1/#{TALKJS_APP_ID}/conversations/#{ERB::Util.url_encode(conversation_id)}/participants/#{ERB::Util.url_encode(user_id)}")

  # How long to wait before retrying failed requests (doubles each time)
  delay = 1

  4.times do |attempt|
    # Reuse your existing Admin JWT generation code
    # Example: https://talkjs.com/docs/REST_API/#authentication
    token = generate_admin_jwt

    request = should_be_participant ? Net::HTTP::Put.new(uri) : Net::HTTP::Delete.new(uri)
    request['Authorization'] = "Bearer #{token}"
    request['Content-Type'] = 'application/json'

    begin
      response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
        http.request(request)
      end
    rescue IOError, SystemCallError, SocketError, Timeout::Error, OpenSSL::SSL::SSLError
      raise if attempt == 3
      sleep(delay)
      delay = delay * 2
      next
    end

    status = response.code.to_i
    return if status == 200

    # When removing, 404 means the user is already not a participant.
    return if !should_be_participant && status == 404

    # A 404 while adding is an error. Only retry 429 or 5xx, up to four attempts.
    if (status != 429 && status < 500) || attempt == 3
      raise "TalkJS returned HTTP #{status}"
    end
    sleep(delay)
    delay = delay * 2
  end
end
```

**Java**

```clike
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

// Your app ID from the TalkJS Dashboard.
static final String APP_ID = "<APP_ID>";
static final HttpClient talkjsClient = HttpClient.newHttpClient();

static void setParticipant(String conversationId, String userId, boolean shouldBeParticipant) throws Exception {
    var encodedConversationId = URLEncoder.encode(conversationId, StandardCharsets.UTF_8).replace("+", "%20");
    var encodedUserId = URLEncoder.encode(userId, StandardCharsets.UTF_8).replace("+", "%20");
    var url = "https://api.talkjs.com/v1/" + APP_ID + "/conversations/" + encodedConversationId + "/participants/" + encodedUserId;
    var method = shouldBeParticipant ? "PUT" : "DELETE";

    // How long to wait before retrying failed requests (doubles each time)
    long delay = 1000;

    for (int attempt = 0; attempt < 4; attempt++) {
        // Reuse your existing Admin JWT generation code
        // Example: https://talkjs.com/docs/REST_API/#authentication
        var token = generateAdminJwt();

        try {
            var response = talkjsClient.send(
                HttpRequest.newBuilder(URI.create(url))
                    .header("Authorization", "Bearer " + token)
                    .header("Content-Type", "application/json")
                    .method(method, HttpRequest.BodyPublishers.noBody())
                    .build(),
                HttpResponse.BodyHandlers.discarding()
            );
            int status = response.statusCode();
            if (status == 200) {
                return;
            }

            // When removing, 404 means the user is already not a participant.
            if (!shouldBeParticipant && status == 404) {
                return;
            }

            // A 404 while adding is an error. Only retry 429 or 5xx, up to four attempts.
            if ((status != 429 && status < 500) || attempt == 3) {
                throw new IllegalStateException("TalkJS returned HTTP " + status);
            }
        } catch (IOException error) {
            if (attempt == 3) {
                throw error;
            }
        }
        Thread.sleep(delay);
        delay = delay * 2;
    }
}
```

**C#**

```clike
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

// Your app ID from the TalkJS Dashboard.
const string AppId = "<APP_ID>";
static readonly HttpClient talkjsClient = new HttpClient();

static async Task SetParticipant(string conversationId, string userId, bool shouldBeParticipant)
{
    var url = $"https://api.talkjs.com/v1/{AppId}/conversations/{Uri.EscapeDataString(conversationId)}/participants/{Uri.EscapeDataString(userId)}";

    // How long to wait before retrying failed requests (doubles each time)
    var delay = 1000;

    for (int attempt = 0; attempt < 4; attempt++) {
        // Reuse your existing Admin JWT generation code
        // Example: https://talkjs.com/docs/REST_API/#authentication
        var token = GenerateAdminJwt();

        try {
            using var request = new HttpRequestMessage(new HttpMethod(shouldBeParticipant ? "PUT" : "DELETE"), url);
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
            request.Content = new StringContent("");
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            using var response = await talkjsClient.SendAsync(request);
            int status = (int)response.StatusCode;
            if (status == 200) {
                return;
            }

            // When removing, 404 means the user is already not a participant.
            if (!shouldBeParticipant && status == 404) {
                return;
            }

            // A 404 while adding is an error. Only retry 429 or 5xx, up to four attempts.
            if ((status != 429 && status < 500) || attempt == 3) {
                throw new InvalidOperationException("TalkJS returned HTTP " + status);
            }
        } catch (HttpRequestException) {
            if (attempt == 3) {
                throw;
            }
        } catch (TaskCanceledException) {
            if (attempt == 3) {
                throw;
            }
        }
        await Task.Delay(delay);
        delay = delay * 2;
    }
}
```

**Go**

```go
import (
    "fmt"
    "io"
    "net/http"
    "net/url"
    "time"
)

// Your app ID from the TalkJS Dashboard.
const appID = "<APP_ID>"

func setParticipant(conversationID, userID string, shouldBeParticipant bool) error {
    requestURL := "https://api.talkjs.com/v1/" + appID + "/conversations/" + url.PathEscape(conversationID) + "/participants/" + url.PathEscape(userID)
    method := http.MethodDelete
    if shouldBeParticipant {
        method = http.MethodPut
    }

    // How long to wait before retrying failed requests (doubles each time)
    delay := time.Second

    var lastError error

    for attempt := 0; attempt < 4; attempt++ {
        // Reuse your existing Admin JWT generation code
        // Example: https://talkjs.com/docs/REST_API/#authentication
        token, err := generateAdminJWT()

        if err != nil {
            return err
        }
        request, err := http.NewRequest(method, requestURL, nil)
        if err != nil {
            return err
        }
        request.Header.Set("Authorization", "Bearer " + token)
        request.Header.Set("Content-Type", "application/json")

        response, err := http.DefaultClient.Do(request)
        if err == nil {
            _, err = io.Copy(io.Discard, response.Body)
            response.Body.Close()
        }
        if err != nil {
            lastError = err
        } else {
            status := response.StatusCode
            if status == 200 {
                return nil
            }

            // When removing, 404 means the user is already not a participant.
            if !shouldBeParticipant && status == 404 {
                return nil
            }
            lastError = fmt.Errorf("TalkJS returned HTTP %d", status)

            // A 404 while adding is an error. Only retry 429 or 5xx.
            if status != 429 && status < 500 {
                return lastError
            }
        }
        if attempt < 3 {
            time.Sleep(delay)
            delay = delay * 2
        }
    }
    return lastError
}
```

**Elixir**

```elixir
# Your app ID from the TalkJS Dashboard.
@app_id "<APP_ID>"

# delay: how long to wait before retrying failed requests (doubles each time)
defp set_participant(conversation_id, user_id, should_be_participant, attempt \\ 0, delay \\ 1000) do
  result = Req.request(
    method: if(should_be_participant, do: :put, else: :delete),
    url: "https://api.talkjs.com/v1/#{@app_id}/conversations/#{URI.encode(conversation_id, &URI.char_unreserved?/1)}/participants/#{URI.encode(user_id, &URI.char_unreserved?/1)}",
    # Reuse your existing Admin JWT generation code
    # Example: https://talkjs.com/docs/REST_API/#authentication
    auth: {:bearer, generate_admin_jwt()},

    headers: [{"content-type", "application/json"}],
    retry: false,
    decode_body: false
  )

  case result do
    {:ok, %{status: 200}} ->
      :ok

    # When removing, 404 means the user is already not a participant.
    {:ok, %{status: 404}} when not should_be_participant ->
      :ok

    # A 404 while adding is an error. Only retry 429 or 5xx.
    {:ok, %{status: status}} when status == 429 or status >= 500 ->
      error = RuntimeError.exception("TalkJS returned HTTP #{status}")
      retry_participant(conversation_id, user_id, should_be_participant, attempt, delay, error)

    {:error, error} ->
      retry_participant(conversation_id, user_id, should_be_participant, attempt, delay, error)

    {:ok, %{status: status}} ->
      raise "TalkJS returned HTTP #{status}"
  end
end

defp retry_participant(_conversation_id, _user_id, _should_be_participant, 3, _delay, error), do: raise(error)

defp retry_participant(conversation_id, user_id, should_be_participant, attempt, delay, _error) do
  Process.sleep(delay)
  set_participant(conversation_id, user_id, should_be_participant, attempt + 1, delay * 2)
end
```

**Dart**

```dart
import 'dart:async';
import 'package:http/http.dart' as http;

// Your app ID from the TalkJS Dashboard.
const appId = '<APP_ID>';

Future<void> setParticipant(String conversationId, String userId, bool shouldBeParticipant) async {
  final url = Uri.parse('https://api.talkjs.com/v1/$appId/conversations/${Uri.encodeComponent(conversationId)}/participants/${Uri.encodeComponent(userId)}');

  // How long to wait before retrying failed requests (doubles each time)
  var delay = 1;

  for (var attempt = 0; attempt < 4; attempt++) {
    // Reuse your existing Admin JWT generation code
    // Example: https://talkjs.com/docs/REST_API/#authentication
    final token = generateAdminJwt();

    try {
      final request = http.Request(shouldBeParticipant ? 'PUT' : 'DELETE', url);
      request.headers['Authorization'] = 'Bearer $token';
      request.headers['Content-Type'] = 'application/json';
      final response = await http.Response.fromStream(await request.send());

      if (response.statusCode == 200) {
        return;
      }

      // When removing, 404 means the user is already not a participant.
      if (!shouldBeParticipant && response.statusCode == 404) {
        return;
      }

      // A 404 while adding is an error. Only retry 429 or 5xx, up to four attempts.
      if ((response.statusCode != 429 && response.statusCode < 500) || attempt == 3) {
        throw StateError('TalkJS returned HTTP ${response.statusCode}');
      }
    } on http.ClientException {
      if (attempt == 3) {
        rethrow;
      }
    } on TimeoutException {
      if (attempt == 3) {
        rethrow;
      }
    }
    await Future<void>.delayed(Duration(seconds: delay));
    delay = delay * 2;
  }
}
```
