-
Notifications
You must be signed in to change notification settings - Fork 1.5k
[Feat] Integrate Wechat #3087
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
[Feat] Integrate Wechat #3087
Conversation
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the WalkthroughIntroduces 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
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
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}
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Poem
✨ Finishing Touches🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
Thanks @Ol1ver0413 for your contribution! |
@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. |
There was a problem hiding this comment.
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:
if data.get("errcode") and data.get("errcode") != 0: | ||
raise ValueError(f"WeChat API error: {data.get('errmsg', 'Unknown error')}") | ||
|
There was a problem hiding this comment.
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}")
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() |
There was a problem hiding this comment.
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()
Thanks @nitpicker55555! I've already make relevant changes according to your comment and organized the overall code structure. Thanks again! |
There was a problem hiding this 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
camel/toolkits/__init__.py
Outdated
'ImageGenToolkit', | ||
'WeChatOfficialToolkit', | ||
'OpenAIImageToolkit', |
There was a problem hiding this comment.
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'). |
There was a problem hiding this comment.
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
if not app_id or not app_secret: | ||
raise ValueError( | ||
"WeChat credentials missing. Set WECHAT_APP_ID and WECHAT_APP_SECRET." | ||
) |
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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]?
There was a problem hiding this comment.
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?
Thanks @Wendong-Fan! I've made relevant changes already and updated example file with agent using toolkits. |
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this 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, ModelTypeNote: 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.
📒 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
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 |
There was a problem hiding this comment.
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.
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.
@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 |
There was a problem hiding this comment.
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.
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) | ||
|
There was a problem hiding this comment.
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.
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: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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
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}) | ||
|
||
""" |
There was a problem hiding this comment.
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.
""" | |
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.
""" | ||
=============================================== 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 ================================================= | ||
|
||
""" |
There was a problem hiding this comment.
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.
""" | |
=============================================== 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.
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.Fixes #issue-number
in the PR description (required)pyproject.toml
anduv lock
If you are unsure about any of these, don't hesitate to ask. We are here to help!