### Install DingTalk SDK with go get (Go) Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/11-quick-start.md Install the DingTalk SDK for Go using go get. ```bash go get github.com/aliyun/alibabacloud-dingtalk-golang ``` -------------------------------- ### Install AliGenie SDK with Pip Source: https://github.com/aliyun/dingtalk-sdk/blob/master/aligenie/python/README.md Install the alibabacloud_aligenie package using pip. Ensure pip is installed on your system. ```bash # Install the alibabacloud_aligenie pip install alibabacloud_aligenie ``` -------------------------------- ### Install DingTalk SDK using Go Mod Source: https://github.com/aliyun/dingtalk-sdk/blob/master/dingtalk/golang/README.md Install the DingTalk SDK for Go using the go get command when managing dependencies with go mod. ```sh go get github.com/alibabacloud-go/dingtalk ``` -------------------------------- ### Install DingTalk SDK with pip (Python) Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/11-quick-start.md Install the DingTalk SDK for Python using pip. ```bash pip install alibabacloud_dingtalk ``` -------------------------------- ### Object/Map Initialization Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/05-types.md Example of initializing an object with string keys and string values. ```typescript const headers = { 'content-type': 'application/json', 'x-custom-header': 'value' }; ``` -------------------------------- ### Install DingTalk SDK using Composer Source: https://github.com/aliyun/dingtalk-sdk/blob/master/dingtalk/php/README.md Use Composer to install the Alibaba Cloud DingTalk SDK for PHP. This is the recommended method for managing dependencies. ```bash composer require alibabacloud/dingtalk ``` -------------------------------- ### Install DingTalk SDK with npm or yarn Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/11-quick-start.md Install the DingTalk SDK using either npm or yarn package managers. ```bash npm install @alicloud/dingtalk # or yarn add @alicloud/dingtalk ``` -------------------------------- ### String Array Initialization Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/05-types.md Example of initializing an array of strings. ```typescript const userIds = ['user1', 'user2', 'user3']; ``` -------------------------------- ### Install DingTalk SDK via NuGet Source: https://github.com/aliyun/dingtalk-sdk/blob/master/dingtalk/csharp/README.md Use the dotnet CLI to add the AlibabaCloud.SDK.Dingtalk package to your C# project. ```bash dotnet add package AlibabaCloud.SDK.Dingtalk ``` -------------------------------- ### Install DingTalk SDK using npm Source: https://github.com/aliyun/dingtalk-sdk/blob/master/dingtalk/ts/README.md Install the DingTalk SDK for NodeJS using npm. This command adds the SDK as a dependency to your project. ```sh npm install @alicloud/dingtalk -S ``` -------------------------------- ### Authentication Example Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/02-client-base-pattern.md Demonstrates how to authenticate API requests using an access token and the `CountWorkRecordHeaders` class. ```APIDOC ## Authentication ### Description All API operations require a valid DingTalk access token for authentication. This token should be provided in the `x-acs-dingtalk-access-token` header. ### Usage ```typescript const headers = new CountWorkRecordHeaders({ xAcsDingtalkAccessToken: accessToken }); const response = await client.countWorkRecordWithOptions(request, headers, runtime); ``` ``` -------------------------------- ### Map/Dictionary Initialization Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/05-types.md Example of initializing a string-to-string map. ```typescript const metadata = { 'key1': 'value1', 'key2': 'value2' }; ``` -------------------------------- ### Go Configuration Example Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/06-configuration.md Illustrates how to configure the DingTalk SDK client in Go, setting parameters such as protocol, region ID, user agent, and various timeouts. ```go package main import ( "github.com/aliyun/dingtalk-sdk-golang/client" ) config := &client.Config{ Protocol: "https", RegionId: "cn-hangzhou", UserAgent: "my-app/1.0.0", MaxAttempts: 3, ConnectTimeout: 10000, ReadTimeout: 20000, } dingtalkClient := client.NewClient(config) ``` -------------------------------- ### Python Configuration Example Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/06-configuration.md Demonstrates how to configure the DingTalk SDK client in Python, including protocol, region, user agent, retry attempts, and timeouts. ```python from alibabacloud_dingtalk.models import Config from alibabacloud_dingtalk import contact_1_0 config = contact_1_0.Config( protocol='https', region_id='cn-hangzhou', user_agent='my-app/1.0.0', max_attempts=3, connect_timeout=10000, read_timeout=20000 ) client = contact_1_0.Client(config) ``` -------------------------------- ### Java Configuration Example Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/06-configuration.md Shows how to configure the DingTalk SDK client in Java using a fluent builder pattern for settings like protocol, region, user agent, and timeouts. ```java import com.alibabacloud.dingtalk.models.Config; import com.alibabacloud.dingtalk.contact_1_0.Client; Config config = new Config() .setProtocol("https") .setRegionId("cn-hangzhou") .setUserAgent("my-app/1.0.0") .setMaxAttempts(3) .setConnectTimeout(10000) .setReadTimeout(20000); Client client = new Client(config); ``` -------------------------------- ### TypeScript Example: Count Work Records Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/01-overview.md Demonstrates how to use the DingTalk SDK in TypeScript to count work records for a user. Ensure you have the necessary SDK packages installed and a valid configuration object. ```typescript import * as dingtalk from '@alicloud/dingtalk'; const client = new dingtalk.workrecord_1_0.Client(config); const request = new dingtalk.workrecord_1_0.CountWorkRecordRequest({ userId: 'user123' }); const response = await client.countWorkRecord(request); console.log(response.body.undoCount); ``` -------------------------------- ### Number Array Initialization Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/05-types.md Example of initializing an array of numbers. ```typescript const deptIds = [123, 456, 789]; ``` -------------------------------- ### Create Get User Request in Python Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/11-quick-start.md Create a request object to get user information by specifying the user ID. ```python request = contact_1_0.GetUserRequest() request.user_id = 'your_user_id' ``` -------------------------------- ### Initialize WorkRecord Client Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/03-api-reference-workrecord.md Initializes the WorkRecord client using provided configuration. Ensure you have the necessary SDK packages installed. ```typescript import * as dingtalk from '@alicloud/dingtalk'; import { Config } from '@alicloud/openapi-client'; const client = new dingtalk.workrecord_1_0.Client(new Config({})); ``` -------------------------------- ### Nested Object Usage Example Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/05-types.md Demonstrates how to instantiate and populate a nested object structure. ```typescript const parent = new ParentType({ child: new ChildType({ field: 'value' }), childList: [ new ChildType({ field: 'value1' }), new ChildType({ field: 'value2' }) ] }); ``` -------------------------------- ### Date Format Examples Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/08-api-reference-attendance.md Demonstrates equivalent ways to represent dates for API calls, including milliseconds, YYYYMMDD integer format, and ISO strings. ```typescript // All equivalent const date1 = new Date('2026-06-15').getTime(); // milliseconds const date2 = 20260615; // YYYYMMDD format const date3 = new Date('2026-06-15T00:00:00Z').getTime(); ``` -------------------------------- ### Call Get User API in Python Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/11-quick-start.md Call the get_user_with_options API to retrieve user details and handle the response. ```python response = client.get_user_with_options(request, headers) if response.status_code == 200: print('User:', response.body) else: print('Error:', response.status_code) ``` -------------------------------- ### Instantiate a Request with Extended Types Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/05-types.md Shows how to create an instance of a request model, populating it with simple values, arrays, and nested objects. This is a practical example of using the defined request model. ```typescript const request = new AddContactHideBySceneSettingRequest({ name: 'Hide Setting', description: 'Hide certain fields', objectUserIds: ['user1', 'user2'], objectDeptIds: [100, 200], nodeListSceneConfig: new AddContactHideBySceneSettingRequestNodeListSceneConfig({ // ... nested fields }) }); ``` -------------------------------- ### DingTalk SDK Client Pattern Implementation Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/02-client-base-pattern.md This example shows the complete client pattern for calling a DingTalk API. It includes configuring the client, creating a request, setting optional headers and runtime options, and handling the API response. ```typescript import * as dingtalk from '@alicloud/dingtalk'; import { Config } from '@alicloud/openapi-client'; import * as $Util from '@alicloud/tea-util'; // 1. Configure client const config = new Config({ }); const client = new dingtalk.workrecord_1_0.Client(config); // 2. Create request const request = new dingtalk.workrecord_1_0.CountWorkRecordRequest({ userId: 'user_id_123' }); // 3. Optional: Set up headers with token const headers = new dingtalk.workrecord_1_0.CountWorkRecordHeaders({ xAcsDingtalkAccessToken: 'your_access_token' }); // 4. Optional: Configure runtime behavior const runtime = new $Util.RuntimeOptions({ maxAttempts: 3, connectTimeout: 5000 }); // 5. Call API with options const response = await client.countWorkRecordWithOptions(request, headers, runtime); // 6. Handle response if (response.statusCode === 200) { console.log(`Work records to do: ${response.body?.undoCount}`); } else { console.error(`API error: ${response.statusCode}`, response.body); } ``` -------------------------------- ### Safely Get User with 404 Handling Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/10-error-handling.md Implement a function to safely retrieve user data, returning null if the user is not found (404). Throws an error for other unexpected statuses. ```typescript async function getUserSafe(userId: string) { const request = new dingtalk.contact_1_0.GetUserRequest({ userId: userId }); const response = await client.getUser(request); if (response.statusCode === 404) { console.warn(`User ${userId} not found`); return null; } if (response.statusCode === 200) { return response.body; } throw new Error(`Unexpected status: ${response.statusCode}`); } ``` -------------------------------- ### Unit Test Example for DingTalk API Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/11-quick-start.md This snippet demonstrates how to write a unit test for interacting with the DingTalk Contact API to retrieve user information. It includes setting up the client, making a request, and asserting the response. ```typescript import { expect } from 'chai'; import * as dingtalk from '@alicloud/dingtalk'; describe('DingTalk API', () => { it('should get user successfully', async () => { const client = new dingtalk.contact_1_0.Client(new Config({})); const request = new dingtalk.contact_1_0.GetUserRequest({ userId: 'test_user_123' }); const headers = new dingtalk.contact_1_0.GetUserHeaders({ xAcsDingtalkAccessToken: process.env.DINGTALK_TOKEN! }); const response = await client.getUserWithOptions(request, headers, new (require('@alicloud/tea-util')).RuntimeOptions() ); expect(response.statusCode).to.equal(200); expect(response.body).to.not.be.undefined; }); }); ``` -------------------------------- ### Type Validation Example Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/05-types.md Illustrates the SDK's type validation by showing an incorrect type assignment (string instead of number) and the correct way to assign a number. This helps prevent runtime errors. ```typescript // Invalid: string instead of number const request = new Request({ count: 'not a number' // Type error (may not catch at runtime) }); // Correct: use proper type const request = new Request({ count: 42 }); ``` -------------------------------- ### Get Department Attendance Data Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/08-api-reference-attendance.md Retrieves attendance records for a specified department. Requires department ID, start date, and end date. Pagination is supported via cursor and pageSize. ```typescript const request = new dingtalk.attendance_1_0.GetDeptAttendanceDataRequest({ deptId: 1001, startDate: new Date('2026-01-01').getTime(), endDate: new Date('2026-01-31').getTime(), pageSize: 100 }); const response = await attendanceClient.getDeptAttendanceData(request); if (response.statusCode === 200) { response.body?.data?.forEach(userRecord => { console.log(`User ${userRecord.userId}: ${userRecord.records?.length} records`); }); } ``` -------------------------------- ### Initialize DingTalk Client in Python Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/02-client-base-pattern.md Shows how to set up configuration and instantiate a DingTalk client using Python. Requires specific imports from the DingTalk SDK. ```python from alibabacloud_dingtalk.models import Config from alibabacloud_dingtalk import contact_1_0 config = contact_1_0.Config( protocol='https', region_id='cn-hangzhou' ) client = contact_1_0.Client(config) ``` -------------------------------- ### Create Get User Request in TypeScript/JavaScript Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/11-quick-start.md Create a request object to get user information by specifying the user ID. ```typescript const request = new dingtalk.contact_1_0.GetUserRequest({ userId: 'your_user_id' }); ``` -------------------------------- ### Initialize DingTalk Client in TypeScript Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/02-client-base-pattern.md Demonstrates how to create a configuration object and initialize a DingTalk client in TypeScript. Ensure necessary imports are included. ```typescript import * as dingtalk from '@alicloud/dingtalk'; import { Config } from '@alicloud/openapi-client'; // Create configuration const config = new Config({ protocol: 'https', regionId: 'cn-hangzhou', maxAttempts: 3, backoffPolicy: 'exponential', userAgent: 'my-app/1.0.0' }); // Initialize client const client = new dingtalk.contact_1_0.Client(config); ``` -------------------------------- ### getDept Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/07-api-reference-contact.md Get department details. ```APIDOC ## GET /department ### Description Get department details. ### Method GET ### Endpoint /department ### Parameters #### Query Parameters - **deptId** (number) - Yes - Department ID ``` -------------------------------- ### Initialize OpenAPI Client with Config Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/06-configuration.md Configure the OpenAPI client with essential parameters like protocol, region, credentials, user agent, and retry settings. ```typescript import { Config } from '@alicloud/openapi-client'; const config = new Config({ protocol: 'https', regionId: 'cn-hangzhou', credentials: credentialsProvider, userAgent: 'my-app/1.0.0', maxAttempts: 3, backoffPolicy: 'exponential' }); ``` -------------------------------- ### getEmpAttribute Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/07-api-reference-contact.md Get employee attribute definition. Retrieves the schema or definition for custom employee attributes. ```APIDOC ## getEmpAttribute() ### Description Get employee attribute definition. ### Method GET ### Endpoint /v1.0/contact/attributes/emp/definitions ### Parameters #### Query Parameters - **attributeName** (string) - Optional - The name of the attribute to retrieve. ``` -------------------------------- ### getBotListInGroup() Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/04-api-reference-robot.md Get a list of bots available in a specific group conversation. Requires the group conversation ID. ```APIDOC ## getBotListInGroup() ### Description Get a list of bots available in a specific group conversation. Requires the group conversation ID. ### Method GET ### Endpoint /robot/group/listBots ### Parameters #### Query Parameters - **openConversationId** (string) - Yes - Group conversation ID ### Response #### Success Response (200) Returns an array of bot information including bot code and status. ``` -------------------------------- ### Configure SDK Proxy Settings Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/11-quick-start.md Set up HTTP and HTTPS proxy servers for SDK communication. You can also specify hosts that should bypass the proxy using 'noProxy'. ```typescript const config = new Config({ httpProxy: 'http://proxy.company.com:8080', httpsProxy: 'https://proxy.company.com:8443', noProxy: '127.0.0.1,localhost' }); const client = new dingtalk.contact_1_0.Client(config); ``` -------------------------------- ### Initialize DingTalk Client in Python Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/11-quick-start.md Initialize a DingTalk contact client with a configuration object. ```python config = contact_1_0.Config() client = contact_1_0.Client(config) ``` -------------------------------- ### Call Get User API in TypeScript/JavaScript Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/11-quick-start.md Call the getUserWithOptions API to retrieve user details and handle the response. ```typescript const response = await client.getUserWithOptions(request, headers, new (require('@alicloud/tea-util')).RuntimeOptions() ); if (response.statusCode === 200) { console.log('User:', response.body); } else { console.error('Error:', response.statusCode); } ``` -------------------------------- ### Initialize DingTalk Client Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/README.md Instantiate the DingTalk client with necessary configurations. This is the first step before making any API calls. ```typescript import * as dingtalk from '@alicloud/dingtalk'; const client = new dingtalk.contact_1_0.Client(new Config({})); ``` -------------------------------- ### Get Department Attendance Data Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/08-api-reference-attendance.md Queries attendance data for an entire department. This is useful for managers to review team attendance. ```APIDOC ## GET /attendance/1.0/departments/{deptId}/attendanceData ### Description Query department attendance data. ### Method GET ### Endpoint /attendance/1.0/departments/{deptId}/attendanceData ### Parameters #### Path Parameters - **deptId** (string) - Required - The ID of the department. #### Query Parameters - **startDate** (number) - Required - Start date in milliseconds since epoch. - **endDate** (number) - Required - End date in milliseconds since epoch. ### Response #### Success Response (200) - **attendanceRecords** (array) - Array of attendance records for the department. - **userId** (string) - User ID. - **checkInTime** (number) - Check-in timestamp. - **checkOutTime** (number) - Check-out timestamp. - **attendanceType** (string) - Type of attendance. #### Response Example ```json { "attendanceRecords": [ { "userId": "user1", "checkInTime": 1719772800000, "checkOutTime": 1719805200000, "attendanceType": "normal" } ] } ``` ``` -------------------------------- ### Get Attendance Data Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/08-api-reference-attendance.md Queries user attendance data. This allows retrieval of historical attendance records for a specified period. ```APIDOC ## GET /attendance/1.0/attendanceData ### Description Query user attendance data. ### Method GET ### Endpoint /attendance/1.0/attendanceData ### Parameters #### Query Parameters - **userId** (string) - Required - The ID of the user whose attendance data is to be queried. - **startDate** (number) - Required - Start date in milliseconds since epoch. - **endDate** (number) - Required - End date in milliseconds since epoch. ### Response #### Success Response (200) - **attendanceRecords** (array) - Array of attendance records. - **checkInTime** (number) - Check-in timestamp. - **checkOutTime** (number) - Check-out timestamp. - **attendanceType** (string) - Type of attendance (e.g., 'normal', 'leave', 'trip'). #### Response Example ```json { "attendanceRecords": [ { "checkInTime": 1719772800000, "checkOutTime": 1719805200000, "attendanceType": "normal" } ] } ``` ``` -------------------------------- ### Initialize Attendance Client Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/08-api-reference-attendance.md Instantiate the Attendance client using the provided configuration. This client is used to interact with the Attendance API. ```typescript import * as dingtalk from '@alicloud/dingtalk'; import { Config } from '@alicloud/openapi-client'; const attendanceClient = new dingtalk.attendance_1_0.Client(new Config({})); ``` -------------------------------- ### Add Authentication Headers for Get User in Python Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/11-quick-start.md Add authentication headers, including the DingTalk access token, to the request. ```python headers = contact_1_0.GetUserHeaders() headers.x_acs_dingtalk_access_token = 'your_access_token' ``` -------------------------------- ### createDept Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/07-api-reference-contact.md Create a new department. ```APIDOC ## POST /department ### Description Create a new department. ### Method POST ### Endpoint /department ### Parameters #### Request Body - **name** (string) - Yes - Department name - **parentId** (number) - No - Parent department ID - **order** (number) - No - Display order ``` -------------------------------- ### Add Authentication Headers for Get User in TypeScript/JavaScript Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/11-quick-start.md Add authentication headers, including the DingTalk access token, to the request. ```typescript const headers = new dingtalk.contact_1_0.GetUserHeaders({ xAcsDingtalkAccessToken: 'your_access_token' }); ``` -------------------------------- ### Importing Multiple DingTalk Modules Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/09-module-catalog.md Demonstrates how to import and initialize clients for multiple specific modules like Contact, Robot, and Workflow. This pattern is applicable to all available modules. ```typescript import * as dingtalk from '@alicloud/dingtalk'; // Contact module const contactClient = new dingtalk.contact_1_0.Client(config); // Robot module const robotClient = new dingtalk.robot_1_0.Client(config); // Workflow module const workflowClient = new dingtalk.workflow_1_0.Client(config); ``` -------------------------------- ### Get Department Details Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/07-api-reference-contact.md Retrieves specific details for a department using its ID. The department name is available in the response body. ```typescript const request = new dingtalk.contact_1_0.GetDeptRequest({ deptId: 1001 }); const response = await contactClient.getDept(request); if (response.statusCode === 200) { console.log(`Department: ${response.body?.name}`); } ``` -------------------------------- ### Get Attendance Settings Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/08-api-reference-attendance.md Retrieves the attendance rules and settings for a company or department. This includes work hours, break times, and holiday policies. ```APIDOC ## GET /attendance/1.0/settings ### Description Get attendance rules and settings. ### Method GET ### Endpoint /attendance/1.0/settings ### Response #### Success Response (200) - **workdayStart** (string) - Start of workday (e.g., '09:00'). - **workdayEnd** (string) - End of workday (e.g., '18:00'). - **workDays** (array) - Days of the week considered workdays (e.g., ['Monday', 'Tuesday']). #### Response Example ```json { "workdayStart": "09:00", "workdayEnd": "18:00", "workDays": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] } ``` ``` -------------------------------- ### Define Client Configuration Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/01-overview.md Defines the configuration interface for client initialization. Customize protocol, region, credentials, user agent, retry attempts, and backoff strategy. ```typescript interface Config { protocol?: string; // Default: "https" regionId?: string; // AWS region (optional) credentials?: any; // Credential object (optional) userAgent?: string; // Custom user agent maxAttempts?: number; // Retry attempts backoffPolicy?: string; // Backoff strategy } ``` -------------------------------- ### Get User Information Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/07-api-reference-contact.md Retrieves detailed information for a specific user by their userId. The response includes basic info, department assignments, and status. ```typescript const request = new dingtalk.contact_1_0.GetUserRequest({ userId: 'user_id_123' }); const response = await contactClient.getUser(request); if (response.statusCode === 200) { const user = response.body; console.log(`User: ${user?.name}`); console.log(`Email: ${user?.email}`); console.log(`Mobile: ${user?.mobile}`); } ``` -------------------------------- ### SDK File Structure Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/INDEX.md Lists the directory structure for the DingTalk SDK documentation files. ```text output/ ├── README.md (Master index - start here) ├── 01-overview.md (Architecture & concepts) ├── 02-client-base-pattern.md (Universal SDK pattern) ├── 03-api-reference-workrecord.md (Example: WorkRecord) ├── 04-api-reference-robot.md (Example: Robot/Messaging) ├── 05-types.md (Data structures) ├── 06-configuration.md (Client setup) ├── 07-api-reference-contact.md (Example: Contact Mgmt) ├── 08-api-reference-attendance.md (Example: Attendance) ├── 09-module-catalog.md (All 109 modules) ├── 10-error-handling.md (Error reference) ├── 11-quick-start.md (Getting started) └── INDEX.md (This file) ``` -------------------------------- ### Error Handling Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/02-client-base-pattern.md Explains how API errors are communicated through HTTP status codes and provides a switch-case example for handling common error responses. ```APIDOC ## Error Handling ### Description API errors are indicated by standard HTTP status codes in the response. The `response.statusCode` property can be used to determine the outcome of an operation and handle specific error conditions. ### Handling Common Status Codes | Status Code | Description | |---|---| | 200 | Success | | 400 | Bad request | | 401 | Unauthorized: check access token | | 403 | Forbidden: insufficient permissions | | 404 | Not found | | 500 | Server error | ### Usage Example ```typescript const response = await client.countWorkRecord(request); switch (response.statusCode) { case 200: console.log('Success', response.body); break; case 400: console.error('Bad request:', response.body); break; // ... other cases ... default: console.error('Unknown status:', response.statusCode); } ``` ``` -------------------------------- ### Configure Read Timeout for Long-Running Operations Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/06-configuration.md Adjust the read timeout specifically for long-running operations. This example sets a 5-minute read timeout. ```typescript const runtime = new $Util.RuntimeOptions({ readTimeout: 300000 // 5 minutes for slow operations }); const response = await client.methodWithOptions(request, headers, runtime); ``` -------------------------------- ### Type Casting Best Practice Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/05-types.md Demonstrates the correct way to instantiate objects using the SDK's constructor for type safety, avoiding direct casting. ```typescript // Correct - use constructor const request = new RequestType(data); // Avoid - raw object without type const request = data as RequestType; ``` -------------------------------- ### Configure Client with Proxy Settings Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/06-configuration.md Set up HTTP and HTTPS proxies, and specify hosts to bypass proxy for the DingTalk client. ```typescript const config = new Config({ httpProxy: 'http://proxy.company.com:8080', httpsProxy: 'https://proxy.company.com:8443', noProxy: '127.0.0.1,localhost,.company.com' }); const client = new dingtalk.contact_1_0.Client(config); ``` -------------------------------- ### createUser() Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/07-api-reference-contact.md Create a new user in the organization with specified details including name, mobile, and optional department assignments and roles. ```APIDOC ## createUser() ### Description Create a new user in the organization. ### Signature ```typescript async createUser(request: CreateUserRequest): Promise ``` ### Request: CreateUserRequest | Field | Type | Required | Description | |-------|------|----------|-------------| | name | string | Yes | User's full name | | mobile | string | Yes | Phone number | | email | string | No | Email address | | deptIdList | number[] | No | List of department IDs | | roles | UserRole[] | No | Roles to assign | | customAttributes | any | No | Custom fields | ### Example ```typescript const request = new dingtalk.contact_1_0.CreateUserRequest({ name: 'John Doe', mobile: '+86 138 0000 0000', email: 'john.doe@company.com', deptIdList: [1001, 1002] }); const response = await contactClient.createUser(request); if (response.statusCode === 200) { const newUserId = response.body?.userId; console.log(`User created: ${newUserId}`); } ``` ``` -------------------------------- ### Get Attendance Settings Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/08-api-reference-attendance.md Retrieves the organization's current attendance settings and rules. This includes work days, work hours, and thresholds for late arrivals and early departures. ```typescript const response = await attendanceClient.getAttendanceSettings(); if (response.statusCode === 200) { const settings = response.body; console.log(`Work days: ${settings?.workDays}`); console.log(`Work hours: ${settings?.workHours}`); console.log(`Late threshold: ${settings?.lateThreshold} minutes`); } ``` -------------------------------- ### Initialize Contact Client Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/07-api-reference-contact.md Initializes the DingTalk contact client using provided configuration. Ensure necessary SDK packages are imported. ```typescript import * as dingtalk from '@alicloud/dingtalk'; import { Config } from '@alicloud/openapi-client'; const contactClient = new dingtalk.contact_1_0.Client(new Config({})); ``` -------------------------------- ### Get Access Token via API Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/11-quick-start.md Obtain an access token by making a POST request to the DingTalk OAuth2 token endpoint. You will need your application's ClientId and ClientSecret. ```bash curl -X POST https://api.dingtalk.com/v1.0/oauth2/token \ -H "Content-Type: application/json" \ -d '{ "clientId": "your_client_id", "clientSecret": "your_client_secret" }' ``` -------------------------------- ### Basic TypeScript/JavaScript Client Configuration Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/06-configuration.md Initialize a DingTalk client with a basic configuration object. This sets up the client for default operation. ```typescript import * as dingtalk from '@alicloud/dingtalk'; import { Config } from '@alicloud/openapi-client'; const config = new Config({}); const client = new dingtalk.contact_1_0.Client(config); ``` -------------------------------- ### Discover Available Types in a Module Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/05-types.md Demonstrates how to import the DingTalk SDK and explore the available type classes within a specific module, such as 'robot_1_0'. This is useful for understanding the SDK's structure. ```typescript import * as dingtalk from '@alicloud/dingtalk'; // View types in module const module = dingtalk.robot_1_0; // Access type classes like: // - module.PrivateChatSendRequest // - module.PrivateChatSendResponse // - module.PrivateChatSendResponseBody ``` -------------------------------- ### RuntimeOptions Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/02-client-base-pattern.md Explains how to configure `RuntimeOptions` to control the behavior of API requests, such as retry attempts, timeouts, and proxy settings. ```APIDOC ## Runtime Options ### Description Control request behavior and network settings using the `RuntimeOptions` class. This allows customization of retries, timeouts, proxy configurations, and SSL verification. ### Properties - **maxAttempts** (number) - Optional - Maximum number of retry attempts (default: 1). - **connectTimeout** (number) - Optional - Connection timeout in milliseconds (default: 10000). - **readTimeout** (number) - Optional - Read timeout in milliseconds (default: 20000). - **ignoreSSL** (boolean) - Optional - Ignore SSL verification (default: false). - **httpProxy** (string) - Optional - HTTP proxy URL. - **httpsProxy** (string) - Optional - HTTPS proxy URL. - **noProxy** (string) - Optional - Hosts to bypass proxy. - **maxIdleConns** (number) - Optional - Maximum idle connections. - **socks5Proxy** (string) - Optional - SOCKS5 proxy URL. - **socks5NetWork** (string) - Optional - SOCKS5 network type (e.g., 'TCP'). ### Usage ```typescript import * as $Util from '@alicloud/tea-util'; const runtime = new $Util.RuntimeOptions({ maxAttempts: 3, connectTimeout: 5000 }); const response = await client.methodWithOptions(request, headers, runtime); ``` ``` -------------------------------- ### Accessing Response Data in TypeScript Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/02-client-base-pattern.md Provides examples of how to check the response status code, access the response body, and retrieve specific headers from a DingTalk SDK response object. ```typescript const response = await client.countWorkRecord(request); // Check success if (response.statusCode === 200) { const undoCount = response.body?.undoCount; console.log(`Undo work records: ${undoCount}`); } // Access headers const etag = response.headers?.['etag']; ``` -------------------------------- ### Import DingTalk SDK in Python Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/11-quick-start.md Import the necessary DingTalk SDK models and modules for Python. ```python from alibabacloud_dingtalk.models import Config from alibabacloud_dingtalk import contact_1_0 ``` -------------------------------- ### Submit Leave Request Source: https://github.com/aliyun/dingtalk-sdk/blob/master/_autodocs/08-api-reference-attendance.md Submits a leave request for a user. Requires user ID, start and end dates, and leave type. Optional fields include reason and duration. ```typescript const request = new dingtalk.attendance_1_0.SubmitLeaveRequestRequest({ userId: 'user_id_123', startDate: new Date('2026-01-01').getTime(), endDate: new Date('2026-01-31').getTime(), leaveType: 'annual', reason: 'Vacation', duration: 5 }); const response = await attendanceClient.submitLeaveRequest(request); ```