Skip to content

feat(im): add +chat-members-add shortcut#1988

Open
zhangheng023 wants to merge 8 commits into
mainfrom
feat/im-chat-add-members
Open

feat(im): add +chat-members-add shortcut#1988
zhangheng023 wants to merge 8 commits into
mainfrom
feat/im-chat-add-members

Conversation

@zhangheng023

@zhangheng023 zhangheng023 commented Jul 21, 2026

Copy link
Copy Markdown
Collaborator

Summary

Add im +chat-members-add, a shortcut that adds users and/or bots to a group chat. The existing Meta API command chat.members.create only accepts one member_id_type per request (open_id for users, app_id for bots), so adding both requires two separate calls whose results must be merged by hand. This shortcut orchestrates that internally under best-effort semantics and returns one merged ledger.

Changes

  • New im +chat-members-add shortcut: --users/--bots flags with local validation (ID prefix + count limits), --dry-run preview of up to two underlying API calls, and a merged output ledger (succeeded_id_list / invalid_id_list / not_existed_id_list / pending_approval_id_list / call_errors / success_count / failure_count / total)
  • Best-effort execution: a resigned/nonexistent/pending-approval ID doesn't block the rest of the batch from being added
  • When both --users and --bots are supplied and both underlying calls fail with an auth/permission-classified error, the command returns that typed error directly instead of building a ledger
  • Registered the shortcut and updated the package's shortcut-list test
  • Added a skill reference doc and updated the domain's SKILL.md

Test Plan

  • Unit tests pass (go test ./shortcuts/im/...) — covers validation rules, batch-merge logic (all-succeed / partial failure across all three failure buckets / call-level failure), the auth-both-fail short-circuit, and dry-run output
  • go build ./... and go vet ./... pass
  • Manual local verification confirms the lark-cli im +chat-members-add flow works as expected

Related Issues

  • None

Summary by CodeRabbit

  • New Features

    • Added the +chat-members-add shortcut for batch-adding users and bots to chats.
    • Supports input validation, duplicate removal, dry-run previews, and partial-success reporting.
    • Reports successful, invalid, nonexistent, and pending-approval member IDs.
  • Documentation

    • Added usage guidance, parameters, limits, output details, and troubleshooting information.
  • Tests

    • Added coverage for validation, batching, dry runs, partial failures, and authorization errors.

…check

chat.members.create raw meta lists ["im:chat", "im:chat.members:write_only"]
as OR alternatives, but the local scope precheck (MissingScopes) treats every
entry in Scopes as required (AND), so declaring both wrongly rejected tokens
holding only the narrower write_only scope. Declare only that narrow scope,
matching the chat-members-list shortcut pattern, and update the doc
troubleshooting row/login example to match.
@zhangheng023 zhangheng023 added enhancement New feature or request domain/im PR touches the im domain size/M Single-domain feat or fix with limited business impact labels Jul 21, 2026
@github-actions github-actions Bot added size/L Large or sensitive change across domains or core paths and removed size/M Single-domain feat or fix with limited business impact labels Jul 21, 2026
@coderabbitai

coderabbitai Bot commented Jul 21, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds the +chat-members-add IM shortcut with validation, separate user and bot API calls, merged result reporting, partial-failure handling, authorization semantics, tests, shortcut registration, and CLI documentation.

Changes

IM chat member addition

Layer / File(s) Summary
Input validation and result contract
shortcuts/im/im_chat_members_add.go
Validates chat and member IDs, trims and deduplicates inputs, enforces limits, and defines the merged result ledger.
Batch execution and failure handling
shortcuts/im/im_chat_members_add.go
Performs separate user and bot requests, merges categorized results, computes counts, and handles authorization failures.
Shortcut wiring and behavioral tests
shortcuts/im/im_chat_members_add.go, shortcuts/im/shortcuts.go, shortcuts/im/helpers_test.go, shortcuts/im/im_chat_members_add_test.go
Registers the shortcut, wires execute and dry-run behavior, and tests validation, API outcomes, output shaping, and authorization cases.
CLI reference documentation
skills/lark-im/SKILL.md, skills/lark-im/references/lark-im-chat-members-add.md
Documents command usage, limits, output fields, partial failures, and authorization behavior.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant ImChatMembersAdd
  participant ChatMembersAPI
  CLI->>ImChatMembersAdd: Execute chat and member flags
  ImChatMembersAdd->>ChatMembersAPI: POST user members with open_id
  ImChatMembersAdd->>ChatMembersAPI: POST bot members with app_id
  ChatMembersAPI-->>ImChatMembersAdd: Return categorized member results
  ImChatMembersAdd-->>CLI: Return merged ledger or typed authorization error
