Text anti-spam

更新时间:
复制 MD 格式

Use AI Guardrails SDK for Python to detect spam content in text, including pornographic and terrorist material.

Text anti-spam uses synchronous moderation only. You are charged per text entry moderated, not per request — a single request can include multiple text entries. For pricing details, see Billing overview.

Prerequisites

Before you begin, make sure you have:

  • Python dependencies installed using the Python version specified in the Installation guide — using a different Python version causes operation calls to fail

  • The Extension.Uploader utility class downloaded and imported into your project

  • Your AccessKey ID and AccessKey secret stored as environment variables:

    Important

    Never hardcode your AccessKey credentials directly in your code. Use environment variables or a secrets manager to keep credentials out of source control.

    export ALIBABA_CLOUD_ACCESS_KEY_ID='<your-access-key-id>'
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET='<your-access-key-secret>'

How it works

  1. Initialize an AcsClient with your credentials and target region. Reuse the client across requests to improve performance and avoid repeated connections.

  2. Create a TextScanRequest object for each request. Request objects cannot be reused.

  3. Set the scenes parameter to antispam and submit one or more text entries in the tasks array.

  4. Parse the response: check suggestion in each result to decide the next action.

For the full list of request and response parameters, see /green/text/scan.

Submit a text moderation task

Use TextScanRequest to submit text entries for anti-spam moderation.

Supported regions

Region IDLocation
cn-shanghaiChina (Shanghai)
cn-beijingChina (Beijing)
cn-shenzhenChina (Shenzhen)
ap-southeast-1Singapore

Sample code

# coding=utf-8
from aliyunsdkcore import client
from aliyunsdkcore.profile import region_provider
from aliyunsdkgreen.request.v20180509 import TextScanRequest
import json, uuid, datetime, os

# Reuse the client across requests to improve performance.
# Obtain credentials from environment variables — never hardcode them.
clt = client.AcsClient(
    os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
    os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    "cn-shanghai"
)
region_provider.modify_point('Green', 'cn-shanghai', 'green.cn-shanghai.aliyuncs.com')

# Create a new request object for each request — request objects cannot be reused.
request = TextScanRequest.TextScanRequest()
request.set_accept_format('JSON')

task1 = {
    "dataId": str(uuid.uuid1()),          # Unique ID for this text entry
    "content": "textContentToBeModerated",
    "time": datetime.datetime.now().microsecond
}

# Set scenes to antispam and include one or more tasks.
request.set_content(bytearray(
    json.dumps({"tasks": [task1], "scenes": ["antispam"]}), "utf-8"
))

response = clt.do_action_with_exception(request)
result = json.loads(response)

if result["code"] == 200:
    for task_result in result["data"]:
        if task_result["code"] == 200:
            for scene_result in task_result["results"]:
                scene = scene_result["scene"]
                suggestion = scene_result["suggestion"]
                # Take action based on suggestion: pass, review, or block.

Understanding the response

The suggestion field in each result tells you the recommended action:

ValueMeaning
passContent is safe — no action needed
reviewContent needs human review
blockContent violates policy — reject or remove it

Use custom terms

Add custom terms — such as competitor brand names — to a text library. When moderated text contains a custom term, the response returns suggestion: block.

Add terms in the AI Guardrails console or by calling an API operation.

Provide feedback on moderation results

If a result is incorrect, use TextFeedbackRequest to correct it. The system updates its text library based on your feedback and applies the correction to future submissions that match the same text pattern.

Supported regions: cn-shanghai, cn-beijing, cn-shenzhen, ap-southeast-1

Sample code

# coding=utf-8
from aliyunsdkcore import client
from aliyunsdkcore.profile import region_provider
from aliyunsdkgreen.request.v20180509 import TextFeedbackRequest
import json, os

clt = client.AcsClient(
    os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
    os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    "cn-shanghai"
)
region_provider.modify_point('Green', 'cn-shanghai', 'green.cn-shanghai.aliyuncs.com')

request = TextFeedbackRequest.TextFeedbackRequest()
request.set_accept_format('JSON')

request.set_content(json.dumps({
    "dataId": "<data-id>",    # ID of the moderated text entry
    "taskId": "<task-id>",    # ID returned in the moderation response
    "content": "<text-content>",
    "label": "spam",
    "note": "<remarks>"
}))

try:
    response = clt.do_action_with_exception(request)
    result = json.loads(response)
    if result["code"] == 200:
        print("Feedback submitted successfully.")
except Exception as err:
    print(err)

Required fields

FieldDescription
dataIdID of the moderated text entry
taskIdTask ID returned in the original moderation response
contentThe text content that was moderated
labelCorrection label, for example spam
noteRemarks explaining the correction

What's next