Skip to content

Conversation

Ol1ver0413
Copy link
Contributor

Description

Integrate Wechat via api.
There are two APIs available for integration on Wechat platform, one for the WeChat Official Account and one for WeChat Work. Due to lack of test account in WeChat Work, I have integrated the WeChat Official Account toolkit and implemented six functionalities.
#3049

Checklist

Go over all the following points, and put an x in all the boxes that apply.

  • I have read the CONTRIBUTION guide (required)
  • I have linked this PR to an issue using the Development section on the right sidebar or by adding Fixes #issue-number in the PR description (required)
  • I have checked if any dependencies need to be added or updated in pyproject.toml and uv lock
  • I have updated the tests accordingly (required for a bug fix or a new feature)
  • I have updated the documentation if needed:
  • I have added examples if this is a new feature

If you are unsure about any of these, don't hesitate to ask. We are here to help!

Copy link
Contributor

coderabbitai bot commented Aug 30, 2025

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Introduces a new WeChat Official Account toolkit, exports it via camel.toolkits, adds an example script demonstrating usage with an agent, and adds unit tests covering initialization, tools listing, token retrieval, messaging, user info, and missing-credential handling.

Changes

Cohort / File(s) Summary
Public export update
camel/toolkits/__init__.py
Imports WeChatOfficialToolkit and adds it to __all__.
WeChat toolkit implementation
camel/toolkits/wechat_official_toolkit.py
Adds WeChatOfficialToolkit with token caching, centralized request helper, and methods for customer messaging, user info, followers list, media upload/listing, and mass messaging; exposes tools via get_tools.
Example usage
examples/toolkits/wechat_official_toolkit.py
Adds a runnable example demonstrating toolkit integration with an agent, showcasing follower retrieval, text/media messaging, user info, and media management.
Unit tests
test/toolkits/test_wechat_official_toolkit.py
Adds tests for initialization, tools enumeration, access token retrieval, customer messaging, user info, and missing credentials using mocks/fixtures.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App as Agent/Client
  participant TK as WeChatOfficialToolkit
  participant Auth as WeChat Token Cache
  participant WX as WeChat API

  App->>TK: send_customer_message(openid, content, msgtype)
  TK->>Auth: _get_wechat_access_token()
  alt token missing/expired
    Auth->>WX: GET /cgi-bin/token?grant_type=client_credential&appid&secret
    WX-->>Auth: {access_token, expires_in}
    Note right of Auth: Cache token with expiry
  else token valid
    Note right of Auth: Use cached token
  end
  TK->>WX: POST /cgi-bin/message/custom/send?access_token=...
  WX-->>TK: {errcode, errmsg, ...}
  alt errcode != 0
    TK-->>App: raise ValueError(code,msg)
  else success
    TK-->>App: "Message sent successfully"
  end
Loading
sequenceDiagram
  autonumber
  participant App as Client Script
  participant TK as WeChatOfficialToolkit
  participant WX as WeChat API

  App->>TK: upload_wechat_media(type, file_path, permanent?)
  TK->>WX: POST media/upload or material/add_material
  WX-->>TK: {media_id, ...}
  App->>TK: get_media_list(type, offset, count)
  TK->>WX: POST material/batchget_material
  WX-->>TK: {item, total_count}
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Poem

I twitch my ears at fresh new tools,
With tokens cached and tidy rules.
I hop through chats, send notes en masse,
Upload a pic, then swiftly pass.
From warren logs to user streams—
WeChat now joins our bunny dreams. 🐇📨

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@nitpicker55555
Copy link
Collaborator

Thanks @Ol1ver0413 for your contribution!

Comment on lines 110 to 112
@api_keys_required([(None, "WECHAT_APP_ID"), (None, "WECHAT_APP_SECRET")])
def send_wechat_customer_message(openid: str, content: str, msgtype: str = "text") -> str:
r"""Sends a customer service message to a WeChat user.
Copy link
Collaborator

Choose a reason for hiding this comment

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

can we use Literal type for better type safety? like:
from typing import Literal

def send_wechat_customer_message(
openid: str,
content: str,
msgtype: Literal["text", "image", "voice", "video"] = "text"
) -> str:

Comment on lines 105 to 107
if data.get("errcode") and data.get("errcode") != 0:
raise ValueError(f"WeChat API error: {data.get('errmsg', 'Unknown error')}")

Copy link
Collaborator

Choose a reason for hiding this comment

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

Include error code for better debugging, like:
if data.get("errcode") and data.get("errcode") != 0:
errcode = data.get("errcode")
errmsg = data.get("errmsg", "Unknown error")
raise ValueError(f"WeChat API error {errcode}: {errmsg}")

Comment on lines 212 to 220
files = {"media": open(file_path, "rb")}
data_payload = {}

if media_type == "video" and description:
data_payload["description"] = description
files["description"] = (None, description)

data = _make_wechat_request("POST", endpoint, files=files, data=data_payload)
files["media"].close()
Copy link
Collaborator

Choose a reason for hiding this comment

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

It seems like file will not close if exception occurs before close()

@Ol1ver0413
Copy link
Contributor Author

Thanks @nitpicker55555! I've already make relevant changes according to your comment and organized the overall code structure. Thanks again!

@Wendong-Fan Wendong-Fan added this to the Sprint 36 milestone Aug 31, 2025
@Wendong-Fan Wendong-Fan linked an issue Aug 31, 2025 that may be closed by this pull request
2 tasks
Copy link
Member

@Wendong-Fan Wendong-Fan left a comment

Choose a reason for hiding this comment

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

thanks @Ol1ver0413 's contribution! Left some comments below

cc @nitpicker55555

Comment on lines 105 to 107
'ImageGenToolkit',
'WeChatOfficialToolkit',
'OpenAIImageToolkit',
Copy link
Member

Choose a reason for hiding this comment

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

seems we shouldn't change ImageGenToolkit to OpenAIImageToolkit

r"""Makes a request to WeChat API with proper error handling.

