### Install OpenCloud with bun Source: https://opencloud.relatio.cc/guide/getting-started Install the OpenCloud client package using bun. ```sh $ bun add @relatiohq/opencloud ``` -------------------------------- ### Install OpenCloud with yarn Source: https://opencloud.relatio.cc/guide/getting-started Install the OpenCloud client package using yarn. ```sh $ yarn add @relatiohq/opencloud ``` -------------------------------- ### Complete Example Source: https://opencloud.relatio.cc/guide/resources/groups A comprehensive example demonstrating the integration of various group operations. ```APIDOC ## Complete Example Here's a complete example that combines multiple group operations: ```typescript // Get group information const group = await client.groups.get("123456789"); console.log(`Managing group: ${group.displayName}`); // List all roles const roles = await client.groups.listGroupRoles("123456789"); console.log(`Total roles: ${roles.groupRoles.length}`); // Get admin role const adminRole = roles.groupRoles.find(r => r.displayName === "Admin"); // List members with admin role if (adminRole) { const admins = await client.groups.listGroupMemberships("123456789", { filter: `role == '${adminRole.id}'` }); console.log(`Total admins: ${admins.groupMemberships.length}`); } // Check for pending join requests const requests = await client.groups.listGroupJoinRequests("123456789"); console.log(`Pending requests: ${requests.groupJoinRequests.length}`); ``` ``` -------------------------------- ### Install OpenCloud SDK Source: https://opencloud.relatio.cc/ Install the Relatio OpenCloudTyped SDK using npm. This is the first step to using the SDK in your project. ```bash npm install @relatiohq/opencloud ``` -------------------------------- ### Install OpenCloud with npm Source: https://opencloud.relatio.cc/guide/getting-started Install the OpenCloud client package using npm. ```sh $ npm install @relatiohq/opencloud ``` -------------------------------- ### Install OpenCloud with pnpm Source: https://opencloud.relatio.cc/guide/getting-started Install the OpenCloud client package using pnpm. ```sh $ pnpm add @relatiohq/opencloud ``` -------------------------------- ### Install OpenCloud SDK with npm Source: https://opencloud.relatio.cc/guide/migration Command to install the OpenCloud SDK using npm. ```sh $ npm install @relatiohq/opencloud ``` -------------------------------- ### Get User Information: Before and After SDK Source: https://opencloud.relatio.cc/guide/migration Compares fetching user information using manual fetch calls versus the OpenCloud SDK's `client.users.get` method. ```typescript // Before const response = await fetch( `https://apis.roblox.com/cloud/v2/users/${userId}` ); const user = await response.json(); ``` ```typescript // After const user = await client.users.get(userId); ``` -------------------------------- ### Quick Start: Initialize and Use OpenCloud Client Source: https://opencloud.relatio.cc/guide/getting-started Initialize the OpenCloud client with an API key and perform basic operations like fetching user and group details. Ensure your API key is set as an environment variable. ```typescript import { OpenCloud } from "@relatiohq/opencloud"; // Initialize the client with your API key const client = new OpenCloud({ apiKey: process.env.ROBLOX_API_KEY, }); // Get user information const user = await client.users.get("123456789"); console.log(user.displayName); // "John Doe" // Get group details const group = await client.groups.get("987654321"); console.log(group.displayName); // "My Group" ``` -------------------------------- ### Complete Example: Group Operations Source: https://opencloud.relatio.cc/guide/resources/groups Demonstrates a sequence of common group operations, including fetching group info, listing roles, finding members by role, and checking join requests. ```typescript // Get group information const group = await client.groups.get("123456789"); console.log(`Managing group: ${group.displayName}`); // List all roles const roles = await client.groups.listGroupRoles("123456789"); console.log(`Total roles: ${roles.groupRoles.length}`); // Get admin role const adminRole = roles.groupRoles.find(r => r.displayName === "Admin"); // List members with admin role if (adminRole) { const admins = await client.groups.listGroupMemberships("123456789", { filter: `role == '${adminRole.id}'` }); console.log(`Total admins: ${admins.groupMemberships.length}`); } // Check for pending join requests const requests = await client.groups.listGroupJoinRequests("123456789"); console.log(`Pending requests: ${requests.groupJoinRequests.length}`); ``` -------------------------------- ### Get Group Members: Before and After SDK Source: https://opencloud.relatio.cc/guide/migration Shows how to retrieve group members using manual fetch calls compared to the SDK's `client.groups.listGroupMemberships`. ```typescript // Before const response = await fetch( `https://apis.roblox.com/cloud/v2/groups/${groupId}/memberships`, { headers: { "x-api-key": apiKey } } ); const data = await response.json(); const members = data.groupMemberships; ``` ```typescript // After const page = await client.groups.listGroupMemberships(groupId); const members = page.groupMemberships; ``` -------------------------------- ### Filter User Inventory by Asset Type Source: https://opencloud.relatio.cc/guide/resources/users Retrieve specific types of items from a user's inventory by applying filters. This example shows how to get only hats and pants. ```typescript // Get only hats and pants const items = await client.users.listInventoryItems("123456789", { filter: "inventoryItemAssetTypes=HAT,CLASSIC_PANTS" }); ``` -------------------------------- ### Getting User Information Source: https://opencloud.relatio.cc/guide/resources/users Retrieve basic user profile information by providing a user ID. ```APIDOC ## Get User Information ### Description Retrieve basic user profile information by user ID. ### Method GET (implied by client.users.get) ### Endpoint /users/{userId} ### Parameters #### Path Parameters - **userId** (string) - Required - The ID of the user to retrieve. ### Request Example ```typescript const user = await client.users.get("123456789"); ``` ### Response #### Success Response (200) - **displayName** (string) - The display name of the user. - **name** (string) - The username of the user. - **hasVerifiedBadge** (boolean) - Indicates if the user has a verified badge. ``` -------------------------------- ### Initialize OpenCloud Client for Multi-Tenant OAuth2 Source: https://opencloud.relatio.cc/api/classes/OpenCloud This example demonstrates creating an OpenCloud client without default authentication, intended for multi-tenant scenarios using per-request OAuth2 tokens. The `withAuth` method is used to apply specific credentials for subsequent requests. ```typescript // Multi-tenant usage with per-request OAuth2 const client = new OpenCloud(); // No default auth const userClient = client.withAuth({ kind: "oauth2", accessToken: "user-token" }); const groups = await userClient.groups.listMemberships("123456"); ``` -------------------------------- ### Initialize OpenCloud Client with Custom Retry Attempts Source: https://opencloud.relatio.cc/guide/rate-limiting Configure the OpenCloud SDK client with a custom number of retry attempts. This example increases the attempts to 6 for more aggressive retries. ```typescript // More aggressive retries const client = new OpenCloud({ apiKey: process.env.ROBLOX_API_KEY!, retry: { attempts: 6, // More retry attempts backoff: "exponential" } }); ``` -------------------------------- ### Fetch User Inventory Items Source: https://opencloud.relatio.cc/guide/getting-started Retrieve a list of inventory items for a given user, with options to filter by item type and page size. This example iterates through the items and logs their display names. ```typescript // Get a user's inventory items const inventory = await client.users.listInventoryItems("123456789", { maxPageSize: 50, filter: "inventoryItemAssetTypes=HAT,CLASSIC_PANTS", }); for (const item of inventory.inventoryItems) { console.log(item.assetDetails.displayName); } ``` -------------------------------- ### get Source: https://opencloud.relatio.cc/api/classes/Universes Retrieves a universe's information by its unique ID. This method is useful for fetching details about a specific Roblox universe. ```APIDOC ## GET /universes/{universeId} ### Description Retrieves a universe's information by universe ID. ### Method GET ### Endpoint /universes/{universeId} ### Parameters #### Path Parameters - **universeId** (string) - Required - The unique universe ID (numeric string) ### Response #### Success Response (200) - **Universe** (object) - The universe's data ### Response Example ```json { "id": "123456789", "displayName": "Roblox" } ``` ### See https://create.roblox.com/docs/cloud/reference/universe#Cloud_Getuniverse ``` -------------------------------- ### List Group Memberships Source: https://opencloud.relatio.cc/guide/getting-started List members of a specific group, with options to filter by role and page size. This example logs the total count of members found. ```typescript const members = await client.groups.listGroupMemberships("987654321", { maxPageSize: 100, filter: "role == 'groups/987654321/roles/12345678'", }); console.log(`Total members: ${members.groupMemberships.length}`); ``` -------------------------------- ### Fetch First Page of User Inventory Source: https://opencloud.relatio.cc/guide/pagination Retrieve the initial set of items for a user's inventory. This snippet demonstrates how to get the first page of results and check if more pages are available. ```typescript // Get first page of user inventory const firstPage = await client.users.listInventoryItems("123456789"); console.log(`Found ${firstPage.inventoryItems.length} items`); console.log(`Has more pages: ${!!firstPage.nextPageToken}`); ``` -------------------------------- ### get Source: https://opencloud.relatio.cc/api/classes/Users Retrieves a Roblox user's profile information by user ID. This method fetches comprehensive profile data for a specified user. ```APIDOC ## GET /v1/users/{userId} ### Description Retrieves a Roblox user's profile information by user ID. ### Method GET ### Endpoint /v1/users/{userId} ### Parameters #### Path Parameters - **userId** (string) - Required - The unique user ID (numeric string) ### Response #### Success Response (200) - **User** (object) - User profile data ### Response Example ```json { "description": "Promise resolving to the user's profile data" } ``` ### See https://create.roblox.com/docs/cloud/reference/User#Cloud_GetUser ``` -------------------------------- ### Get Universe Information Source: https://opencloud.relatio.cc/guide/resources/universes Retrieve universe information by its unique ID. This includes details like display name and feature flags for voice chat and desktop support. ```APIDOC ## Get Universe Information ### Description Retrieve universe information by universe ID. ### Method GET ### Endpoint /universes/{universeId} ### Parameters #### Path Parameters - **universeId** (string) - Required - The ID of the universe to retrieve. ### Response #### Success Response (200) - **displayName** (string) - The display name of the universe. - **voiceChatEnabled** (boolean) - Indicates if voice chat is enabled for the universe. - **desktopEnabled** (boolean) - Indicates if desktop support is enabled for the universe. - **privateServerPriceRobux** (number) - The price of a private server in Robux, if applicable. ### Request Example ```typescript const universe = await client.universes.get("123456789"); console.log(universe.displayName); console.log(universe.voiceChatEnabled); console.log(universe.desktopEnabled); console.log(universe.privateServerPriceRobux); ``` ``` -------------------------------- ### Send Notification to User Source: https://opencloud.relatio.cc/guide/resources/users Send a notification to a specific user. Requires proper API key permissions for the target universe. This example demonstrates sending a 'MOMENT' type notification with parameters for a daily reward. ```typescript await client.users.createNotification("123456789", { source: { universe: "universes/96623001" }, payload: { type: "MOMENT", messageId: "daily-reward", parameters: { rewardType: { stringValue: "coins" }, amount: { int64Value: "1000" } }, joinExperience: { launchData: "reward_claim" }, analyticsData: { category: "Daily Rewards" } } }); ``` -------------------------------- ### Get User Profile Information Source: https://opencloud.relatio.cc/guide/resources/users Retrieve basic user profile information using their unique user ID. This method returns details such as display name, username, and verification status. ```typescript const user = await client.users.get("123456789"); console.log(user.displayName); // "John Doe" console.log(user.name); // "@johndoe" console.log(user.hasVerifiedBadge); ``` -------------------------------- ### Add Delays Between Batch Operations Source: https://opencloud.relatio.cc/guide/rate-limiting When processing multiple items in a loop, introduce small delays between requests to prevent hitting rate limits. This example adds a 100ms delay between fetching user data. ```typescript const userIds = ["123", "456", "789", "012"]; for (const userId of userIds) { try { const user = await client.users.get(userId); console.log(user.displayName); // Small delay between requests await new Promise(resolve => setTimeout(resolve, 100)); } catch (error) { console.error(`Failed to fetch user ${userId}:`, error); } } ``` -------------------------------- ### List Inventory with Pagination: Before and After SDK Source: https://opencloud.relatio.cc/guide/migration Demonstrates migrating inventory listing with pagination from manual fetch loops to the SDK's `client.users.listInventoryItems`. ```typescript // Before let allItems = []; let pageToken = undefined; do { const url = new URL(`https://apis.roblox.com/cloud/v2/users/${userId}/inventory-items`); if (pageToken) url.searchParams.set("pageToken", pageToken); const response = await fetch(url, { headers: { "x-api-key": apiKey } }); const data = await response.json(); allItems.push(...data.inventoryItems); pageToken = data.nextPageToken; } while (pageToken); ``` ```typescript // After let allItems = []; let pageToken = undefined; do { const page = await client.users.listInventoryItems(userId, { pageToken }); allItems.push(...page.inventoryItems); pageToken = page.nextPageToken; } while (pageToken); ``` -------------------------------- ### Getting Group Information Source: https://opencloud.relatio.cc/guide/resources/groups Retrieve basic information about a group using its ID. ```APIDOC ## Getting Group Information Retrieve basic group information by group ID: ```typescript const group = await client.groups.get("123456789"); console.log(group.displayName); // "My Awesome Group" console.log(group.description); console.log(group.owner); // "users/987654321" console.log(group.memberCount); console.log(group.publicEntryAllowed); ``` ``` -------------------------------- ### Initialize and Use OpenCloud Client Source: https://opencloud.relatio.cc/ Initialize the OpenCloud client with your API key and make a request to fetch user data. Ensure you replace 'your-api-key' with your actual key. ```typescript import { OpenCloud } from "@relatiohq/opencloud"; const client = new OpenCloud({ apiKey: "your-api-key" }); const user = await client.users.get("123456789"); console.log(user.displayName); ``` -------------------------------- ### OpenCloud Constructor Source: https://opencloud.relatio.cc/api/classes/OpenCloud Initializes a new instance of the OpenCloud client. This is the main entry point for the SDK. ```APIDOC ## Constructor OpenCloud ### Description Creates a new OpenCloud SDK client instance. ### Signature ```ts new OpenCloud(config: OpenCloudConfig): OpenCloud ``` ### Parameters #### Parameters - **config** (OpenCloudConfig) - Required - Configuration options for the client ### Returns - `OpenCloud` - A new OpenCloud client instance. ``` -------------------------------- ### Get User Restriction Source: https://opencloud.relatio.cc/guide/resources/universes Check the restriction details for a specific user within a universe. Requires both universe and user IDs. ```typescript const restriction = await client.universes.getUserRestriction( "123456789", // Universe ID "987654321" // User ID ); console.log(restriction.gameJoinRestriction.duration); console.log(restriction.gameJoinRestriction.displayReason); ``` -------------------------------- ### Get Current Group Shout Source: https://opencloud.relatio.cc/guide/resources/groups Retrieve the latest announcement (shout) posted for a group. If no shout exists, it indicates that there is no active announcement. ```typescript const shout = await client.groups.getGroupShout("123456789"); if (shout.content) { console.log(shout.content); // Shout message console.log(shout.poster); // User who posted console.log(shout.createTime); console.log(shout.updateTime); } else { console.log("No active shout"); } ``` -------------------------------- ### Get User Restriction Source: https://opencloud.relatio.cc/guide/resources/universes Check the restriction details for a specific user within a universe. This provides information on the duration and reason for any active restrictions. ```APIDOC ## Getting a User Restriction ### Description Check restriction details for a specific user. ### Method GET ### Endpoint /universes/{universeId}/restrictions/users/{userId} ### Parameters #### Path Parameters - **universeId** (string) - Required - The ID of the universe. - **userId** (string) - Required - The ID of the user. ### Response #### Success Response (200) - **gameJoinRestriction** (object) - Details about the game join restriction. - **duration** (string) - The duration of the restriction (e.g., "86400s"). - **displayReason** (string) - The reason for the restriction, visible to the user. ### Request Example ```typescript const restriction = await client.universes.getUserRestriction( "123456789", // Universe ID "987654321" // User ID ); console.log(restriction.gameJoinRestriction.duration); console.log(restriction.gameJoinRestriction.displayReason); ``` ``` -------------------------------- ### Initialize OpenCloud Client with API Key Source: https://opencloud.relatio.cc/api/classes/OpenCloud Use this snippet to create a client instance for traditional API key authentication. You can then use this client to access various API resources like user data. ```typescript const client = new OpenCloud({ apiKey: 'your-api-key-here' }); const user = await client.users.get('123456789'); console.log(user.displayName); ``` -------------------------------- ### get Source: https://opencloud.relatio.cc/api/classes/Groups Retrieves a Roblox group's information by group ID. This method fetches details about a specific group using its unique identifier. ```APIDOC ## GET /groups/{groupId} ### Description Retrieves a Roblox group's information by group ID. ### Method GET ### Endpoint /groups/{groupId} ### Parameters #### Path Parameters - **groupId** (string) - Required - The unique group ID (numeric string) ### Response #### Success Response (200) - **Group** (object) - The group's data ### Response Example ```json { "id": "123456789", "name": "Roblox", "displayName": "Roblox", "description": "The official Roblox group.", "memberCount": 1000000, "publicEntryAllowed": true } ``` ### See https://create.roblox.com/docs/cloud/reference/Group#Cloud_GetGroup ``` -------------------------------- ### Code Conciseness: Before and After SDK for Inventory Listing Source: https://opencloud.relatio.cc/guide/migration Compares the verbosity of manual fetch calls for listing inventory items with specific filters to the conciseness achieved using the OpenCloud SDK. ```typescript // Before: Verbose const url = new URL(`https://apis.roblox.com/cloud/v2/users/${userId}/inventory-items`); url.searchParams.set("maxPageSize", "50"); url.searchParams.set("filter", "inventoryItemAssetTypes=HAT"); const response = await fetch(url, { headers: { "x-api-key": apiKey } }); const data = await response.json(); ``` ```typescript // After: Concise const data = await client.users.listInventoryItems(userId, { maxPageSize: 50, filter: "inventoryItemAssetTypes=HAT" }); ``` -------------------------------- ### Constructor for OpenCloud Client Source: https://opencloud.relatio.cc/api/classes/OpenCloud Instantiates a new OpenCloud SDK client. The configuration object allows specifying authentication details and other client-specific options. ```typescript new OpenCloud(config): OpenCloud; ``` -------------------------------- ### withAuth Method Source: https://opencloud.relatio.cc/api/classes/OpenCloud Creates a scoped client instance with per-request authentication, allowing for different credentials for each request. ```APIDOC ## Method withAuth ### Description Creates a scoped client instance with per-request authentication. This allows reusing a single client while providing different credentials for each request. ### Signature ```ts withAuth(auth: AuthConfig): OpenCloud ``` ### Parameters #### Parameters - **auth** (AuthConfig) - Required - Authentication configuration to use for this scope ### Returns - `OpenCloud` - A new scoped OpenCloud instance with the provided auth ### Example ```typescript // OAuth2 authentication const userClient = client.withAuth({ kind: "oauth2", accessToken: "user-token-here" }); const groups = await userClient.groups.listMemberships("123456"); // API key authentication const adminClient = client.withAuth({ kind: "apiKey", apiKey: "admin-key-here" }); const user = await adminClient.users.get("789"); ``` ``` -------------------------------- ### Get Group Shout Source: https://opencloud.relatio.cc/api/classes/Groups Fetches the latest shout from a Roblox group using its unique ID. The returned shout object contains the content and timestamp. ```typescript const shout = await client.groups.getGroupShout('123456789'); console.log(shout.content); // "Welcome to the group!" ``` -------------------------------- ### OpenCloudConfig Properties Source: https://opencloud.relatio.cc/api/interfaces/OpenCloudConfig Configuration options for initializing the OpenCloud SDK client. ```APIDOC ## Interface: OpenCloudConfig ### Description Configuration options for initializing the OpenCloud SDK client. ### Properties #### apiKey (string, optional) Roblox Open Cloud API key for authentication. This is optional and if not provided, you must use withAuth() for per-request authentication. #### userAgent (string, optional) Custom user agent string for API requests (defaults to "@relatiohq/opencloud") #### baseUrl (string, optional) Base URL for the Roblox API (defaults to "https://apis.roblox.com") #### retry (HttpRetry, optional) Retry configuration for failed requests #### fetchImpl (function, optional) Custom fetch implementation (useful for testing or custom environments) ##### Call Signature ```typescript (input: URL | RequestInfo, init?: RequestInit): Promise; ``` ##### Parameters - `input` (URL | RequestInfo) - `init` (RequestInit, optional) ##### Returns `Promise` ##### Call Signature ```typescript (input: string | URL | Request, init?: RequestInit): Promise; ``` ##### Parameters - `input` (string | URL | Request) - `init` (RequestInit, optional) ##### Returns `Promise` ``` -------------------------------- ### Create Scoped Client with API Key Authentication Source: https://opencloud.relatio.cc/api/classes/OpenCloud This snippet shows how to create a client instance with API key authentication using the `withAuth` method. This is suitable for administrative tasks or when using service-based API keys. ```typescript // API key authentication const adminClient = client.withAuth({ kind: "apiKey", apiKey: "admin-key-here" }); const user = await adminClient.users.get("789"); ``` -------------------------------- ### Accept Join Requests: Before and After SDK Source: https://opencloud.relatio.cc/guide/migration Compares accepting group join requests via manual POST requests to using the SDK's `client.groups.acceptGroupJoinRequest`. ```typescript // Before await fetch( `https://apis.roblox.com/cloud/v2/groups/${groupId}/join-requests/${requestId}:accept`, { method: "POST", headers: { "x-api-key": apiKey } } ); ``` ```typescript // After await client.groups.acceptGroupJoinRequest(groupId, requestId); ``` -------------------------------- ### Get Universe Information Source: https://opencloud.relatio.cc/guide/resources/universes Retrieve details about a specific Roblox universe using its ID. This includes display name, voice chat status, and platform availability. ```typescript const universe = await client.universes.get("123456789"); console.log(universe.displayName); console.log(universe.voiceChatEnabled); console.log(universe.desktopEnabled); console.log(universe.privateServerPriceRobux); ``` -------------------------------- ### Get Universe Information Source: https://opencloud.relatio.cc/api/classes/Universes Retrieves a universe's information using its unique ID. Ensure the API key is valid and the universe exists to avoid errors. ```typescript const universe = await client.universes.get('123456789'); console.log(universe.displayName); // "Roblox" ``` -------------------------------- ### Create Users Client Source: https://opencloud.relatio.cc/api/classes/Users Instantiates the Users API client. Requires an HTTP client for making requests. ```typescript new Users(http): Users; ``` -------------------------------- ### Get User Profile Source: https://opencloud.relatio.cc/api/classes/Users Retrieves a Roblox user's profile information by their unique user ID. Ensure the API key is valid and the user exists. ```typescript get(userId): Promise; ``` ```typescript const user = await client.users.get('123456789'); console.log(user.displayName); // "John Doe" ``` -------------------------------- ### Initialize OpenCloud Client with Environment Variable Source: https://opencloud.relatio.cc/guide/authentication Recommends storing API keys in environment variables for security. This snippet shows how to access the API key from `process.env` when initializing the client. ```typescript const client = new OpenCloud({ apiKey: process.env.ROBLOX_API_KEY! }); ``` -------------------------------- ### Get Group Information Source: https://opencloud.relatio.cc/guide/resources/groups Retrieve basic information about a group using its ID. This includes display name, description, owner, member count, and public entry status. ```typescript const group = await client.groups.get("123456789"); console.log(group.displayName); // "My Awesome Group" console.log(group.description); console.log(group.owner); // "users/987654321" console.log(group.memberCount); console.log(group.publicEntryAllowed); ``` -------------------------------- ### Use Pagination Wisely with Max Page Size Source: https://opencloud.relatio.cc/guide/rate-limiting Demonstrates appropriate usage of pagination by setting a reasonable 'maxPageSize'. Avoid requesting the maximum allowed items too frequently, as this can lead to rate limiting. ```typescript // Good: Reasonable page size const members = await client.groups.listGroupMemberships("123456789", { maxPageSize: 100 }); // Avoid: Requesting maximum items too frequently const members = await client.groups.listGroupMemberships("123456789", { maxPageSize: 1000 }); ``` -------------------------------- ### Configure OAuth2 Authentication Source: https://opencloud.relatio.cc/guide/authentication Illustrates how to set up OAuth2 authentication using the `AuthConfig` type with an access token. This method is typically used for user-specific operations. ```typescript const auth = { kind: "oauth2", accessToken: "user-access-token" }; const client = new OpenCloud().withAuth(auth); ``` -------------------------------- ### Get Specific User Restriction Source: https://opencloud.relatio.cc/api/classes/Universes Retrieves a specific user restriction by providing both the universe ID and the user restriction ID. This operation requires the `universe.user-restriction:read` scope and valid credentials. ```typescript const userRestriction = await client.universes.getUserRestriction('123456789', '123456789'); console.log(userRestriction); ``` -------------------------------- ### Load Environment Variables with dotenv Source: https://opencloud.relatio.cc/guide/authentication Shows how to use the `dotenv` package to load environment variables, including API keys, from a `.env` file into your application. Ensure the `.env` file is in your project root. ```plaintext ROBLOX_API_KEY=your-api-key-here ``` ```typescript import "dotenv/config"; import { OpenCloud } from "@relatiohq/opencloud"; const client = new OpenCloud({ apiKey: process.env.ROBLOX_API_KEY! }); ``` -------------------------------- ### Join Experience Object Source: https://opencloud.relatio.cc/api/interfaces/UserNotificationPayload Contains data specific to the join experience, including launch data. ```typescript joinExperience: { launchData: string; }; ``` -------------------------------- ### Get Group Role Source: https://opencloud.relatio.cc/api/classes/Groups Fetches details for a specific role within a Roblox group, identified by both group ID and role ID. This is useful for retrieving role permissions or display names. ```typescript const role = await client.groups.getGroupRole('123456789', '7920705'); console.log(role.displayName); // "Admin" ``` -------------------------------- ### Configure API Key Authentication Source: https://opencloud.relatio.cc/guide/authentication Demonstrates how to explicitly define API key authentication using the `AuthConfig` type. This is useful for clarity or when dynamically setting authentication methods. ```typescript const auth = { kind: "apiKey", apiKey: "your-api-key" }; const client = new OpenCloud().withAuth(auth); ``` -------------------------------- ### Get Specific Group Role Details Source: https://opencloud.relatio.cc/guide/resources/groups Retrieve detailed information about a single role within a group, identified by both the group ID and the role ID. Includes display name, description, and permissions. ```typescript const role = await client.groups.getGroupRole("123456789", "12345"); console.log(role.displayName); console.log(role.description); console.log(role.permissions); // Role permissions object ``` -------------------------------- ### Initialize OpenCloud Client with Default Retries Source: https://opencloud.relatio.cc/guide/rate-limiting Configure the OpenCloud SDK client with default retry settings. The SDK will automatically attempt retries with exponential backoff when rate limits are encountered. ```typescript const client = new OpenCloud({ apiKey: process.env.ROBLOX_API_KEY!, retry: { attempts: 4, // Number of retry attempts (default: 4) backoff: "exponential" // Exponential backoff strategy (default) } }); // The SDK will automatically retry if rate limited const user = await client.users.get("123456789"); ``` -------------------------------- ### Get Group Information Source: https://opencloud.relatio.cc/api/classes/Groups Retrieves a Roblox group's information by its unique ID. Ensure the group ID is a numeric string. Throws an error if the API key is invalid or the group is not found. ```typescript const group = await client.groups.get('123456789'); console.log(group.displayName); // "Roblox" ``` -------------------------------- ### Working with Inventory Source: https://opencloud.relatio.cc/guide/resources/users List items in a user's inventory with optional filtering and pagination. ```APIDOC ## List Inventory Items ### Description List items in a user's inventory with optional filtering and pagination. ### Method GET (implied by client.users.listInventoryItems) ### Endpoint /users/{userId}/inventory ### Parameters #### Path Parameters - **userId** (string) - Required - The ID of the user whose inventory to list. #### Query Parameters - **filter** (string) - Optional - Filters items by asset type (e.g., "inventoryItemAssetTypes=HAT,CLASSIC_PANTS"). - **maxPageSize** (number) - Optional - The maximum number of items to return per page. - **pageToken** (string) - Optional - A token to retrieve the next page of results. ### Request Example ```typescript // Get all inventory items const inventory = await client.users.listInventoryItems("123456789"); // Get only hats and pants const items = await client.users.listInventoryItems("123456789", { filter: "inventoryItemAssetTypes=HAT,CLASSIC_PANTS" }); // Paginate large inventories let pageToken: string | undefined; let allItems = []; do { const page = await client.users.listInventoryItems("123456789", { maxPageSize: 100, pageToken }); allItems.push(...page.inventoryItems); pageToken = page.nextPageToken; } while (pageToken); ``` ### Response #### Success Response (200) - **inventoryItems** (array) - A list of inventory items. - **item.assetDetails.displayName** (string) - The display name of the asset. - **item.assetDetails.assetType** (string) - The type of the asset. - **nextPageToken** (string) - A token for retrieving the next page of results. ``` -------------------------------- ### Launch Data Property Source: https://opencloud.relatio.cc/api/interfaces/UserNotificationPayload The launch data associated with the join experience. This property is a string. ```typescript launchData: string; ``` -------------------------------- ### Multi-Tenant Server Authentication with OAuth2 Source: https://opencloud.relatio.cc/guide/authentication This pattern is suitable for backend services handling requests from multiple users. It dynamically creates a scoped client for each user based on their access token provided in the request headers. ```typescript import { OpenCloud } from "@relatiohq/opencloud"; import express from "express"; const app = express(); const client = new OpenCloud(); // Shared client, no default auth app.get("/api/my-groups", async (req, res) => { // Get user's access token from request const accessToken = req.headers.authorization?.split(" ")[1]; // Create scoped client for this user const userClient = client.withAuth({ kind: "oauth2", accessToken: accessToken! }); // Make requests on behalf of the user const memberships = await userClient.groups.listGroupMemberships(req.query.userId); res.json(memberships); }); ``` -------------------------------- ### restartUniverseServers Source: https://opencloud.relatio.cc/api/classes/Universes Restarts all servers for a given universe. This is useful for applying updates or resolving issues. ```APIDOC ## restartUniverseServers ### Description Restarts all servers for a given universe. ### Method POST ### Endpoint /v1/universes/{universeId}/servers/restart ### Parameters #### Path Parameters - **universeId** (string) - Required - The ID of the universe whose servers should be restarted. ### Request Example ```json { "example": "" } ``` ### Response #### Success Response (200) This endpoint does not return a response body on success. #### Response Example ```json { "example": "" } ``` ``` -------------------------------- ### ListOptions Interface Source: https://opencloud.relatio.cc/api/interfaces/ListOptions This interface defines the structure for options used in list and pagination operations. It includes parameters for controlling the page size and for fetching subsequent pages of results. ```APIDOC ## Interface: ListOptions Common options for list/pagination operations. ### Properties #### maxPageSize (optional, number) Maximum number of items to return per page. #### pageToken (optional, string) Token from a previous response to fetch the next page. ``` -------------------------------- ### generateSpeechAsset Source: https://opencloud.relatio.cc/api/classes/Universes Generates an English speech audio asset from the specified text. Requires `asset:read`, `asset:write`, and `universe:write` scopes. ```APIDOC ## generateSpeechAsset(universeId, body) ### Description Generates an English speech audio asset from the specified text. This endpoint requires the `asset:read` and `asset:write` scopes in addition to the `universe:write` scope. ### Parameters #### Path Parameters - **universeId** (string) - Required - The universe ID (numeric string) #### Request Body - **body** (SpeechAssetBody) - Required - The speech asset generation request body ### Returns `Promise` Promise resolving to the speech asset response ### Throws - If API key is invalid - If the universeId is invalid or other API error occurs ### Example ```typescript const speechAsset = await client.universes.generateSpeechAsset('123456789', { text: "Hello, world!", speechStyle: { voiceId: "rbx_voice_001", pitch: 1, speed: 1 } }); console.log(speechAsset); ``` ### See https://create.roblox.com/docs/cloud/reference/Universe#Cloud_GenerateSpeechAsset ``` -------------------------------- ### Create Scoped Client with OAuth2 Authentication Source: https://opencloud.relatio.cc/api/classes/OpenCloud Use the `withAuth` method to create a client instance with OAuth2 authentication for specific requests. This is useful when you need to perform actions on behalf of a user using their access token. ```typescript // OAuth2 authentication const userClient = client.withAuth({ kind: "oauth2", accessToken: "user-token-here" }); const groups = await userClient.groups.listMemberships("123456"); ``` -------------------------------- ### Override Default Authentication with OAuth2 Source: https://opencloud.relatio.cc/guide/authentication Demonstrates how to set a default API key for a client but override it with an OAuth2 token for specific requests, offering flexibility in authentication strategies. ```typescript // Client with default API key const client = new OpenCloud({ apiKey: "default-api-key" }); // Most requests use the default API key const group = await client.groups.get("123"); // But you can override with OAuth2 for specific requests const userClient = client.withAuth({ kind: "oauth2", accessToken: "user-token" }); const userGroups = await userClient.groups.listGroupMemberships("456"); ``` -------------------------------- ### listAssetQuotas Source: https://opencloud.relatio.cc/api/classes/Users Lists asset upload and distribution quotas for a user. Quotas track rate limits for operations like uploading assets and indicate when they reset. ```APIDOC ## GET /v1/users/{userId}/asset-quotas ### Description Lists asset upload and distribution quotas for a user. Quotas track rate limits for operations like uploading assets. ### Method GET ### Endpoint /v1/users/{userId}/asset-quotas ### Parameters #### Path Parameters - **userId** (string) - Required - The unique user ID (numeric string) #### Query Parameters - **maxPageSize** (number) - Optional - The maximum number of quotas to return per page - **pageToken** (string) - Optional - A token to retrieve the next page of results ### Response #### Success Response (200) - **AssetQuotasPage** (object) - A page of asset quotas, including usage and reset times ### Response Example ```json { "description": "Promise resolving to a page of asset quotas" } ``` ### See https://create.roblox.com/docs/cloud/reference/AssetQuota#Cloud_ListAssetQuotas ``` -------------------------------- ### restartUniverseServers Source: https://opencloud.relatio.cc/api/classes/Universes Restarts all active servers for a specific universe if and only if a new version of the experience has been published. Used for releasing experience updates. ```APIDOC ## restartUniverseServers(universeId) ### Description Restarts all active servers for a specific universe if and only if a new version of the experience has been published. Used for releasing experience updates. ### Parameters #### Path Parameters - **universeId** (string) - Required - The universe ID (numeric string) ### Returns `Promise` Promise resolving to void ### Throws - If API key is invalid - If the universeId is invalid or other API error occurs ``` -------------------------------- ### List Group Join Requests with Pagination Source: https://opencloud.relatio.cc/guide/resources/groups Fetch pending join requests for a group, with support for pagination. Each request includes the user ID and the time of creation. ```typescript const requests = await client.groups.listGroupJoinRequests("123456789", { maxPageSize: 50 }); for (const request of requests.groupJoinRequests) { console.log(request.user); // "users/987654321" console.log(request.createTime); } ``` -------------------------------- ### Migrate Manual API Calls to OpenCloud SDK Source: https://opencloud.relatio.cc/guide/migration Replaces manual fetch calls with the OpenCloud SDK for user data retrieval. The SDK offers automatic error handling, retries, and type safety. ```typescript // Manual implementation const response = await fetch( `https://apis.roblox.com/cloud/v2/users/${userId}`, { headers: { "x-api-key": process.env.ROBLOX_API_KEY } } ); if (!response.ok) { const error = await response.json(); throw new Error(`API error: ${response.status} - ${error.message}`); } const user = await response.json(); ``` ```typescript import { OpenCloud } from "@relatiohq/opencloud"; const client = new OpenCloud({ apiKey: process.env.ROBLOX_API_KEY! }); // Automatic error handling, retries, and type safety const user = await client.users.get(userId); ``` -------------------------------- ### GenerateThumbnailOptions Source: https://opencloud.relatio.cc/api/interfaces/GenerateThumbnailOptions Defines the configuration options for generating a thumbnail. ```APIDOC ## Interface: GenerateThumbnailOptions ### Description This interface specifies the optional parameters that can be provided when generating a thumbnail. ### Properties #### size - **Type**: `number` - **Optional**: Yes - **Description**: The desired size of the thumbnail (e.g., width or height). #### format - **Type**: `ThumbnailFormat` - **Optional**: Yes - **Description**: The desired format of the thumbnail (e.g., JPEG, PNG). #### shape - **Type**: `ThumbnailShape` - **Optional**: Yes - **Description**: The desired shape of the thumbnail (e.g., square, circle). ``` -------------------------------- ### List User Inventory Items Source: https://opencloud.relatio.cc/api/classes/Users Lists items in a user's inventory, supporting pagination and filtering by asset type. Use `pageToken` for subsequent requests. ```typescript listInventoryItems(userId, options): Promise; ``` ```typescript // Get first page of inventory const page1 = await client.users.listInventoryItems('123456789', { maxPageSize: 50 }); // Get next page const page2 = await client.users.listInventoryItems('123456789', { pageToken: page1.nextPageToken }); // Filter for specific asset types const hats = await client.users.listInventoryItems('123456789', { filter: "inventoryItemAssetTypes=HAT,CLASSIC_PANTS,TSHIRT_ACCESSORY" }); ``` -------------------------------- ### Fetch Second Page of User Inventory Source: https://opencloud.relatio.cc/guide/pagination Fetch the subsequent page of results by using the `nextPageToken` obtained from a previous response. This is essential for retrieving data that spans multiple pages. ```typescript const firstPage = await client.users.listInventoryItems("123456789"); if (firstPage.nextPageToken) { const secondPage = await client.users.listInventoryItems("123456789", { pageToken: firstPage.nextPageToken }); console.log(`Page 2 has ${secondPage.inventoryItems.length} items`); } ``` -------------------------------- ### List User Restrictions for a Universe Source: https://opencloud.relatio.cc/api/classes/Universes Lists all user restrictions for a given universe. This method supports pagination through the `options` parameter. Requires a valid API key and an existing universe. ```typescript const userRestrictions = await client.universes.listUserRestrictions('123456789'); console.log(userRestrictions); ``` -------------------------------- ### List User Inventory Items Source: https://opencloud.relatio.cc/guide/resources/users Retrieve all items from a user's inventory. This method can be used to list all assets owned by a user. ```typescript // Get all inventory items const inventory = await client.users.listInventoryItems("123456789"); for (const item of inventory.inventoryItems) { console.log(item.assetDetails.displayName); console.log(item.assetDetails.assetType); } ``` -------------------------------- ### Handling Join Requests Source: https://opencloud.relatio.cc/guide/resources/groups Manage join requests for invite-only groups, including listing, accepting, and declining requests. ```APIDOC ## Handling Join Requests For invite-only groups, manage join requests: ### Listing Join Requests ```typescript const requests = await client.groups.listGroupJoinRequests("123456789", { maxPageSize: 50 }); for (const request of requests.groupJoinRequests) { console.log(request.user); // "users/987654321" console.log(request.createTime); } ``` ### Filtering Requests Find join requests from a specific user: ```typescript const userRequest = await client.groups.listGroupJoinRequests("123456789", { filter: "user == 'users/987654321'" }); ``` ### Accepting Requests ```typescript await client.groups.acceptGroupJoinRequest( "123456789", // Group ID "555555555" // Join request ID ); console.log("Join request accepted"); ``` ### Declining Requests ```typescript await client.groups.declineGroupJoinRequest( "123456789", // Group ID "555555555" // Join request ID ); console.log("Join request declined"); ``` ``` -------------------------------- ### Update Universe Settings Source: https://opencloud.relatio.cc/guide/resources/universes Update platform availability and other settings for a universe. This allows modification of features like voice chat and desktop support, as well as private server pricing. ```APIDOC ## Update Universe Settings ### Description Update platform availability and other settings for a universe. ### Method PUT ### Endpoint /universes/{universeId} ### Parameters #### Path Parameters - **universeId** (string) - Required - The ID of the universe to update. #### Request Body - **voiceChatEnabled** (boolean) - Optional - Whether to enable voice chat. - **desktopEnabled** (boolean) - Optional - Whether to enable desktop support. - **mobileEnabled** (boolean) - Optional - Whether to enable mobile support. - **privateServerPriceRobux** (number) - Optional - The price for private servers in Robux. ### Request Example ```typescript await client.universes.update("123456789", { voiceChatEnabled: true, desktopEnabled: true, mobileEnabled: true, privateServerPriceRobux: 100 }); ``` ``` -------------------------------- ### Importing SDK Types Source: https://opencloud.relatio.cc/guide/typescript All necessary types for the OpenCloud SDK are exported from the main package, allowing for easy import. ```typescript import { OpenCloud, User, Group, InventoryItem, GroupRole, GroupMembershipItem } from "@relatiohq/opencloud"; ``` -------------------------------- ### Publish Message to Universe Servers Source: https://opencloud.relatio.cc/api/classes/Universes Publishes a message to a universe's live servers, which can be consumed via MessagingService. ```typescript await client.universes.publishMessage('123456789', { topic: "UpdateAvailable", message: "New update has been deployed!" }); ``` -------------------------------- ### Restart Universe Servers Source: https://opencloud.relatio.cc/api/classes/Universes Restarts all active servers for a specific universe, but only if a new version of the experience has been published. This is used for releasing experience updates. ```typescript await client.universes.restartUniverseServers('123456789'); ``` -------------------------------- ### Type-Safe Client Configuration Source: https://opencloud.relatio.cc/guide/typescript Configure the OpenCloud client using a type-safe configuration object, ensuring all parameters are correctly typed. ```typescript import type { OpenCloudConfig } from "@relatiohq/opencloud"; const config: OpenCloudConfig = { apiKey: process.env.ROBLOX_API_KEY!, userAgent: "MyApp/1.0", baseUrl: "https://apis.roblox.com", retry: { attempts: 4, backoff: "exponential" } }; const client = new OpenCloud(config); ``` -------------------------------- ### AuthError Constructor Source: https://opencloud.relatio.cc/api/classes/AuthError Creates a new AuthError instance. This error is typically thrown when authentication fails due to invalid or missing API keys. ```APIDOC ## Constructor AuthError ### Description Creates a new `AuthError` instance. This error is thrown when authentication fails or credentials are invalid, typically indicating an invalid or missing API key. ### Signature ```typescript new AuthError(message?: string, status?: number, details?: unknown): AuthError ``` ### Parameters #### Parameters - **message** (string) - Optional - Error message. Defaults to "Unauthorized: invalid or missing Open Cloud credentials". - **status** (number) - Optional - HTTP status code. Defaults to 401. Can be 401 or 403. - **details** (unknown) - Optional - Additional error details from the API response. ### Returns - `AuthError` - An instance of the AuthError class. ### Overrides `OpenCloudError.constructor` ```