Implementation steps
1. Install dependencies
Before you start, you need to install the necessary Python libraries. Commonly used libraries includerequests
anddingtalk-sdk
。
pip install requests dingtalk-sdk
2. Obtain DingTalk Developer Permissions
Before using DingTalk API, you need to create an application on the DingTalk developer platform and obtainAppKey
andAppSecret
。
- Log inDingTalk Developer Platform。
- Create an in-house or third-party application.
- Get the application
AppKey
andAppSecret
。 - Set the permissions of the application (for example: message sending, address book management, approval flow, etc.).
3. Obtain Access Token
DingTalk API calls requireAccess Token
, can be passedAppKey
andAppSecret
Get it.
import requests def get_access_token(app_key, app_secret): url = "/gettoken" params = { "appkey": app_key, "appsecret": app_secret } response = (url, params=params) return ().get("access_token") # Replace with your AppKey and AppSecretapp_key = "your_app_key" app_secret = "your_app_secret" access_token = get_access_token(app_key, app_secret) print("Access Token:", access_token)
4. Send a message
DingTalk supports multiple message types (such as text, links, Markdown, etc.). Here is an example of sending text messages:
def send_text_message(access_token, agent_id, userid_list, content): url = "/topapi/message/corpconversation/asyncsend_v2" headers = { "Content-Type": "application/json" } data = { "agent_id": agent_id, # AgentId of the application "userid_list": userid_list, # List of user IDs that receive messages, separated by commas "msg": { "msgtype": "text", "text": { "content": content } } } params = { "access_token": access_token } response = (url, headers=headers, json=data, params=params) return () # Replace with your AgentId and User ID listagent_id = "your_agent_id" userid_list = "user1,user2" # List of user IDs that receive messages, separated by commascontent = "This is a test message" response = send_text_message(access_token, agent_id, userid_list, content) print("Message Sent:", response)
5. Get the department list
You can obtain a list of internal departments within the company through DingTalk API.
def get_department_list(access_token): url = "/department/list" params = { "access_token": access_token } response = (url, params=params) return () department_list = get_department_list(access_token) print("Department List:", department_list)
6. Get department user details
Get user details under this department through department ID.
def get_department_user_details(access_token, department_id): url = "/user/listbypage" params = { "access_token": access_token, "department_id": department_id, "offset": 0, "size": 100 } response = (url, params=params) return () # Replace with your department IDdepartment_id = "your_department_id" user_details = get_department_user_details(access_token, department_id) print("User Details:", user_details)
7. Process approval process
DingTalk's approval process can be triggered and queried through the API. Here is an example that triggers the approval process:
def trigger_approval_process(access_token, process_code, originator_user_id, dept_id, form_component_values): url = "/topapi/processinstance/create" headers = { "Content-Type": "application/json" } data = { "process_code": process_code, # Unique identification of the approval template "originator_user_id": originator_user_id, # User ID that initiated the approval "dept_id": dept_id, # Department ID to initiate the approval "form_component_values": form_component_values # Approval form content } params = { "access_token": access_token } response = (url, headers=headers, json=data, params=params) return () # Replace with your approval template informationprocess_code = "your_process_code" originator_user_id = "your_user_id" dept_id = "your_dept_id" form_component_values = [ {"name": "field1", "value": "value1"}, {"name": "field2", "value": "value2"} ] response = trigger_approval_process(access_token, process_code, originator_user_id, dept_id, form_component_values) print("Approval Process Triggered:", response)
8. Error handling
In actual use, you may encounter problems such as network problems or API call frequency limitations. It is recommended to add an error handling mechanism to the code.
import time def safe_send_message(access_token, agent_id, userid_list, content, retries=3): for i in range(retries): try: response = send_text_message(access_token, agent_id, userid_list, content) if ("errcode") == 0: return response else: print(f"Error: {('errmsg')}") except Exception as e: print(f"Exception: {e}") (2) # Wait for 2 seconds before trying again return None response = safe_send_message(access_token, agent_id, userid_list, content) if response: print("Message Sent Successfully") else: print("Failed to Send Message")
Prerequisites
-
DingTalk Developer Account:
- You need to have a DingTalk developer account and create an application.
- Get the application
AppKey
andAppSecret
。
-
Application permissions:
- Make sure that the application has enabled relevant permissions (such as message sending, address book management, approval flow, etc.).
-
Python environment:
- Make sure that Python 3.6 and above is installed.
- Install the necessary dependency libraries (such as
requests
anddingtalk-sdk
)。
Dependencies
Here are the dependencies required to implement DingTalk automation:
-
Python Library:
-
requests
: Used to send HTTP requests. -
dingtalk-sdk
: Python SDK (optional) provided by DingTalk.
-
-
DingTalk API Permissions:
- Message sending permission.
- Address book management permissions.
- Approval flow permissions (if you need to handle the approval process).
-
Network environment:
- Ensure that the server or local environment has access to the DingTalk API (
)。
- Ensure that the server or local environment has access to the DingTalk API (
Things to note
1. Management of Access Tokens
-
Validity period: DingTalk
Access Token
Validity period is7200 seconds (2 hours), need to be re-acquisitioned after expiration. -
Cache mechanism: It is recommended to
Access Token
Cache (such as stored in memory or Redis) to avoid frequent calls to obtain interfaces. -
Refresh strategy: Check before each API call
Access Token
Whether it expires, and re-acquire if it expires.
import time # Cache Access Tokenaccess_token_cache = { "token": None, "expires_at": 0 } def get_access_token_with_cache(app_key, app_secret): now = () if access_token_cache["token"] and access_token_cache["expires_at"] > now: return access_token_cache["token"] # Re-acquire Access Token access_token = get_access_token(app_key, app_secret) access_token_cache["token"] = access_token access_token_cache["expires_at"] = now + 7200 # Validity period 7200 seconds return access_token
2. API call frequency limit
- Frequency Limitation: DingTalk API has restrictions on call frequency, and the specific restrictions vary from interface to interface. For example, the default limit for the message sending interface is20 times/second。
-
Error handling: If the frequency limit is triggered, DingTalk will return the error code.
43004
, it is recommended to add retry mechanism and delay in the code.
import time def safe_send_message(access_token, agent_id, userid_list, content, retries=3): for i in range(retries): try: response = send_text_message(access_token, agent_id, userid_list, content) if ("errcode") == 0: return response elif ("errcode") == 43004: # Frequency Limitation print("Rate limit exceeded, retrying...") (2) # Wait for 2 seconds and try again else: print(f"Error: {('errmsg')}") except Exception as e: print(f"Exception: {e}") (1) # Wait 1 second before each retry return None
3. Permissions and scope of message sending
-
User permissions: Ensure the message recipient (
userid_list
) within the visible range of the application. - Message Type: DingTalk supports multiple message types (such as text, links, Markdown, etc.), and you need to choose the appropriate type according to your needs.
- Message length: The content length of the text message cannot exceed5000 characters, otherwise it will be truncated.
4. Configuration of approval process
-
Approval template: Before triggering the approval process, you need to configure the approval template in the DingTalk background and obtain
process_code
。 - Form fields: The field name and value of the approval form must be consistent with the fields in the template, otherwise an error will be triggered.
-
Approval authority: Ensure that the user who initiated the approval (
originator_user_id
) Have the authority to initiate the approval.
5. Data security
-
Sensitive information protection: Avoid hard-code sensitive information in code (such as
AppKey
、AppSecret
), it is recommended to use environment variables or configuration files. - HTTPS encryption: DingTalk API only supports the HTTPS protocol, ensuring that the code uses HTTPS to call the API.
import os # Read sensitive information from environment variablesapp_key = ("DINGTALK_APP_KEY") app_secret = ("DINGTALK_APP_SECRET")
6. Logging
- Log output: It is recommended to add logging to the code to facilitate troubleshooting and monitoring the operation status.
- Error log: Record error messages (such as error codes, error messages) when API calls fail.
import logging (level=, format="%(asctime)s - %(levelname)s - %(message)s") def send_text_message_with_logging(access_token, agent_id, userid_list, content): try: response = send_text_message(access_token, agent_id, userid_list, content) if ("errcode") == 0: ("Message sent successfully") else: (f"Failed to send message: {('errmsg')}") return response except Exception as e: (f"Exception occurred: {e}") return None
7. Separation of test environment and production environment
- Test environment: During the development stage, it is recommended to use DingTalk's test environment for debugging to avoid affecting production data.
- Environment Switching: Distinguish between test environment and production environment by configuration files or environment variables.
# Configuration file exampleconfig = { "test": { "app_key": "test_app_key", "app_secret": "test_app_secret", "agent_id": "test_agent_id" }, "production": { "app_key": "prod_app_key", "app_secret": "prod_app_secret", "agent_id": "prod_agent_id" } } # Select configuration according to the environmentenv = "test" # or "production"app_key = config[env]["app_key"] app_secret = config[env]["app_secret"] agent_id = config[env]["agent_id"]
8. Version compatibility of DingTalk API
- API version: DingTalk API will be updated continuously, it is recommended to check it regularlyDingTalk Open Platform Documentation, make sure the API version used is up to date.
- Abandoned interface: If you use the old version of the API, you need to pay attention to whether it has been abandoned and migrate to the new version of the API in time.
9. Asynchronous calls and callbacks
- Asynchronous call: Some DingTalk APIs support asynchronous calls (such as message sending) and need to process callback notifications.
- Callback configuration: Configure the callback address on the DingTalk developer platform and implement the callback interface to receive asynchronous results.
10. Performance optimization
- Batch operation: If you need to operate on a large number of users or departments, it is recommended to use a batch interface to reduce the number of API calls.
- Concurrent control: In high concurrency scenarios, the API call frequency needs to be controlled to avoid triggering frequency limits.
Summarize
Through the above steps and precautions, you can use Python to realize DingTalk automation, including message sending, department management, approval process triggering and other functions. DingTalk API is powerful and supports automated operations in multiple scenarios. More API interfaces can be further explored and used according to specific needs.
The above is the detailed content of the complete guide for Python to implement DingTalk automation. For more information about Python DingTalk automation, please follow my other related articles!