Args:
method (str): HTTP method ('GET' or 'POST').
Copy link
Member

Choose a reason for hiding this comment

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

we can also use Literal type for better type safety here

Comment on lines 54 to 57
if not app_id or not app_secret:
raise ValueError(
"WeChat credentials missing. Set WECHAT_APP_ID and WECHAT_APP_SECRET."
)
Copy link
Member

Choose a reason for hiding this comment

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

we have used decorator as below, would the check here still necessary?

    @api_keys_required([
        (None, "WECHAT_APP_ID"),
        (None, "WECHAT_APP_SECRET"),
    ])


Args:
openid (str): The user's OpenID.
lang (str): Response language: "zh_CN", "zh_TW", "en". (default: "zh_CN")
Copy link
Member

Choose a reason for hiding this comment

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

we can also use Literal type for better type safety here

self,
openid: str,
lang: str = "zh_CN",
) -> str:
Copy link
Member

Choose a reason for hiding this comment

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

could you double check the type hint here? should it be Dict[str, Any]?

def get_followers_list(
self,
next_openid: str = "",
) -> str:
Copy link
Member

Choose a reason for hiding this comment

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

could you double check the type hint here? should it be Dict[str, Any]?

file_path: str,
permanent: bool = False,
description: Optional[str] = None,
) -> str:
Copy link
Member

Choose a reason for hiding this comment

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

could you double check the type hint here? should it be Dict[str, Any]?

],
offset: int = 0,
count: int = 20,
) -> str:
Copy link
Member

Choose a reason for hiding this comment

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

could you double check the type hint here? should it be Dict[str, Any]?

Copy link
Member

Choose a reason for hiding this comment

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

toolkit would be used by agent, could you update the example code to showcase how this toolkit would be used by agent like how https://github.com/camel-ai/camel/blob/master/examples/toolkits/terminal_toolkit.py did?

@Ol1ver0413
Copy link
Contributor Author

Ol1ver0413 commented Sep 1, 2025

Thanks @Wendong-Fan! I've made relevant changes already and updated example file with agent using toolkits.

@nitpicker55555
Copy link
Collaborator

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Sep 1, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Nitpick comments (9)
test/toolkits/test_wechat_official_toolkit.py (3)

15-22: Fix import ordering to satisfy Ruff I001.

Sort the multi-name import and keep groups separated (stdlib → third-party → first-party).

Apply:

-from unittest.mock import MagicMock, patch
-
-import pytest
-
-from camel.toolkits.wechat_official_toolkit import (
-    WeChatOfficialToolkit,
-    _get_wechat_access_token,
-)
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from camel.toolkits.wechat_official_toolkit import (
+    _get_wechat_access_token,
+    WeChatOfficialToolkit,
+)

44-56: Avoid testing private function directly.

Importing and asserting on _get_wechat_access_token couples tests to internals. Prefer exercising token fetch via public methods (e.g., get_user_info) with requests.get patched.

If you’d like, I can provide a revised test that asserts token usage through get_user_info while stubbing requests.get and _make_wechat_request.


37-42: Make tool enumeration test resilient.

Asserting count==6 is brittle. Assert expected tool names instead.

Example:

-    tools = toolkit.get_tools()
-    assert len(tools) == 6
+    tool_names = {t.func.__name__ for t in toolkit.get_tools()}
+    assert {
+        "send_customer_message",
+        "get_user_info",
+        "get_followers_list",
+        "upload_wechat_media",
+        "get_media_list",
+        "send_mass_message_to_all",
+    }.issubset(tool_names)
examples/toolkits/wechat_official_toolkit.py (3)