Loading

Possibly related PRs

Suggested labels: feature

Suggested reviewers: liangshuo-1, yangjunzhou-01

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the new IM shortcut.
Description check ✅ Passed The description follows the template and includes summary, changes, test plan, and related issues.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/im-chat-add-members

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Jul 21, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.66667% with 17 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.07%. Comparing base (c876841) to head (cdb5343).
⚠️ Report is 6 commits behind head on main.

Files with missing lines Patch % Lines
shortcuts/im/im_chat_members_add.go 88.59% 10 Missing and 7 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1988      +/-   ##
==========================================
+ Coverage   75.05%   75.07%   +0.02%     
==========================================
  Files         901      902       +1     
  Lines       95391    95541     +150     
==========================================
+ Hits        71591    71724     +133     
- Misses      18307    18317      +10     
- Partials     5493     5500       +7     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions

Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

npm i -g https://pkg.pr.new/larksuite/cli/@larksuite/cli@cdb5343bd435a29c390d90c60f13e1bfa7accd63

🧩 Skill update

npx skills add larksuite/cli#feat/im-chat-add-members -y -g

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@shortcuts/im/im_chat_members_add.go`:
- Around line 65-72: Add adjacent table-driven tests covering invalid --users
and --bots prefixes through both validateChatMembersAdd and
executeChatMembersAdd, asserting the collectMemberAddIDs errors are propagated.
Add direct allAuthClassified tests for an empty slice and a mixed-category
slice, asserting the empty guard and non-auth mismatch results.
- Around line 84-91: Replace the loose map-based API and call-error handling in
addChatMembersBatch with typed structures: introduce typed response and
call-error structs, decode the response into the typed API response once, and
change chatMembersAddResult.callErrors to []chatMembersAddCallError. Update the
affected ledger construction and consumption sites to use typed fields instead
of map indexing and type assertions, preserving the existing invalid,
nonexistent, pending-approval, and error values.
- Line 178: Remove the stray “user/bot;” fragment from the command Description
string, leaving the surrounding wording and batching behavior unchanged so the
CLI help text reads clearly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b02903e2-e762-4fed-9529-8d3cadc6f949

📥 Commits

Reviewing files that changed from the base of the PR and between d382ee9 and cdb5343.

📒 Files selected for processing (6)
  • shortcuts/im/helpers_test.go
  • shortcuts/im/im_chat_members_add.go
  • shortcuts/im/im_chat_members_add_test.go
  • shortcuts/im/shortcuts.go
  • skills/lark-im/SKILL.md
  • skills/lark-im/references/lark-im-chat-members-add.md

Comment on lines +65 to +72
users, err := collectMemberAddIDs(runtime, "users", "ou_", chatMembersAddMaxUsers)
if err != nil {
return err
}
bots, err := collectMemberAddIDs(runtime, "bots", "cli_", chatMembersAddMaxBots)
if err != nil {
return err
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Add test coverage for these error-propagation and classification branches.

Codecov flags Lines 67, 71 (validateChatMembersAdd returning collectMemberAddIDs errors for --users/--bots), Lines 235, 239 (same pattern in executeChatMembersAdd), and Lines 296, 301 (allAuthClassified's empty-slice guard and non-auth mismatch branch) as uncovered. None of the current table-driven tests exercise an invalid --users/--bots prefix through the full validateChatMembersAdd/executeChatMembersAdd wiring, or exercise allAuthClassified with an empty or mixed-category slice directly.

As per coding guidelines, "Every behavior change must include an adjacent test, and the test must directly assert the changed field or behavior so reverting the implementation causes the test to fail."

Also applies to: 233-240, 294-305

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 67-67: shortcuts/im/im_chat_members_add.go#L67
Added line #L67 was not covered by tests


[warning] 71-71: shortcuts/im/im_chat_members_add.go#L71
Added line #L71 was not covered by tests

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shortcuts/im/im_chat_members_add.go` around lines 65 - 72, Add adjacent
table-driven tests covering invalid --users and --bots prefixes through both
validateChatMembersAdd and executeChatMembersAdd, asserting the
collectMemberAddIDs errors are propagated. Add direct allAuthClassified tests
for an empty slice and a mixed-category slice, asserting the empty guard and
non-auth mismatch results.

