Working with Groups and Teams in Team Messaging

Last updated: 2024-02-08Contributors
Edit this page

In RingCentral's team messaging product a "team" is a special kind of chat that is defined by the name or topic of discussion rather than the members of the chat (as is the case with "conversations").

Team visibility

Teams can be either public or private. A public team is discoverable by everyone within an organization, whereas a private team is only discoverable by the members of that team.

Creating Teams

Create a team by posting to the teams endpoint. You can specify the name, description, its membership, and its visibility within the organization.

const RC = require('@ringcentral/sdk').SDK
require('dotenv').config();

var rcsdk = new RC({
    'server':       process.env.RC_SERVER_URL,
    'clientId':     process.env.RC_APP_CLIENT_ID,
    'clientSecret': process.env.RC_APP_CLIENT_SECRET
});
var platform = rcsdk.platform();
platform.login({ 'jwt':  process.env.RC_USER_JWT })

platform.on(platform.events.loginSuccess, function(){
  create_team()
})

async function create_team(){
  try {
    let bodyParams = {
      "name": "The second Death Star",
      "description": "Another Death Star!? Are you kidding?",
      "public": true,
      "members": [
          { "id": 1 },
          { "email": "[email protected]" },
          { "email": "[email protected]" }
      ]
    }
    let endpoint = "/restapi/v1.0/glip/teams"
    let resp = await platform.post(endpoint, bodyParams)
    let jsonObj = await resp.json()
    console.log(`Team id ${jsonObj.id} created.`)
  } catch (e) {
    console.log(e.Message)
  }
}

When specifying the members of a team, one can provide a mix of either person IDs and/or email addresses. If the email address refers to someone outside the organization that person will be added to the team as a guest, and invoke an email onboarding flow for that user.

Please refer to the Team Messaging Quick start for sample code

Listing Teams

A list of teams can be retrieved by calling the teams endpoint. Long lists can be iterated over using page tokens.

The following code sample shows how to list all created teams under and account print out the team name and creation date and time.

Running the code

  • If you have tried the Team Messaging quick start, you can just copy all the functions below and add them to the quick start project then call the list_teams("") function. Otherwise, edit the variables in ALL CAPS with your app and user credentials before running the code.
  • If you run on your production account, remember to use app credentials for production and change the RingCentral server URL to "https://platform.ringcentral.com"
const RC = require('@ringcentral/sdk').SDK

// Instantiate the SDK and get the platform instance
var rcsdk = new RC({
    server: "https://platform.ringcentral.com",
    clientId: "RC_APP_CLIENT_ID",
    clientSecret: "RC_APP_CLIENT_SECRET"
});
var platform = rcsdk.platform();

/* Authenticate a user using a personal JWT token */
platform.login({ jwt: "RC_USER_JWT" })

platform.on(platform.events.loginSuccess, () => {
    list_teams("")
})

platform.on(platform.events.loginError, function(e){
    console.log("Unable to authenticate to platform. Check credentials.", e.message)
    process.exit(1)
});

/*
* List teams under an account. Read 10 teams at a time.
*/
async function list_teams(pageToken) {
  try{
    var queryParams = {
      recordCount: 10,
      pageToken: pageToken
    }
    var endpoint = "/team-messaging/v1/teams"
    var resp = await platform.get(endpoint, queryParams)
    var jsonObj = await resp.json()
    // List teams API returns a list of teams in the ascending order based on team creation date and time.
    // I.e. from older team to newer team
    for (var record of jsonObj.records) {
        console.log(`The team "${record.name}" was created on ${record.creationTime}.`)
    }

    // To read the next page, check and use the previous page token in the navigation object.
    if (jsonObj.navigation.hasOwnProperty('prevPageToken')) {
      var pageToken = jsonObj.navigation.prevPageToken
      // Make sure not to exceed the API rate limit of 40 API calls per minute
      sleep(1200)
      console.log("Read newer teams ...")
      list_teams(pageToken)
    }
  }catch (e){
    console.log("Unable to read teams.", e.message)
  }
}

const sleep = async (ms) => {
  await new Promise(r => setTimeout(r, ms));
}
from ringcentral import SDK
import time

#
# List teams under an account. Read 10 teams at a time.
#
def list_teams(pageToken):
    try:
        queryParams = {
          'recordCount': 10,
          'pageToken': pageToken
        }
        endpoint = "/team-messaging/v1/teams"
        resp = platform.get(endpoint, queryParams)
        jsonObj = resp.json()

        # List teams API returns a list of teams in the ascending order based on team creation date and time.
        # I.e. from older team to newer team
        for record in jsonObj.records:
            print (f'The team "{record.name}" was created on {record.creationTime}')

        # To read the next page, check and use the previous page token in the navigation object.
        if hasattr(jsonObj.navigation, 'prevPageToken'):
            pageToken = jsonObj.navigation.prevPageToken
            # Make sure not to exceed the API rate limit of 40 API calls per minute
            time.sleep(1.2)
            print ("Read newer teams ...")
            list_teams(pageToken)
    except Exception as e:
        print ("Unable to read teams. ", str(e))


# Authenticate a user using a personal JWT token
def login():
  try:
    platform.login( jwt= "RC_USER_JWT" )
    read_teams("")
  except Exception as e:
    print ("Unable to authenticate to platform. Check credentials." + str(e))

# Instantiate the SDK and get the platform instance
rcsdk = SDK("RC_APP_CLIENT_ID", "RC_APP_CLIENT_SECRET", "https://platform.ringcentral.com")
platform = rcsdk.platform()

login()
<?php
require('vendor/autoload.php');

// Instantiate the SDK and get the platform instance
$rcsdk = new RingCentral\SDK\SDK( "RC_APP_CLIENT_ID", "RC_APP_CLIENT_SECRET", "https://platform.ringcentral.com" );
$platform = $rcsdk->platform();

/* Authenticate a user using a personal JWT token */
try {
  $platform->login(["jwt" => "RC_USER_JWT"]);
}catch (\RingCentral\SDK\Http\ApiException $e) {
  // Getting error messages using PHP native interface
  print 'Expected HTTP Error: ' . $e;
  exit ("Error message: " . $e->apiResponse->response()->error() . PHP_EOL;
}

list_teams("");

/*
* List teams under an account. Read 10 teams at a time.
*/
function list_teams($pageToken){
  global $platform;
  try{
    $queryParams = array(
      'recordCount' => 10,
      'pageToken' => $pageToken
    );

    $endpoint = "/team-messaging/v1/teams";
    $resp = $platform->get($endpoint, $queryParams);
    $jsonObj = $resp->json();
    // List teams API returns a list of teams in the ascending order based on team creation date and time.
    // I.e. from older team to newer team
    foreach ($jsonObj->records as $record) {
      // You can filter out any call queue you don't want to read analytics data!
      print_r ("The team " . $record->name . " was created on " . $record->creationTime . PHP_EOL);
    }
    // To read the next page, check and use the previous page token in the navigation object.
    if (property_exists($jsonObj->navigation, 'prevPageToken')){
        $pageToken = $jsonObj->navigation->prevPageToken;
        // Make sure not to exceed the API rate limit of 40 API calls per minute
        usleep(1200000);
        print_r ("Read newer teams ..." . PHP_EOL);
        list_teams($pageToken);
    }
  }catch (\RingCentral\SDK\Http\ApiException $e) {
    print_r ("Unable to read teams. " . $e->getMessage() . PHP_EOL);
  }
}
?>
require 'ringcentral'

#
# List teams under an account. Read 10 teams at a time.
#
def list_teams(pageToken)
  begin
    queryParams = {
      'recordCount': 10,
      'pageToken': pageToken
    }
    endpoint = "/team-messaging/v1/teams"
    resp = $platform.get(endpoint, queryParams)
    jsonObj = resp.body

    # List teams API returns a list of teams in the ascending order based on team creation date and time.
    # I.e. from older team to newer team
    for record in jsonObj['records'] do
        puts("The team \"" + record['name'] + "\" was created on " + record['creationTime'])
    end
    # To read the next page, check and use the previous page token in the navigation object.
    if jsonObj['navigation']['prevPageToken']
      pageToken = jsonObj['navigation']['prevPageToken']
      # Make sure not to exceed the API rate limit of 40 API calls per minute
      sleep(1.2)
      puts ("Read newer teams ...")
      list_teams(pageToken)
    end
  rescue StandardError => e
    puts ("Unable to read teams. " + e.to_s)
  end
end

# Authenticate a user using a personal JWT token
def login()
  begin
    $platform.authorize( jwt: "RC_USER_JWT" )
    list_teams("")
  rescue StandardError => e
    puts ("Unable to authenticate to platform. Check credentials. " + e.to_s)
  end
end

# Instantiate the SDK and get the platform instance
$platform = RingCentral.new( "RC_APP_CLIENT_ID", "RC_APP_CLIENT_SECRET", "https://platform.ringcentral.com" )

login()
using System;
using System.IO;
using System.Threading.Tasks;
using System.Collections.Generic;
using RingCentral;
using Newtonsoft.Json;

namespace ListTeam {
  class Program {
    static RestClient restClient;

    static async Task Main(string[] args){
      // Instantiate the SDK
      restClient = new RestClient("RC_APP_CLIENT_ID", "RC_APP_CLIENT_SECRET", "https://platform.ringcentral.com");
      // Authenticate a user using a personal JWT token
      await restClient.Authorize("RC_USER_JWT");

      await list_teams("");
    }
    /*
    * List teams under an account. Read 10 teams at a time.
    */
    static private async Task list_teams(String pageToken)
    {
      try
      {
        var queryParams = new ListGlipTeamsNewParameters()
                              {
                                recordCount = 10,
                                pageToken = pageToken
                              };

        var resp = await restClient.TeamMessaging().V1().Teams().List(queryParams);
        // List teams API returns a list of teams in the ascending order based on team creation date and time.
        // I.e. from older team to newer team
        foreach (var record in resp.records)
        {
          Console.WriteLine("Team \"" + record.name + " was created on " + record.creationTime);
        }
        // To read the next page, check and use the previous page token in the navigation object.
        if (resp.navigation.prevPageToken != null)
        {
          // Make sure not to exceed the API rate limit of 40 API calls per minute
          Thread.Sleep(1200);
          Console.WriteLine("Read newer teams ...");
          await list_teams(resp.navigation.prevPageToken);
        }
      }
      catch (Exception ex)
      {
        Console.WriteLine("Unable to read teams. " + ex.Message);
      }
    }
  }
}
package ListTeams;

import java.io.IOException;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

import com.ringcentral.*;
import com.ringcentral.definitions.*;

public class ListTeams {
    static RestClient restClient;

    public static void main(String[] args) {
      var obj = new ListTeams();
      try {
        // Instantiate the SDK
        restClient = new RestClient("RC_APP_CLIENT_ID", "RC_APP_CLIENT_SECRET", "https://platform.ringcentral.com");

        // Authenticate a user using a personal JWT token
        restClient.authorize("RC_USER_JWT");
        obj.list_teams();
      } catch (RestException e) {
        System.out.println(e.getMessage());
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    /*
    * List teams under an account. Read 10 teams at a time.
    */
    public void list_teams(String pageToken) throws RestException, IOException {
        try {
            var queryParams = new ListGlipTeamsNewParameters()
                    .recordCount(10l)
                    .pageToken(pageToken);

            var resp = restClient.teamMessaging().v1().teams().list(queryParams);
            // List teams API returns a list of teams in the ascending order based on team creation date and time.
            // I.e. from older team to newer team
            for (var record : resp.records) {
                System.out.println("Team \"" + record.name + " was created on " + record.creationTime);
            }
            // To read the next page, check and use the previous page token in the navigation object.
            if (resp.navigation.prevPageToken != null) {
                try {
                    Thread.sleep(1200);
                    System.out.println("Read newer teams ...");
                    list_teams(resp.navigation.prevPageToken);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }catch (RestException e){
            System.out.println(e.getMessage());
        }
    }
}

Finding the members of a teams

Unfortunately, there is not currently a way to retrieve the members of a team. The only way to find the members of a team is via the Compliance Export.

Joining and leaving teams

A public team is visible to all users under the same account, a user can join a public team to become a new team member and existing members from any team can leave the team.

  1. The join team and leave team endpoints can be called.
  2. The add team members and remove team members can be called.

The join/leave endpoints work within the context of the currently authenticated user. Meaning if I authenticate to the API on behalf of user A, then calling these endpoints results exclusively in user A joining or leaving a team.

Adding and removing team members

The add/remove team members endpoints provides the means of adding anyone to a team, and to add/remove people in batch. Using this endpoint one can add new members by their extension id or by their email address.

The add team members and remove team members can be called.

Example: adding team members in batch

The following code sample shows how to find a team id using a team name and add more members to the team.

Running the code

  • If you have tried the Team Messaging quick start, you can just copy all the functions below and add them to the quick start project then call the find_team("", ...) function. Otherwise, edit the variables in ALL CAPS with your app and user credentials before running the code.
  • If you run on your production account, remember to use app credentials for production and change the RingCentral server URL to "https://platform.ringcentral.com"
const RC = require('@ringcentral/sdk').SDK

// Instantiate the SDK and get the platform instance
var rcsdk = new RC({
    server: "https://platform.ringcentral.com",
    clientId: "RC_APP_CLIENT_ID",
    clientSecret: "RC_APP_CLIENT_SECRET"
});
var platform = rcsdk.platform();

/* Authenticate a user using a personal JWT token */
platform.login({ jwt: "RC_USER_JWT" })

platform.on(platform.events.loginSuccess, () => {
    find_team("", "Node JS Team")
})

platform.on(platform.events.loginError, function(e){
    console.log("Unable to authenticate to platform. Check credentials.", e.message)
    process.exit(1)
});

/*
* Find the team id of the team to be added new members
*/
async function find_team(pageToken, teamName) {
  try{
    var queryParams = {
      recordCount: 10,
      pageToken: pageToken
    }
    var endpoint = "/team-messaging/v1/teams"
    var resp = await platform.get(endpoint, queryParams)
    var jsonObj = await resp.json()
    // Search through the team list to find the team
    console.log(`Find the team id of the "${teamName}`)
    for (var record of jsonObj.records) {
      if (record.name == teamName){
        console.log(`Add new members to this team ${teamName}`)
        add_new_members(record.id)
        return
      }
    }

    if (jsonObj.navigation.hasOwnProperty('prevPageToken')) {
      var pageToken = jsonObj.navigation.prevPageToken
      // Make sure not to exceed the API rate limit of 40 API calls per minute
      sleep(1200)
      console.log("Read newer teams ...")
      find_team(pageToken, teamName)
    }else{
      console.log(`Cannot find team ${teamName}`)
    }
  }catch (e){
    console.log("Unable to read teams.", e.message)
  }
}

/*
* Add new members to a team identified by the team id
*/
async function add_new_members(teamId) {
  try {
    let bodyParams = {
      members: [
          // replace the email addresses below with valid internal or external new member email address
          { email: "[email protected]" },
          { email: "[email protected]" }
      ]
    }
    let endpoint = `/team-messaging/v1/teams/${teamId}/add`
    var resp = await platform.post(endpoint, bodyParams)
    console.log(`New member(s) added. Response status ${resp.status}`)
  }catch (e){
    console.log("Unable to add new members.", e.message)
  }
}

const sleep = async (ms) => {
  await new Promise(r => setTimeout(r, ms));
}
from ringcentral import SDK
import time

#
# Find the team id of the team to be added new members
#
def find_team(pageToken, teamName):
    try:
        queryParams = {
          'recordCount': 10,
          'pageToken': pageToken
        }
        endpoint = "/team-messaging/v1/teams"
        resp = platform.get(endpoint, queryParams)
        jsonObj = resp.json()
        # Search through the team list to find the team
        print (f"Find the team id of the \"{teamName}\"")
        for record in jsonObj.records:
            if (record.name == teamName):
              print (f"Add new members to this team {teamName}")
              add_new_members(record.id)
              return

        # To read the next page, check and use the previous page token in the navigation object.
        if hasattr(jsonObj.navigation, 'prevPageToken'):
            pageToken = jsonObj.navigation.prevPageToken
            # Make sure not to exceed the API rate limit of 40 API calls per minute
            time.sleep(1.2)
            print ("Read newer teams ...")
            find_team(pageToken, teamName)
        else:
            print (f"Cannot find team {teamName}")
    except Exception as e:
        print ("Unable to read teams. ", str(e))

#
# Add new members to a team identified by the team id
#
def add_new_members(teamId):
  try:
    bodyParams = {
        'members': [
            # replace the email addresses below with valid internal or external new member email address
            { 'email': "[email protected]" },
            { 'email': "[email protected]" }
        ]
    }
    endpoint = f"/team-messaging/v1/teams/{teamId}/add"
    resp = platform.post(endpoint, bodyParams)
    print (f"New member(s) added. Response status {resp.response().status_code}")
  except Exception as e:
    print ("Unable to add new members. " + str(e))


# Authenticate a user using a personal JWT token
def login():
  try:
    platform.login( jwt= "RC_USER_JWT" )
    find_team("", "Python Team")
  except Exception as e:
    print ("Unable to authenticate to platform. Check credentials." + str(e))

# Instantiate the SDK and get the platform instance
rcsdk = SDK("RC_APP_CLIENT_ID", "RC_APP_CLIENT_SECRET", "https://platform.ringcentral.com")
platform = rcsdk.platform()

login()
<?php
require('vendor/autoload.php');

// Instantiate the SDK and get the platform instance
$rcsdk = new RingCentral\SDK\SDK( "RC_APP_CLIENT_ID", "RC_APP_CLIENT_SECRET", "https://platform.ringcentral.com" );
$platform = $rcsdk->platform();

/* Authenticate a user using a personal JWT token */
try {
  $platform->login(["jwt" => "RC_USER_JWT"]);
}catch (\RingCentral\SDK\Http\ApiException $e) {
  // Getting error messages using PHP native interface
  print 'Expected HTTP Error: ' . $e;
  exit ("Error message: " . $e->apiResponse->response()->error() . PHP_EOL;
}

find_team("", "PHP Team");

/*
* Find the team id of the team to be added new members
*/
function find_team($pageToken, $teamName){
  global $platform;
  try{
    $queryParams = array(
      'recordCount' => 10,
      'pageToken' => $pageToken
    );

    $endpoint = "/team-messaging/v1/teams";
    $resp = $platform->get($endpoint, $queryParams);
    $jsonObj = $resp->json();
    // Search through the team list to find the team
    print_r ("Find the team id of the \"" . $teamName . PHP_EOL);
    foreach ($jsonObj->records as $record) {
      if ($record->name == $teamName){
        print_r ("Add new members to this team " . $teamName . PHP_EOL);
        add_new_members($record->id);
        return;
      }
    }
    // To read the next page, check and use the previous page token in the navigation object.
    if (property_exists($jsonObj->navigation, 'prevPageToken')){
        $pageToken = $jsonObj->navigation->prevPageToken;
        // Make sure not to exceed the API rate limit of 40 API calls per minute
        usleep(1200000);
        print_r ("Read newer teams ..." . PHP_EOL);
        find_team($pageToken, $teamName);
    }else{
      print_r("Cannot find team " . $teamName . PHP_EOL);
    }
  }catch (\RingCentral\SDK\Http\ApiException $e) {
    print_r ("Unable to read teams. " . $e->getMessage() . PHP_EOL);
  }
}

/*
* Add new members to a team identified by the team id
*/
function add_new_members($teamId) {
  global $platform;
  try {
    $bodyParams = array (
      'members' => array (
          // replace the email addresses below with valid internal or external new member email address
          array ('email' => "[email protected]"),
          array ('email' => "[email protected]")
      )
    );
    $endpoint = "/team-messaging/v1/teams/" . $teamId . "/add";
    $resp = $platform->post($endpoint, $bodyParams);
    print_r ("New member(s) added. Response status " . $resp->response()->getStatusCode() . PHP_EOL);
  }catch (\RingCentral\SDK\Http\ApiException $e) {
    print_r ("Unable to add new members. " . $e->getMessage() . PHP_EOL);
  }
}
?>
require 'ringcentral'

#
# Find the team id of the team to be added new members
#
def find_team(pageToken, teamName)
    begin
        queryParams = {
          'recordCount': 10,
          'pageToken': pageToken
        }
        endpoint = "/team-messaging/v1/teams"
        resp = $platform.get(endpoint, queryParams)
        jsonObj = resp.body
        # Search through the team list to find the team
        puts ("Find the team id of \"" + teamName + "\"")
        for record in jsonObj['records'] do
            if (record['name'] == teamName)
              puts ("Add new members to team \"" + teamName + "\"")
              add_new_members(record['id'])
              return
            end
        end

        # To read the next page, check and use the previous page token in the navigation object.
        if jsonObj['navigation']['prevPageToken']
            pageToken = jsonObj['navigation']['prevPageToken']
            # Make sure not to exceed the API rate limit of 40 API calls per minute
            sleep(1.2)
            puts ("Read newer teams ...")
            find_team(pageToken, teamName)
        else
            puts ("Cannot find team " + teamName)
        end
    rescue StandardError => e
      puts ("Unable to read teams. " + e.to_s)
    end
end

#
# Add new members to a team identified by the team id
#
def add_new_members(teamId)
  begin
    bodyParams = {
        'members': [
            # replace the email addresses below with valid internal or external new member email address
            { 'email': "[email protected]" },
            { 'email': "[email protected]" }
        ]
    }
    endpoint = "/team-messaging/v1/teams/" + teamId + "/add"
    resp = $platform.post(endpoint, payload: bodyParams)
    puts ("New member(s) added. Response status " + resp.status().to_s)
  rescue StandardError => e
    puts ("Unable to add team members. " + e.to_s)
  end
end


# Authenticate a user using a personal JWT token
def login()
  begin
    $platform.authorize( jwt: "RC_USER_JWT" )
    find_team("", "Ruby Team")
  rescue StandardError => e
    puts ("Unable to authenticate to platform. Check credentials. " + e.to_s)
  end
end

# Instantiate the SDK and get the platform instance
$platform = RingCentral.new( "RC_APP_CLIENT_ID", "RC_APP_CLIENT_SECRET", "https://platform.ringcentral.com" )

login()
using System;
using System.IO;
using System.Threading.Tasks;
using System.Collections.Generic;
using RingCentral;
using Newtonsoft.Json;

namespace AddTeamMembers {
  class Program {
    static RestClient restClient;

    static async Task Main(string[] args){
      // Instantiate the SDK
      restClient = new RestClient("RC_APP_CLIENT_ID", "RC_APP_CLIENT_SECRET", "https://platform.ringcentral.com");
      // Authenticate a user using a personal JWT token
      await restClient.Authorize("RC_USER_JWT");

      await find_team("", "C# Team");
    }
    /*
    * Find the team id of the team to be added new members
    */
    static private async Task find_team(String pageToken, String teamName)
    {
      try
      {
        var queryParams = new ListGlipTeamsNewParameters()
        {
          recordCount = 10,
          pageToken = pageToken
        };

        var resp = await restClient.TeamMessaging().V1().Teams().List(queryParams);
        // Search through the team list to find the team
        Console.WriteLine("Find the team id of the " + teamName);
        foreach (var record in resp.records)
        {
          if (record.name == teamName)
          {
            Console.WriteLine("Add new members to team \"" + teamName + "\"");
            await add_new_members(record.id);
            return;
          }
        }
        // To read the next page, check and use the previous page token in the navigation object.
        if (resp.navigation.prevPageToken != null)
        {
          Thread.Sleep(1200);
          Console.WriteLine("Read newer teams ...");
          await find_team(resp.navigation.prevPageToken, teamName);
        }
        else
        {
          Console.WriteLine("Cannot find team " + teamName);
        }
      }
      catch (Exception ex)
      {
        Console.WriteLine("Unable to read teams. " + ex.Message);
      }
    }
    /*
    * Add new members to a team identified by the team id
    */
    static private async Task add_new_members(String teamId)
    {
      try
      {
        var bodyParams = new TMAddTeamMembersRequest();

        // Add internal members using their extension id
        bodyParams.members = new TMAddTeamMembersRequestMembers[] {
          // replace the email addresses below with valid internal or external new member email address
          new TMAddTeamMembersRequestMembers { email = "[email protected]" },
          new TMAddTeamMembersRequestMembers { email = "[email protected]" },
        };

        var resp = await restClient.TeamMessaging().V1().Teams(teamId).Add().Post(bodyParams);
        Console.WriteLine("New member(s) added.");
      }
      catch (Exception ex)
      {
        Console.WriteLine("Unable to create a new team. " + ex.Message);
      }
    }
  }
}
package AddTeamMembers;

import java.io.IOException;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

import com.ringcentral.*;
import com.ringcentral.definitions.*;

public class AddTeamMembers {
    static RestClient restClient;

    public static void main(String[] args) {
      var obj = new AddTeamMembers();
      try {
        // Instantiate the SDK
        restClient = new RestClient("RC_APP_CLIENT_ID", "RC_APP_CLIENT_SECRET", "https://platform.ringcentral.com");

        // Authenticate a user using a personal JWT token
        restClient.authorize("RC_USER_JWT");
        obj.find_team("", "Java Team");
      } catch (RestException e) {
        System.out.println(e.getMessage());
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    /*
    * Find the team id of the team to be added new members
    */
    public void find_team(String pageToken, String teamName) throws RestException, IOException {
        try {
            var queryParams = new ListGlipTeamsNewParameters()
                    .recordCount(10l)
                    .pageToken(pageToken);

            var resp = restClient.teamMessaging().v1().teams().list(queryParams);
            // Search through the team list to find the team
        System.out.println("Find the team id of the " + teamName);
            for (var record : resp.records) {
                if (record.name.equals(teamName)){
                    System.out.println("Add new members to team \"" + teamName + "\"");
                    add_new_members(record.id);
                    return;
                }
            }
            // To read the next page, check and use the previous page token in the navigation object.
            if (resp.navigation.prevPageToken != null) {
                try {
                    Thread.sleep(1200);
                    System.out.println("Read newer teams ...");
                    find_team(resp.navigation.prevPageToken, teamName);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else {
                System.out.println("Cannot find team " + teamName);
            }
        }catch (RestException e){
            System.out.println(e.getMessage());
        }
    }
    /*
    * Add new members to a team identified by the team id
    */
    public void add_new_members(String teamId) throws RestException, IOException{
        try {
            var bodyParams = new TMAddTeamMembersRequest();
            // Add internal members using their extension id
        bodyParams.members = new TMAddTeamMembersRequestMembers[] {
              // replace the email addresses below with valid internal or external new member email address
              new TMAddTeamMembersRequestMembers().email("[email protected]"),
              new TMAddTeamMembersRequestMembers().email("[email protected]")
        };

        restClient.teamMessaging().v1().teams(teamId).add().post(bodyParams);
        System.out.println("New member(s) added.");
        } catch (RestException e) {
            System.out.println(e.getMessage());
        }

    }
}