14-18: Sort imports (I001) and group by origin.

Order internal modules alphabetically to align with style and pre-commit.

Apply:

-from camel.agents import ChatAgent
-from camel.models import ModelFactory
-from camel.toolkits import WeChatOfficialToolkit
-from camel.types import ModelPlatformType, ModelType
+from camel.agents import ChatAgent
+from camel.models import ModelFactory
+from camel.toolkits import WeChatOfficialToolkit
+from camel.types import ModelPlatformType, ModelType

Note: If ruff still flags I001, run isort/ruff --fix on the file.


47-50: Avoid absolute paths in examples.

Use a relative asset path or env-configurable path so the example runs anywhere.

Apply:

-    image_path = "/home/lyz/Camel/CAMEL_logo.jpg"  # Update this path as needed
+    from pathlib import Path
+    image_path = str(Path(__file__).with_suffix("").parent.parent / "assets" / "CAMEL_logo.jpg")

Also applies to: 68-70


36-44: Wrap overly long lines to pass E501.

Break long strings with parentheses or implicit concatenation; same for f-strings.

Example:

-    response = agent.step(
-        "Get the list of followers, then send a welcome message to the fifth follower."
-    )
+    response = agent.step(
+        (
+            "Get the list of followers, then send a welcome message "
+            "to the fifth follower."
+        )
+    )

Repeat for similar occurrences below.

Also applies to: 46-55, 57-65, 67-75

camel/toolkits/wechat_official_toolkit.py (3)

64-66: Wrap long lines to satisfy E501.

Break long expressions and messages per Google style (80 cols).

Apply examples:

-        _wechat_access_token_expires_at = time.time() + data.get("expires_in", 7200) - 60
+        _wechat_access_token_expires_at = (
+            time.time() + data.get("expires_in", 7200) - 60
+        )
-def _make_wechat_request(method: Literal["GET", "POST"], endpoint: str, **kwargs) -> Dict[str, Any]:
+def _make_wechat_request(
+    method: Literal["GET", "POST"],
+    endpoint: str,
+    **kwargs,
+) -> Dict[str, Any]:
-            raise ValueError(
-                "WeChat credentials missing. Set WECHAT_APP_ID and WECHAT_APP_SECRET."
-            )
+            raise ValueError(
+                "WeChat credentials missing. "
+                "Set WECHAT_APP_ID and WECHAT_APP_SECRET."
+            )
-            lang (str): Response language. Common values: "zh_CN", "zh_TW", "en". (default: "zh_CN")
+            lang (str): Response language. Common values: "zh_CN", "zh_TW",
+                "en". (default: "zh_CN")

Also applies to: 72-86, 136-139, 206-207


103-111: Optional: introduce a dedicated exception for API errors.

Raising ValueError with long messages (TRY003) is noisy. A small WeChatAPIError improves clarity.

Example:

+class WeChatAPIError(RuntimeError):
+    pass
@@
-        raise ValueError(f"WeChat API error {errcode}: {errmsg}")
+        raise WeChatAPIError(f"WeChat API error {errcode}: {errmsg}")

And update other ValueError sites similarly if desired.

Also applies to: 167-184


28-31: Optional: key token cache by credentials.

If env vars change at runtime/tests, the single global token can leak across creds. Cache per (app_id, app_secret).

I can draft a small token cache map if you want this now.

Also applies to: 48-53

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9f90e57 and fe865ee.

📒 Files selected for processing (4)
  • camel/toolkits/__init__.py (2 hunks)
  • camel/toolkits/wechat_official_toolkit.py (1 hunks)
  • examples/toolkits/wechat_official_toolkit.py (1 hunks)
  • test/toolkits/test_wechat_official_toolkit.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

⚙️ CodeRabbit configuration file

Review the python code against the google python style guide and point out any mismatches.

Files:

  • camel/toolkits/__init__.py
  • examples/toolkits/wechat_official_toolkit.py
  • test/toolkits/test_wechat_official_toolkit.py
  • camel/toolkits/wechat_official_toolkit.py
🪛 GitHub Actions: Pre Commit Check
examples/toolkits/wechat_official_toolkit.py

[error] 32-32: Ruff: E501 Line too long (101 > 79).


[error] 39-39: Ruff: E501 Line too long (87 > 79).


[error] 50-50: Ruff: E501 Line too long (109 > 79).


[error] 60-60: Ruff: E501 Line too long (122 > 79).


[error] 88-88: Ruff: E501 Line too long (139 > 79).


[error] 1-1: Ruff: I001 unsorted-imports


[warning] 113-113: WARNING - Invalid or missing max_tokens in model_config_dict. Defaulting to 999_999_999 tokens.

test/toolkits/test_wechat_official_toolkit.py

[error] 88-88: Ruff: E501 Line too long (116 > 79).