Sources: Coding guidelines, Linters/SAST tools

Comment on lines +84 to +91
type chatMembersAddResult struct {
succeeded []string
invalid []string
notExisted []string
pendingApproval []string
callErrors []map[string]interface{}
rawCallErrors []error
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift

Loose-map usage for API response and ledger entries.

addChatMembersBatch indexes the decoded response via data["invalid_id_list"], data["not_existed_id_list"], etc., and callErrors is stored as []map[string]interface{} with call sites later doing ce["id_list"].([]string) type assertions (Line 264). This is new loose-map code at an API boundary rather than a parsed typed struct.

♻️ Suggested typed-struct approach
type chatMembersAddAPIResponse struct {
	InvalidIDList         []string `json:"invalid_id_list"`
	NotExistedIDList      []string `json:"not_existed_id_list"`
	PendingApprovalIDList []string `json:"pending_approval_id_list"`
}

type chatMembersAddCallError struct {
	MemberType string   `json:"member_type"`
	IDList     []string `json:"id_list"`
	Error      string   `json:"error"`
}

Decode data into chatMembersAddAPIResponse once, and change chatMembersAddResult.callErrors to []chatMembersAddCallError, replacing the map indexing/assertions accordingly.

As per coding guidelines, "Parse map[string]interface{} into typed structs at boundaries, use projection functions per shape... Do not introduce new loose-map code."

Also applies to: 107-148, 263-267, 270-280

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shortcuts/im/im_chat_members_add.go` around lines 84 - 91, Replace the loose
map-based API and call-error handling in addChatMembersBatch with typed
structures: introduce typed response and call-error structs, decode the response
into the typed API response once, and change chatMembersAddResult.callErrors to
[]chatMembersAddCallError. Update the affected ledger construction and
consumption sites to use typed fields instead of map indexing and type
assertions, preserving the existing invalid, nonexistent, pending-approval, and
error values.

Source: Coding guidelines

var ImChatMembersAdd = common.Shortcut{
Service: "im",
Command: "+chat-members-add",
Description: "Add users and/or bots to a group chat; user/bot; batches --users (open_id) and --bots (app_id) into up to 2 API calls under best-effort semantics; returns a merged succeeded/invalid/not_existed/pending_approval ledger",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Stray fragment in the Description string.

"...to a group chat; user/bot; batches --users..." — the ; user/bot; clause reads as leftover/misplaced text and disrupts an otherwise clear help string shown to CLI users.

✏️ Suggested cleanup
-	Description: "Add users and/or bots to a group chat; user/bot; batches --users (open_id) and --bots (app_id) into up to 2 API calls under best-effort semantics; returns a merged succeeded/invalid/not_existed/pending_approval ledger",
+	Description: "Add users and/or bots to a group chat; batches --users (open_id) and --bots (app_id) into up to 2 API calls under best-effort semantics; returns a merged succeeded/invalid/not_existed/pending_approval ledger",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Description: "Add users and/or bots to a group chat; user/bot; batches --users (open_id) and --bots (app_id) into up to 2 API calls under best-effort semantics; returns a merged succeeded/invalid/not_existed/pending_approval ledger",
Description: "Add users and/or bots to a group chat; batches --users (open_id) and --bots (app_id) into up to 2 API calls under best-effort semantics; returns a merged succeeded/invalid/not_existed/pending_approval ledger",
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shortcuts/im/im_chat_members_add.go` at line 178, Remove the stray
“user/bot;” fragment from the command Description string, leaving the
surrounding wording and batching behavior unchanged so the CLI help text reads
clearly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

domain/im PR touches the im domain enhancement New feature or request size/L Large or sensitive change across domains or core paths

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant