Updated on 2025-07-02 GMT+08:00

Text Moderation (V3)

  1. This section describes how to use the Text Moderation SDK by AK/SK authentication.

    Change the value of Text in TextDetectionDataReq in the sample code to the text to be detected. Then run the code.

    const core = require('@huaweicloud/huaweicloud-sdk-core');
    const moderation = require("@huaweicloud/huaweicloud-sdk-moderation");
    // Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK and store them in the configuration file or environment variables.
    // In this example, the AK and SK are stored in environment variables for identity authentication. Before running this example, configure environment variables HUAWEICLOUD_SDK_AK, HUAWEICLOUD_SDK_SK, and HUAWEICLOUD_SDK_PROJECT_ID.
    const ak = process.env.HUAWEICLOUD_SDK_AK;
    const sk = process.env.HUAWEICLOUD_SDK_SK;
    const projectId = process.env.HUAWEICLOUD_SDK_PROJECT_ID;
    
    const endpoint = "https://moderation.ap-southeast-3.myhuaweicloud.com"; //Replace ap-southeast-3 with the region where the service is located.
    const credentials = new core.BasicCredentials()
                         .withAk(ak)
                         .withSk(sk) 
                         .withProjectId(project_id)
    
    			
    const client = moderation.v3.ModerationClient.newBuilder()
                                .withCredential(credentials)
                                .withEndpoint(endpoint)
                                .build();
    const request = new moderation.v3.RunTextModerationRequest();
    const body = new moderation.v3.TextDetectionReq();
    const databody = new moderation.v3.TextDetectionDataReq();
    databody.withText("test");
    body.withData(databody);
    body.withEventType("comment");
    request.withBody(body);
    const result = client.runTextModeration(request);
    result.then(result => {
        console.log("JSON.stringify(result)::" + JSON.stringify(result));
    }).catch(ex => {
        console.log("exception:" + JSON.stringify(ex));
    });
  2. The code is successfully executed if the text moderation result is displayed on the console.
    JSON.stringify(result)::{"request_id": "d81702cfd3599e103030c3d52d6f955f", "result": {"suggestion": "pass", "label": "normal", "details": []}}