[error] 1-1: Ruff: I001 unsorted-imports

camel/toolkits/wechat_official_toolkit.py

[error] 64-64: Ruff: E501 Line too long (89 > 79).


[error] 72-72: Ruff: E501 Line too long (100 > 79).


[error] 138-138: Ruff: E501 Line too long (86 > 79).


[error] 206-206: Ruff: E501 Line too long (100 > 79).


[error] 298-298: Mypy: Incompatible types in assignment (expression has type 'tuple[None, str]', target has type 'BufferedReader[_BufferedReaderStream]')


[error] 1-1: Ruff: I001 unsorted-imports

🪛 Ruff (0.12.2)
test/toolkits/test_wechat_official_toolkit.py

34-34: Use of assert detected

(S101)


41-41: Use of assert detected

(S101)


55-55: Use of assert detected

(S101)


55-55: Possible hardcoded password assigned to: "token"

(S105)


65-65: Use of assert detected

(S101)


76-76: Use of assert detected

(S101)

camel/toolkits/wechat_official_toolkit.py

58-58: Probable use of requests call without timeout

(S113)


70-70: Avoid specifying long messages outside the exception class

(TRY003)


98-98: Probable use of requests call without timeout

(S113)


100-100: Probable use of requests call without timeout

(S113)


108-108: Avoid specifying long messages outside the exception class

(TRY003)


137-139: Avoid specifying long messages outside the exception class

(TRY003)

🔇 Additional comments (1)
camel/toolkits/__init__.py (1)

43-43: Export looks good; keep backward-compatibility intact.

Adding WeChatOfficialToolkit import and exposing it in all is correct and consistent with other toolkits.

Also applies to: 106-106

Comment on lines +21 to +24
from camel.logger import get_logger
from camel.toolkits import FunctionTool
from camel.toolkits.base import BaseToolkit
from camel.utils import MCPServer, api_keys_required, retry_on_error
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid package-level import to prevent circular imports.

Import FunctionTool from its submodule to remove the import-time cycle (camel.toolkits -> wechat_official_toolkit -> camel.toolkits).

Apply:

-from camel.toolkits import FunctionTool
-from camel.toolkits.base import BaseToolkit
+from camel.toolkits.base import BaseToolkit
+from camel.toolkits.function_tool import FunctionTool
📝 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
from camel.logger import get_logger
from camel.toolkits import FunctionTool
from camel.toolkits.base import BaseToolkit
from camel.utils import MCPServer, api_keys_required, retry_on_error
from camel.logger import get_logger
from camel.toolkits.base import BaseToolkit
from camel.toolkits.function_tool import FunctionTool
from camel.utils import MCPServer, api_keys_required, retry_on_error
🤖 Prompt for AI Agents
In camel/toolkits/wechat_official_toolkit.py around lines 21 to 24, avoid the
package-level import "from camel.toolkits import FunctionTool" which creates a
circular import; instead import FunctionTool directly from its defining
submodule (e.g. from camel.toolkits.function_tool import FunctionTool or the
actual module where FunctionTool is defined) and leave the other imports
unchanged so the module no longer triggers camel.toolkits ->
wechat_official_toolkit -> camel.toolkits at import time.

Comment on lines +33 to +46
@retry_on_error()
def _get_wechat_access_token() -> str:
r"""Retrieves or refreshes the WeChat Official Account access token.

Returns:
str: The valid access token.

Raises:
ValueError: If credentials are missing or token retrieval fails.

References:
https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
"""
global _wechat_access_token, _wechat_access_token_expires_at
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add request timeout to token fetch.

requests.get lacks a timeout (S113). Use a module default to avoid hangs.

Apply:

 @_retry_on_error()
 def _get_wechat_access_token() -> str:
@@
-    response = requests.get(url)
+    response = requests.get(url, timeout=DEFAULT_TIMEOUT)

Add near logger:

+DEFAULT_TIMEOUT: float = float(os.getenv("WECHAT_HTTP_TIMEOUT", "10"))

Also applies to: 58-61

🤖 Prompt for AI Agents
In camel/toolkits/wechat_official_toolkit.py around lines 33-46 (and also apply
same change to lines 58-61), the requests.get calls lack a timeout which can
hang; define a module-level DEFAULT_REQUEST_TIMEOUT constant (e.g., near the
logger definition) and pass timeout=DEFAULT_REQUEST_TIMEOUT to the requests.get
calls used to fetch the token (and the other request at 58-61); ensure the
constant is used for both calls so the module has a single default and avoids
blocking network hangs.

Comment on lines +72 to +101
def _make_wechat_request(method: Literal["GET", "POST"], endpoint: str, **kwargs) -> Dict[str, Any]:
r"""Makes a request to WeChat API with proper error handling.

Args:
method (Literal["GET", "POST"]): HTTP method ('GET' or 'POST').
endpoint (str): API endpoint path.
**kwargs: Additional arguments for requests.

Returns:
Dict[str, Any]: API response data.

Raises:
requests.exceptions.RequestException: If request fails.
ValueError: If API returns an error.
"""
global _wechat_access_token, _wechat_access_token_expires_at
access_token = _get_wechat_access_token()

# Handle URL parameter concatenation
separator = "&" if "?" in endpoint else "?"
url = (
f"https://api.weixin.qq.com{endpoint}{separator}"
f"access_token={access_token}"
)

if method.upper() == "GET":
response = requests.get(url, **kwargs)
else:
response = requests.post(url, **kwargs)

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Plumb timeouts through all requests and set a sensible default.

Ensure every outbound call has a timeout and respects the toolkit’s instance timeout.

Apply:

-def _make_wechat_request(method: Literal["GET", "POST"], endpoint: str, **kwargs) -> Dict[str, Any]:
+def _make_wechat_request(
+    method: Literal["GET", "POST"],
+    endpoint: str,
+    **kwargs,
+) -> Dict[str, Any]:
@@
-    if method.upper() == "GET":
-        response = requests.get(url, **kwargs)
-    else:
-        response = requests.post(url, **kwargs)
+    # Default timeout
+    timeout = kwargs.pop("timeout", None)
+    if timeout is None:
+        timeout = DEFAULT_TIMEOUT
+    if method.upper() == "GET":
+        response = requests.get(url, timeout=timeout, **kwargs)
+    else:
+        response = requests.post(url, timeout=timeout, **kwargs)

And pass self.timeout from call sites:

-        _make_wechat_request(
+        _make_wechat_request(
             "POST",
             "/cgi-bin/message/custom/send",
             headers={"Content-Type": "application/json"},
-            json=payload,
+            json=payload,
+            timeout=self.timeout,
         )
-        data = _make_wechat_request(
-            "GET", f"/cgi-bin/user/info?openid={openid}&lang={lang}"
-        )
+        data = _make_wechat_request(
+            "GET",
+            f"/cgi-bin/user/info?openid={openid}&lang={lang}",
+            timeout=self.timeout,
+        )
-        data = _make_wechat_request("GET", endpoint)
+        data = _make_wechat_request("GET", endpoint, timeout=self.timeout)
-                data = _make_wechat_request(
-                    "POST", endpoint, files=files, data=data_payload
-                )
+                data = _make_wechat_request(
+                    "POST",
+                    endpoint,
+                    files=files,
+                    data=data_payload,
+                    timeout=self.timeout,
+                )
@@
-                data = _make_wechat_request("POST", endpoint, files=files)
+                data = _make_wechat_request(
+                    "POST", endpoint, files=files, timeout=self.timeout
+                )
-        data = _make_wechat_request(
+        data = _make_wechat_request(
             "POST",
             "/cgi-bin/material/batchget_material",
             headers={"Content-Type": "application/json"},
-            json=payload,
+            json=payload,
+            timeout=self.timeout,
         )
-            resp = _make_wechat_request(
+            resp = _make_wechat_request(
                 "POST",
                 "/cgi-bin/message/mass/send",
                 headers={"Content-Type": "application/json"},
-                json=payload,
+                json=payload,
+                timeout=self.timeout,
             )

Also applies to: 185-191, 214-217, 239-242, 284-291, 324-329, 423-429

🧰 Tools
🪛 Ruff (0.12.2)

98-98: Probable use of requests call without timeout

(S113)


100-100: Probable use of requests call without timeout

(S113)

🪛 GitHub Actions: Pre Commit Check

[error] 72-72: Ruff: E501 Line too long (100 > 79).

🤖 Prompt for AI Agents
camel/toolkits/wechat_official_toolkit.py lines 72-101: The _make_wechat_request
implementation does not set a timeout nor accept a timeout parameter, so
outbound calls hang and don't respect the toolkit instance timeout; change the
signature to accept a timeout: Optional[float] = None (or timeout: float) and
ensure you pass a timeout into requests.get/post by doing
kwargs.setdefault("timeout", timeout or DEFAULT_TIMEOUT) (define a sensible
DEFAULT_TIMEOUT constant), then update every call site in this file to pass
self.timeout (and apply the same change to the other request helper usages at
lines 185-191, 214-217, 239-242, 284-291, 324-329, 423-429) so all requests use
the toolkit instance timeout or the default.

Comment on lines +275 to +287
if permanent:
endpoint = f"/cgi-bin/material/add_material?type={media_type}"
data_payload = {}
if media_type == "video" and description:
data_payload["description"] = description
with open(file_path, "rb") as media_file:
files = {"media": media_file}
if media_type == "video" and description:
files["description"] = (None, description)
data = _make_wechat_request(
"POST", endpoint, files=files, data=data_payload
)
else:
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix mypy error and align with WeChat API form fields.

Don’t put “description” in files; send it via form data. Also type the files dict to avoid inference as BufferedReader-only.

Apply:

-            data_payload = {}
+            data_payload: Dict[str, Any] = {}
             if media_type == "video" and description:
                 data_payload["description"] = description
             with open(file_path, "rb") as media_file:
-                files = {"media": media_file}
-                if media_type == "video" and description:
-                    files["description"] = (None, description)
+                files: Dict[str, Any] = {"media": media_file}
                 data = _make_wechat_request(
-                    "POST", endpoint, files=files, data=data_payload
+                    "POST",
+                    endpoint,
+                    files=files,
+                    data=data_payload,
+                    timeout=self.timeout,
                 )
@@
-            with open(file_path, "rb") as f:
-                files = {"media": f}
-                data = _make_wechat_request("POST", endpoint, files=files)
+            with open(file_path, "rb") as media_file:
+                files: Dict[str, Any] = {"media": media_file}
+                data = _make_wechat_request(
+                    "POST", endpoint, files=files, timeout=self.timeout
+                )

Also applies to: 289-293

Comment on lines +81 to +218
2. **Identified the fifth follower**: From the list, the fifth follower has the OpenID: `oKSAF2******rEJI`

3. **Sent a welcome message**: I successfully sent a welcome message to the fifth follower with the content: "Welcome! Thank you for following our WeChat Official Account. We're excited to have you join our community!"

The message was delivered successfully to the fifth follower in your follower list.
Tool calls:
1. get_followers_list({'next_openid': ''})
2. send_customer_message({'openid': 'oKSAF2******rEJI', 'content': "Welcome! Thank you for following our WeChat Official Account. We're excited to have you join our community!", 'msgtype': 'text'})

==============================

Image Upload and Send Response:

Perfect! I've successfully completed both tasks:

1. **Retrieved followers list**: Found 6 followers total, with the fifth follower having OpenID: `oKSAF2******rEJI`

2. **Sent welcome message**: Successfully sent a welcome text message to the fifth follower.

3. **Uploaded image**: Successfully uploaded the CAMEL logo image as temporary media with media_id: `A_6Hlu******MW_ubO`

4. **Sent image**: Successfully sent the uploaded image to the fifth follower.

Both the welcome message and the CAMEL logo image have been delivered to the fifth follower!
Tool calls:
1. upload_wechat_media({'media_type': 'image', 'file_path': '/home/lyz/Camel/CAMEL_logo.jpg', 'permanent': False, 'description': None})
2. send_customer_message({'openid': 'oKSAF2******rEJI', 'content': 'A_6Hlu******MW_ubO', 'msgtype': 'image'})

==============================

User Info Response:

I've retrieved the detailed information about the fifth follower. Here are the key details:

**Language Preference:**
- Language: zh_CN (Chinese, mainland China)

**Subscription Details:**
- Subscribe Status: 1 (actively subscribed)
- Subscribe Time: 1756536553 (Unix timestamp)
- Subscribe Scene: ADD_SCENE_QR_CODE (subscribed via QR code scan)

**Additional Information:**
- OpenID: oKSAF2******rEJI
- Nickname: (not provided)
- Gender: 0 (unknown)
- Location: City, province, and country are all empty
- Profile Picture: Not set
- Group ID: 0 (default group)
- Tags: No tags assigned
- Custom Remark: None

The follower is actively subscribed and prefers Chinese (mainland China) language. They joined the account by scanning a QR code.
Tool calls:
1. get_user_info({'openid': 'oKSAF2******rEJI', 'lang': 'en'})

==============================

Permanent Media Upload Response:

Perfect! I've successfully completed both tasks:

## 1. Image Upload (Permanent Media)
The image `/home/lyz/Camel/CAMEL_logo.jpg` has been uploaded as permanent media with the following details:
- **Media ID**: `Rd1Ljw******mBUw_`
- **URL**: `https://mmbiz.qpic.cn/.../0?wx_fmt=jpeg`

## 2. Image Media List
I retrieved the list of all permanent image media files. Here's what's currently in your media library:

**Total Count**: 5 image files

**Recent Uploads** (most recent first):
1. **CAMEL_logo.jpg** (just uploaded)
- Media ID: `Rd1Ljw******mBUw_`
- Update Time: 1756708975
- URL: `https://mmbiz.qpic.cn/.../0?wx_fmt=jpeg`

2. **CAMEL_logo.jpg**
- Media ID: `Rd1Ljw******65QkxQ`
- Update Time: 1756627187

3. **CAMEL_logo.jpg**
- Media ID: `Rd1Ljw******5aB03`
- Update Time: 1756626675

4. **CAMEL_logo.jpg**
- Media ID: `Rd1Ljw******d2-SA`
- Update Time: 1756540111

5. **CAMEL_logo.jpg**
- Media ID: `Rd1Ljw******QKlyt`
- Update Time: 1756539999

All files appear to be the same CAMEL logo image uploaded at different times. The most recent upload is now available for use in your WeChat communications.
Tool calls:
1. upload_wechat_media({'media_type': 'image', 'file_path': '/home/lyz/Camel/CAMEL_logo.jpg', 'permanent': True, 'description': ''})
2. get_media_list({'media_type': 'image', 'offset': 0, 'count': 20})

"""
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove embedded run transcript.

The giant triple-quoted output block inflates the file and triggers multiple E501 failures. Move it to README or a docs snippet.

Apply:

-"""
-<entire transcript block...>
-"""
📝 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
"""
Text Message Response:
I've successfully completed both tasks:
1. **Retrieved the followers list**: Found 6 total followers with their OpenIDs
2. **Sent welcome message to the fifth follower**: The welcome message was successfully sent to the follower with OpenID `oKSAF2******rEJI`
The welcome message "Welcome! Thank you for following our WeChat Official Account. We're excited to have you as part of our community!" has been delivered successfully.
Tool calls:
1. get_followers_list({'next_openid': ''})
2. send_customer_message({'openid': 'oKSAF2******rEJI', 'content': "Welcome! Thank you for following our WeChat Official Account. We're excited to have you as part of our community!", 'msgtype': 'text'})
==============================
Image Upload and Send Response:
Perfect! I've successfully completed both tasks:
1. **Uploaded the image**: The image at '/home/lyz/Camel/CAMEL_logo.jpg' has been uploaded as temporary media with media_id: `A_6Hlu******C6IUr`
2. **Sent the image to the fifth follower**: The image has been successfully sent to the fifth follower (OpenID: oKSAF2******rEJI)
Both operations completed successfully!
Tool calls:
1. upload_wechat_media({'media_type': 'image', 'file_path': '/home/lyz/Camel/CAMEL_logo.jpg', 'permanent': False, 'description': ''})
2. send_customer_message({'openid': 'oKSAF2******rEJI', 'content': 'A_6Hlu******C6IUr', 'msgtype': 'image'})
==============================
(.camel) [lyz@dev10 toolkits]$ python wechat_official_toolkit.py
2025-09-01 02:41:48,494 - root - WARNING - Invalid or missing `max_tokens` in `model_config_dict`. Defaulting to 999_999_999 tokens.
Text Message Response:
I've successfully completed your request! Here's what I did:
1. **Retrieved the follower list**: I got the list of all followers, which shows there are 6 total followers.
2. **Identified the fifth follower**: From the list, the fifth follower has the OpenID: `oKSAF2******rEJI`
3. **Sent a welcome message**: I successfully sent a welcome message to the fifth follower with the content: "Welcome! Thank you for following our WeChat Official Account. We're excited to have you join our community!"
The message was delivered successfully to the fifth follower in your follower list.
Tool calls:
1. get_followers_list({'next_openid': ''})
2. send_customer_message({'openid': 'oKSAF2******rEJI', 'content': "Welcome! Thank you for following our WeChat Official Account. We're excited to have you join our community!", 'msgtype': 'text'})
==============================
Image Upload and Send Response:
Perfect! I've successfully completed both tasks:
1. **Retrieved followers list**: Found 6 followers total, with the fifth follower having OpenID: `oKSAF2******rEJI`
2. **Sent welcome message**: Successfully sent a welcome text message to the fifth follower.
3. **Uploaded image**: Successfully uploaded the CAMEL logo image as temporary media with media_id: `A_6Hlu******MW_ubO`
4. **Sent image**: Successfully sent the uploaded image to the fifth follower.
Both the welcome message and the CAMEL logo image have been delivered to the fifth follower!
Tool calls:
1. upload_wechat_media({'media_type': 'image', 'file_path': '/home/lyz/Camel/CAMEL_logo.jpg', 'permanent': False, 'description': None})
2. send_customer_message({'openid': 'oKSAF2******rEJI', 'content': 'A_6Hlu******MW_ubO', 'msgtype': 'image'})
==============================
User Info Response:
I've retrieved the detailed information about the fifth follower. Here are the key details:
**Language Preference:**
- Language: zh_CN (Chinese, mainland China)
**Subscription Details:**
- Subscribe Status: 1 (actively subscribed)
- Subscribe Time: 1756536553 (Unix timestamp)
- Subscribe Scene: ADD_SCENE_QR_CODE (subscribed via QR code scan)
**Additional Information:**
- OpenID: oKSAF2******rEJI
- Nickname: (not provided)
- Gender: 0 (unknown)
- Location: City, province, and country are all empty
- Profile Picture: Not set
- Group ID: 0 (default group)
- Tags: No tags assigned
- Custom Remark: None
The follower is actively subscribed and prefers Chinese (mainland China) language. They joined the account by scanning a QR code.
Tool calls:
1. get_user_info({'openid': 'oKSAF2******rEJI', 'lang': 'en'})
==============================
Permanent Media Upload Response:
Perfect! I've successfully completed both tasks:
## 1. Image Upload (Permanent Media)
The image `/home/lyz/Camel/CAMEL_logo.jpg` has been uploaded as permanent media with the following details:
- **Media ID**: `Rd1Ljw******mBUw_`
- **URL**: `https://mmbiz.qpic.cn/.../0?wx_fmt=jpeg`
## 2. Image Media List
I retrieved the list of all permanent image media files. Here's what's currently in your media library:
**Total Count**: 5 image files
**Recent Uploads** (most recent first):
1. **CAMEL_logo.jpg** (just uploaded)
- Media ID: `Rd1Ljw******mBUw_`
- Update Time: 1756708975
- URL: `https://mmbiz.qpic.cn/.../0?wx_fmt=jpeg`
2. **CAMEL_logo.jpg**
- Media ID: `Rd1Ljw******65QkxQ`
- Update Time: 1756627187
3. **CAMEL_logo.jpg**
- Media ID: `Rd1Ljw******5aB03`
- Update Time: 1756626675
4. **CAMEL_logo.jpg**
- Media ID: `Rd1Ljw******d2-SA`
- Update Time: 1756540111
5. **CAMEL_logo.jpg**
- Media ID: `Rd1Ljw******QKlyt`
- Update Time: 1756539999
All files appear to be the same CAMEL logo image uploaded at different times. The most recent upload is now available for use in your WeChat communications.
Tool calls:
1. upload_wechat_media({'media_type': 'image', 'file_path': '/home/lyz/Camel/CAMEL_logo.jpg', 'permanent': True, 'description': ''})
2. get_media_list({'media_type': 'image', 'offset': 0, 'count': 20})
"""
🧰 Tools
🪛 GitHub Actions: Pre Commit Check

[error] 88-88: Ruff: E501 Line too long (139 > 79).


[warning] 113-113: WARNING - Invalid or missing max_tokens in model_config_dict. Defaulting to 999_999_999 tokens.

🤖 Prompt for AI Agents
examples/toolkits/wechat_official_toolkit.py lines 81-218: the file contains a
huge triple-quoted run transcript that causes E501/line-length failures and
inflates the source; remove this embedded transcript and instead move the full
run output to README or a separate docs/snippets file, replacing the
triple-quoted block with a short one-line comment linking to the external doc
(or load the content from a separate file if you need it at runtime); ensure no
long literal strings remain in the module and run flake8/pyright to confirm E501
is resolved.

Comment on lines 86 to 98
"""
=============================================== test session starts ================================================
platform linux -- Python 3.11.7, pytest-8.4.1, pluggy-1.6.0
rootdir: /home/lyz/Camel/camel
configfile: pyproject.toml
plugins: anyio-4.10.0
collected 6 items

test_wechat_official_toolkit.py ...... [100%]

================================================ 6 passed in 0.39s =================================================

"""
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove embedded test run transcript to fix E501 and keep tests clean.

The long triple-quoted log at file end causes line-length failures and adds noise.

Apply:

-"""
-=============================================== test session starts ================================================
-platform linux -- Python 3.11.7, pytest-8.4.1, pluggy-1.6.0
-rootdir: /home/lyz/Camel/camel
-configfile: pyproject.toml
-plugins: anyio-4.10.0
-collected 6 items                                                                                                  
-
-test_wechat_official_toolkit.py ......                                                                       [100%]
-
-================================================ 6 passed in 0.39s =================================================
-
-"""
📝 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
"""
=============================================== test session starts ================================================
platform linux -- Python 3.11.7, pytest-8.4.1, pluggy-1.6.0
rootdir: /home/lyz/Camel/camel
configfile: pyproject.toml
plugins: anyio-4.10.0
collected 6 items
test_wechat_official_toolkit.py ...... [100%]
================================================ 6 passed in 0.39s =================================================
"""
🧰 Tools
🪛 GitHub Actions: Pre Commit Check

[error] 88-88: Ruff: E501 Line too long (116 > 79).

🤖 Prompt for AI Agents
In test/toolkits/test_wechat_official_toolkit.py around lines 86 to 98, remove
the long triple-quoted test run transcript at the end of the file that causes
E501 line-length failures and unnecessary noise; delete the entire multi-line
string (the pytest session log) so the file ends with actual test code or a
normal newline, and run a quick lint/pytest to confirm no trailing whitespace or
remaining long lines.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: No status
Development

Successfully merging this pull request may close these issues.

[Feature Request] Integrate Wechat
3 participants