Tencent Cloud IM Server SDK for Java

repository·dev·Indexed 40 days ago

https://github.com/doocs/qcloud-im-server-sdk-java

A Java SDK (version 0.4.20) providing a programmatic interface to interact with Tencent Cloud Instant Messaging (IM) services. It enables server-side account management, including importing, deleting, and checking account status, as well as content moderation through local and cloud audit keyword libraries. Requires JDK 1.8 or later.

Tokens
35K
Snippets
104
Records
112
Agent score
49%

What's inside Tencent Cloud IM Server SDK for Java

  1. Overview of qcloud-im-server-sdk-java features

    dev

    The qcloud-im-server-sdk-java provides a comprehensive set of server-side capabilities for managing Tencent Cloud IM (Instant Messaging) services. Key functional areas include:

    • Account Management: Import, delete, and query user accounts.
    • Private Chat Messages: Send, query, recall, and manage read receipts for single-chat messages.
    • Global Push & Attributes: Set and retrieve application properties, user properties, and user tags.
    • Profile Management: Set and fetch user profile information.
    • Relationship Management: Add, import, update, delete, and verify friend relationships.
    • Recent Contacts: Fetch and delete chat sessions/recent contacts.
    • Group Management: Manage groups, group members, and group message notifications.
    • Global Mute Management: Set and query global mute status.
    • Bot Management: Create, delete, and fetch bots.
    • Content Moderation: Perform local and cloud-based content auditing.
    • Official Account Management: Create, destroy, and modify official accounts.
  2. Understand Cloudflare Workers deployment workflows

    dev

    The project uses GitHub Actions for two independent deployment workflows:

    • Cloudflare Workers Deployment: Triggered by pushes to the main branch via .github/workflows/cloudflare.yml. It builds the VitePress documentation site and deploys it to Cloudflare Workers.
    • GitHub Pages Deployment: Managed via .github/workflows/docs.yml.

    These two workflows run independently and do not interfere with each other.

  3. Manage blacklists

    dev

    Manage user blacklists including adding, deleting, checking, and retrieving blacklisted users.

    Blacklist Rules:

    • If User A blacklists User B, any existing mutual friendship is dissolved.
    • If User A and User B are both on each other's blacklists, they cannot initiate sessions.
    • If User A blacklists User B, but User B has NOT blacklisted User A: User A can send messages to User B, but User B cannot send messages to User A.
    • If a blacklist relationship exists, users cannot send friend requests to each other.
    // Add to Blacklist
    List<String> toAccount = Collections.singletonList("test2");
    BlackListAddRequest addRequest = BlackListAddRequest.builder()
            .fromAccount("test1")
            .toAccount(toAccount)
            .build();
    client.sns.blackListAdd(addRequest);
    
    // Delete from Blacklist
    BlackListDeleteRequest deleteRequest = BlackListDeleteRequest.builder()
            .fromAccount("test1")
            .toAccount(toAccount)
            .build();
    client.sns.blackListDelete(deleteRequest);
    
    // Paginate Blacklist
    BlackListGetRequest getRequest = BlackListGetRequest.builder()
            .fromAccount("test1")
            .startIndex(0)
            .maxLimited(10)
            .lastSequence(0)
            .build();
    client.sns.blackListGet(getRequest);
    
    // Check Blacklist
    BlackListCheckRequest checkRequest = BlackListCheckRequest.builder()
            .fromAccount("test1")
            .toAccount(toAccount)
            .checkType(BlackCheckResultType.BOTH)
            .build();
    client.sns.blackListCheck(checkRequest);
  4. Cloudflare Worker features for documentation hosting

    dev

    The deployed Cloudflare Worker provides the following capabilities for the documentation site:

    • Serves the static documentation site.
    • Supports clean URLs (allows accessing pages without the .html extension).
    • Automatically handles directory indexing (resolves to index.html).
  5. Manage group topics in Community groups

    dev

    App administrators can manage topics (discussions) within groups.

    Note on Scope: These APIs are only applicable to Community (社群) groups that support the topic feature. They are not supported for Private, Public, ChatRoom, or AVChatRoom groups.

    Available Operations:

    • Create a topic: createGroupTopic
    • Get topic details: getGroupTopic
    • Modify topic details: modifyGroupTopic
    • Import topic data: importGroupTopic (Used for migrating data from other IM systems; does not trigger callbacks or notifications)
    • Dissolve a topic: destroyGroupTopic
    // Create a topic
    CreateGroupTopicRequest createReq = new CreateGroupTopicRequest();
    createReq.setGroupId("MyFirstGroup");
    createReq.setTopicName("test");
    createReq.setFaceUrl("");
    CreateGroupTopicResult createRes = client.group.createGroupTopic(createReq);
    
    // Get topic details
    GetGroupTopicRequest getReq = new GetGroupTopicRequest();
    getReq.setGroupId("MyFirstGroup");
    getReq.setFromAccount("1400187352");
    GetGroupTopicResult getRes = client.group.getGroupTopic(getReq);
    
    // Modify topic
    ModifyGroupTopicRequest modifyReq = new ModifyGroupTopicRequest();
    modifyReq.setGroupId("MyFirstGroup");
    modifyReq.setTopicName("test");
    modifyReq.setFaceUrl("");
    ModifyGroupTopicResult modifyRes = client.group.modifyGroupTopic(modifyReq);
    
    // Import topic (Migration mode)
    ImportGroupTopicRequest importReq = new ImportGroupTopicRequest();
    importReq.setGroupId("MyFirstGroup");
    importReq.setTopicName("test");
    importReq.setFromAccount("123");
    ImportGroupTopicResult importRes = client.group.importGroupTopic(importReq);
    
    // Dissolve topic
    DestroyGroupTopicRequest destroyReq = new DestroyGroupTopicRequest();
    destroyReq.setGroupId("MyFirstGroup");
    DestroyGroupTopicResult destroyRes = client.group.destroyGroupTopic(destroyReq);
  6. Create a robot account

    dev

    Use the createRobot method to create a special robot account. Robot userIds must start with the prefix @RBT#. When creating a robot, you can optionally specify a nickname, avatar URL, and signature.

    Constraints:

    • Attempting to create a robot with an existing userId will not create a duplicate; it will simply result in one robot.
    • Each IM account is limited to a maximum of 20 robot accounts.
    CreateRobotRequest request = new CreateRobotRequest();
    request.setNick("bingo");
    request.setFaceUrl("https://avatars.githubusercontent.com/u/2784452?v=4");
    request.setSelfSignature("hah");
    request.setUserId("@RBT#1233232");
    
    CreateRobotResult result = client.robot.createRobot(request);
  7. Initialize an ImClient instance

    dev

    To use the Tencent Cloud IM Server REST APIs, you must first obtain an ImClient instance using your appId, userId, and key. You can initialize it using default settings, specify a custom domain, or provide a ClientConfiguration for fine-grained control over HTTP and signature settings.

    // sdk appId
    long appId = 1400554812;
    
    // admin userId
    String userId = "test";
    
    // application key
    String key = "60c6c5925f3ae52c7325ac5a8ec78e44c056d1dd84d54e12ffa39911267a2a70";
    
    // create a default ImClient instance
    ImClient client = ImClient.getInstance(appId, userId, key);
    
    // create a default ImClient instance with custom domain
    ImClient client = ImClient.getInstance(appId, userId, key, Domain.SINGAPORE);
    
    // create a custom ImClient instance
    ClientConfiguration config = new ClientConfiguration();
    config.setExpireTime(7 * 24 * 60 * 60L);
    config.setAutoRenewSig(false);
    ImClient client = ImClient.getInstance(appId, userId, key, config);
  8. Manage local audit keywords

    dev

    When local audit is enabled, you can manage the local sensitive word library using the client.audit methods. This includes adding, deleting, and retrieving keywords.

    Add local keywords

    Use AddLocalAuditKeywordsRequest to add new words. You can specify the filterType (e.g., AuditFilterType.REPLACE) and wordType (e.g., AuditWordType.SENSITIVE_WORDS).

    Delete local keywords

    Use DeleteLocalAuditKeywordsRequest to remove words. You must provide the id of the word to be deleted.

    Get local keywords

    Use GetLocalAuditKeywordsRequest to query the local library. You can filter by keyword and filterType, and use limit and offset for pagination.

    // Add local keywords
    LocalAuditWord word = new LocalAuditWord();
    word.setFilterType(AuditFilterType.REPLACE);
    word.setWordType(AuditWordType.SENSITIVE_WORDS);
    word.setKeyword("caonima");
    word.setReplacedContent("****");
    AddLocalAuditKeywordsRequest request = AddLocalAuditKeywordsRequest.builder()
            .sdkAppId(1400594307)
            .localAuditWords(Collections.singletonList(word)).build();
    
    AddLocalAuditKeywordsResult result = client.audit.addLocalAuditKeywords(request);
    
    // Delete local keywords
    DeleteLocalAuditKeywordsRequest deleteRequest = new DeleteLocalAuditKeywordsRequest();
    deleteRequest.setSdkAppId(1400594307);
    LocalAuditWord deleteWord = new LocalAuditWord();
    deleteWord.setId(1L);
    deleteWord.setReplacedContent("****");
    deleteWord.setKeyword("caonima");
    deleteWord.setWordType(AuditWordType.SENSITIVE_WORDS);
    deleteWord.setFilterType(AuditFilterType.REPLACE);
    deleteRequest.setLocalAuditWords(Collections.singletonList(deleteWord));
    
    DeleteLocalAuditKeywordsResult deleteResult = client.audit.deleteLocalAuditKeywords(deleteRequest);
    
    // Get local keywords
    GetLocalAuditKeywordsRequest getRequest = GetLocalAuditKeywordsRequest.builder()
            .keyword("caonima")
            .filterType(AuditFilterType.REPLACE)
            .limit(1)
            .offset(0)
            .sdkAppId(1400594307).build();
    
    GetLocalAuditKeywordsResult getResult = client.audit.getLocalAuditKeywords(getRequest);
  9. Manage cloud audit keyword libraries

    dev

    When cloud audit is enabled, you can manage cloud-based keyword libraries and sensitive words. This involves managing library IDs and the keywords within them.

    Get cloud library list

    Use GetCloudAuditKeyWordsIdsRequest to retrieve a list of available library IDs (libId).

    Get keywords in a library

    Use GetCloudAuditKeyWordsRequest with a specific libId to retrieve the keywords stored in that library.

    Add cloud keywords

    Use AddCloudAuditKeywordsRequest to add keywords to a specific library (libId). You can specify a label (e.g., ContentModerationLabel.COMPOSITE) for the keyword.

    Delete cloud keywords

    Use DeleteCloudAuditKeywordsRequest to remove specific keywords from a library by providing a list of keyword strings.

    // Get cloud library list
    GetCloudAuditKeyWordsIdsRequest listRequest = GetCloudAuditKeyWordsIdsRequest.builder()
            .limit(1)
            .offset(0)
            .sdkAppId(1400594307)
            .build();
    
    GetCloudAuditKeywordsIdsResult listResult = client.audit.getCloudAuditKeywordsIds(listRequest);
    
    // Get keywords in a library
    GetCloudAuditKeyWordsRequest getKeywordsRequest = GetCloudAuditKeyWordsRequest.builder()
            .libId("fd")
            .limit(1)
            .offset(0)
            .sdkAppId(1400594307)
            .build();
    
    GetCloudAuditKeywordsResult getKeywordsResult = client.audit.getCloudAuditKeywords(getKeywordsRequest);
    
    // Add cloud keywords
    UserKeyword userKeyword = new UserKeyword();
    userKeyword.setContent("caonima");
    userKeyword.setLabel(ContentModerationLabel.COMPOSITE);
    
    AddCloudAuditKeywordsRequest addRequest = AddCloudAuditKeywordsRequest.builder()
            .sdkAppId(1400594307)
            .libId("fd")
            .userKeywords(Collections.singletonList(userKeyword))
            .build();
    
    AddCloudAuditKeywordsResult addResult = client.audit.addCloudAuditKeywords(addRequest);
    
    // Delete cloud keywords
    DeleteCloudAuditKeywordsRequest deleteRequest = DeleteCloudAuditKeywordsRequest.builder()
            .sdkAppId(1400594307)
            .libId("fd")
            .keywords(Arrays.asList("caonima", "wtf"))
            .build();
    
    DeleteCloudAuditKeywordsResult deleteResult = client.audit.deleteCloudAuditKeywords(deleteRequest);
  10. Manage Official Accounts

    dev

    App administrators can use the officialAccount interface to perform lifecycle and configuration management for Official Accounts. This includes creating, destroying, and modifying account details.

    // Create an Official Account
    CreateOfficialAccountRequest createReq = new CreateOfficialAccountRequest();
    createReq.setOwnerAccount("test");
    createReq.setName("test_official_account");
    CreateOfficialAccountResult createRes = client.officialAccount.createOfficialAccount(createReq);
    
    // Destroy an Official Account
    DestroyOfficialAccountRequest destroyReq = new DestroyOfficialAccountRequest();
    destroyReq.setOfficialAccount("test_official_account_user_id");
    DestroyOfficialAccountResult destroyRes = client.officialAccount.destroyOfficialAccount(destroyReq);
    
    // Modify Official Account info (name, avatar, etc.)
    ModifyOfficialAccountBaseInfoRequest modifyReq = new ModifyOfficialAccountBaseInfoRequest();
    modifyReq.setOfficialAccount("test_official_account_user_id");
    modifyReq.setName("test_official_account2");
    ModifyOfficialAccountBaseInfoResult modifyRes = client.officialAccount.modifyOfficialAccountBaseInfo(modifyReq);
  11. Retrieve user profile information

    dev

    You can retrieve profile fields for both friends and non-friends, supporting both standard and custom fields.

    Best Practices & Constraints:

    • Batch Size: It is recommended to request no more than 100 users per call to prevent failures caused by excessively large response payloads.
    • Account Existence: Ensure all accounts in the toAccount list have been imported into the IM service. Requesting accounts that are not imported will result in an error from the IM backend.

    Usage Pattern: Construct a PortraitGetRequest specifying the list of tags to retrieve (tagList) and the list of target accounts (toAccount), then call client.profile.portraitGet(request).

    List<String> tagList = Collections.singletonList(TagProfile.IM_NICK);
    List<String> toAccount = Collections.singletonList("test1");
    PortraitGetRequest request = PortraitGetRequest.builder()
            .tagList(tagList)
            .toAccount(toAccount)
            .build();
    
    PortraitGetResult result = client.profile.portraitGet(request);
  12. Get started with Tencent Cloud IM Server SDK

    dev

    To begin using the SDK, initialize an ImClient instance using your appId, an admin userId, and your application key. Once initialized, you can access various service modules (such as client.account) to perform operations like importing accounts.

    Common steps include:

    1. Defining your credentials (appId, userId, key).
    2. Creating the ImClient instance via ImClient.getInstance().
    3. Constructing request objects (e.g., AccountImportRequest).
    4. Calling the appropriate service method and handling potential IOException.
    // sdk appId
    long appId = 1400554812;
    
    // admin userId
    String userId = "test";
    
    // application key
    String key = "60c6c5925f3ae52c7325ac5a8ec78e44c056d1dd84d54e12ffa39911267a2a70";
    
    // create ImClient instance
    ImClient client = ImClient.getInstance(appId, userId, key);
    
    // import account
    AccountImportRequest request = new AccountImportRequest("doocs");
    request.setFaceUrl("https://avatars.githubusercontent.com/u/43716716?s=200&v=4");
    request.setNick("Doocs Community");
    try {
        AccountImportResult result = client.account.accountImport(request);
        // handle result
    } catch (IOException e) {
        // handle exception
    }