Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

[Feat] Integrate Wechat (#3087)

Ol1ver041388cedc9e5179
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.py
index 438f0a494..7c1cdc6c5 100644
--- a/camel/toolkits/__init__.py
+++ b/camel/toolkits/__init__.py
@@ -40,6 +40,7 @@ from .google_calendar_toolkit import GoogleCalendarToolkit
from .arxiv_toolkit import ArxivToolkit
from .slack_toolkit import SlackToolkit
from .whatsapp_toolkit import WhatsAppToolkit
+from .wechat_official_toolkit import WeChatOfficialToolkit
from .twitter_toolkit import TwitterToolkit
from .open_api_toolkit import OpenAPIToolkit
from .retrieval_toolkit import RetrievalToolkit
@@ -103,6 +104,7 @@ __all__ = [
'SearchToolkit',
'SlackToolkit',
'WhatsAppToolkit',
+ 'WeChatOfficialToolkit',
'ImageGenToolkit',
'TwitterToolkit',
'WeatherToolkit',
diff --git a/camel/toolkits/wechat_official_toolkit.py b/camel/toolkits/wechat_official_toolkit.py
new file mode 100644
index 000000000..9563ba6e3
--- /dev/null
+++ b/camel/toolkits/wechat_official_toolkit.py
@@ -0,0 +1,446 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+
+import os
+import time
+from typing import Any, Dict, List, Optional, Literal
+
+import requests
+
+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
+
+logger = get_logger(__name__)
+
+# Global variables for caching access token
+_wechat_access_token = None
+_wechat_access_token_expires_at = 0
+
+
+@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
+
+ if _wechat_access_token and _wechat_access_token_expires_at > time.time():
+ return _wechat_access_token
+
+ app_id = os.environ.get("WECHAT_APP_ID", "")
+ app_secret = os.environ.get("WECHAT_APP_SECRET", "")
+
+ url = (
+ "https://api.weixin.qq.com/cgi-bin/token?"
+ f"grant_type=client_credential&appid={app_id}&secret={app_secret}"
+ )
+ response = requests.get(url)
+ response.raise_for_status()
+ data = response.json()
+
+ if "access_token" in data:
+ _wechat_access_token = data["access_token"]
+ _wechat_access_token_expires_at = time.time() + data.get("expires_in", 7200) - 60
+ logger.info("WeChat access token refreshed.")
+ return _wechat_access_token
+ else:
+ errcode = data.get("errcode")
+ errmsg = data.get("errmsg", "Unknown error")
+ raise ValueError(f"Failed to get access token {errcode}: {errmsg}")
+
+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)
+
+ response.raise_for_status()
+ data = response.json()
+
+ 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}")
+
+ return data
+
+@MCPServer()
+class WeChatOfficialToolkit(BaseToolkit):
+ r"""A toolkit for WeChat Official Account operations.
+
+ This toolkit provides methods to interact with the WeChat Official Account
+ API, allowing users to send messages, manage users, and handle media files.
+
+ References:
+ - Documentation: https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html
+ - Test Account: https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
+
+ Notes:
+ Set environment variables: WECHAT_APP_ID, WECHAT_APP_SECRET
+ """
+
+ def __init__(self, timeout: Optional[float] = None):
+ r"""Initializes the WeChatOfficialToolkit."""
+ super().__init__(timeout=timeout)
+ self.base_url = "https://api.weixin.qq.com"
+
+ # Validate credentials
+ app_id = os.environ.get("WECHAT_APP_ID", "")
+ app_secret = os.environ.get("WECHAT_APP_SECRET", "")
+
+ if not all([app_id, app_secret]):
+ raise ValueError(
+ "WeChat credentials missing. Set WECHAT_APP_ID and WECHAT_APP_SECRET."
+ )
+
+ # Define full logic as class methods; top-level functions delegate here
+ @api_keys_required([
+ (None, "WECHAT_APP_ID"),
+ (None, "WECHAT_APP_SECRET"),
+ ])
+ def send_customer_message(
+ self,
+ openid: str,
+ content: str,
+ msgtype: Literal[
+ "text",
+ "image",
+ "voice",
+ "video",
+ ] = "text",
+ ) -> str:
+ r"""Sends a customer service message to a WeChat user.
+
+ Args:
+ openid (str): The user's OpenID.
+ content (str): Message content or media_id for non-text messages.
+ msgtype (str): Message type: "text", "image", "voice", "video".
+
+ Returns:
+ str: Success or error message.
+
+ References:
+ https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html
+ """
+ payload: Dict[str, Any] = {"touser": openid, "msgtype": msgtype}
+ if msgtype == "text":
+ payload["text"] = {"content": content}
+ elif msgtype in ["image", "voice"]:
+ payload[msgtype] = {"media_id": content}
+ elif msgtype == "video":
+ parts = content.split(",", 2)
+ payload["video"] = {
+ "media_id": parts[0],
+ "title": parts[1] if len(parts) > 1 else "",
+ "description": parts[2] if len(parts) > 2 else "",
+ }
+ else:
+ return f"Unsupported message type: {msgtype}"
+
+ _make_wechat_request(
+ "POST",
+ "/cgi-bin/message/custom/send",
+ headers={"Content-Type": "application/json"},
+ json=payload,
+ )
+ return f"Message sent successfully to {openid}."
+
+ @api_keys_required([
+ (None, "WECHAT_APP_ID"),
+ (None, "WECHAT_APP_SECRET"),
+ ])
+ def get_user_info(
+ self,
+ openid: str,
+ lang: str = "zh_CN",
+ ) -> Dict[str, Any]:
+ r"""Retrieves WeChat user information.
+
+ Args:
+ openid (str): The user's OpenID.
+ lang (str): Response language. Common values: "zh_CN", "zh_TW", "en". (default: "zh_CN")
+
+ Returns:
+ Dict[str, Any]: User information as dictionary or error information.
+
+ References:
+ https://developers.weixin.qq.com/doc/offiaccount/User_Management/Getting_user_basic_information.html
+ """
+ data = _make_wechat_request(
+ "GET", f"/cgi-bin/user/info?openid={openid}&lang={lang}"
+ )
+ return data
+
+ @api_keys_required([
+ (None, "WECHAT_APP_ID"),
+ (None, "WECHAT_APP_SECRET"),
+ ])
+ def get_followers_list(
+ self,
+ next_openid: str = "",
+ ) -> Dict[str, Any]:
+ r"""Retrieves list of followers' OpenIDs.
+
+ Args:
+ next_openid (str): Starting OpenID for pagination. (default: "")
+
+ Returns:
+ Dict[str, Any]: Followers list as dictionary or error information.
+
+ References:
+ https://developers.weixin.qq.com/doc/offiaccount/User_Management/Getting_a_list_of_followers.html
+ """
+ endpoint = "/cgi-bin/user/get"
+ if next_openid:
+ endpoint += f"?next_openid={next_openid}"
+ data = _make_wechat_request("GET", endpoint)
+ return data
+
+ @api_keys_required([
+ (None, "WECHAT_APP_ID"),
+ (None, "WECHAT_APP_SECRET"),
+ ])
+ def upload_wechat_media(
+ self,
+ media_type: Literal[
+ "image",
+ "voice",
+ "video",
+ "thumb",
+ ],
+ file_path: str,
+ permanent: bool = False,
+ description: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ r"""Uploads media file to WeChat.
+
+ Args:
+ media_type (str): Media type: "image", "voice", "video", "thumb".
+ file_path (str): Local file path.
+ permanent (bool): Whether to upload as permanent media. (default: False)
+ description (Optional[str]): Video description in JSON format for permanent upload.
+
+ Returns:
+ Dict[str, Any]: Upload result with media_id or error information.
+
+ References:
+ - Temporary: https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Adding_Temporary_Assets.html
+ - Permanent: https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Adding_Permanent_Assets.html
+ """
+ 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:
+ endpoint = f"/cgi-bin/media/upload?type={media_type}"
+ with open(file_path, "rb") as f:
+ files = {"media": f}
+ data = _make_wechat_request("POST", endpoint, files=files)
+
+ return data
+
+ @api_keys_required([
+ (None, "WECHAT_APP_ID"),
+ (None, "WECHAT_APP_SECRET"),
+ ])
+ def get_media_list(
+ self,
+ media_type: Literal[
+ "image",
+ "voice",
+ "video",
+ "news",
+ ],
+ offset: int = 0,
+ count: int = 20,
+ ) -> Dict[str, Any]:
+ r"""Gets list of permanent media files.
+
+ Args:
+ media_type (str): Media type: "image", "voice", "video", "news".
+ offset (int): Starting position. (default: 0)
+ count (int): Number of items (1-20). (default: 20)
+
+ Returns:
+ Dict[str, Any]: Media list as dictionary or error information.
+
+ References:
+ https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Get_the_list_of_all_materials.html
+ """
+ payload = {"type": media_type, "offset": offset, "count": count}
+ data = _make_wechat_request(
+ "POST",
+ "/cgi-bin/material/batchget_material",
+ headers={"Content-Type": "application/json"},
+ json=payload,
+ )
+ return data
+
+ @api_keys_required([
+ (None, "WECHAT_APP_ID"),
+ (None, "WECHAT_APP_SECRET"),
+ ])
+ def send_mass_message_to_all(
+ self,
+ content: str,
+ msgtype: Literal[
+ "text",
+ "image",
+ "voice",
+ "video",
+ ] = "text",
+ clientmsgid: Optional[str] = None,
+ send_ignore_reprint: Optional[int] = 0,
+ batch_size: int = 10000,
+ ) -> Dict[str, Any]:
+ r"""Sends a mass message to all followers (by OpenID list).
+
+ This method paginates all follower OpenIDs and calls the
+ mass-send API in batches.
+
+ Args:
+ content (str): For text, the message content; for non-text,
+ the media_id.
+ msgtype (Literal["text","image","voice","video"]):
+ Message type. For "video", the mass API expects
+ "mpvideo" internally.
+ clientmsgid (Optional[str]): Idempotency key to avoid
+ duplicate mass jobs.
+ send_ignore_reprint (Optional[int]): Whether to continue
+ when a news article is judged as a reprint (reserved;
+ applies to news/mpnews).
+ batch_size (int): Max OpenIDs per request (WeChat limit
+ is up to 10000 per batch).
+
+ Returns:
+ Dict[str, Any]: Aggregated result including counts and
+ each batch response.
+
+ References:
+ - Mass send by OpenID list:
+ https://developers.weixin.qq.com/doc/service/api/notify/message/api_masssend.html
+ """
+ # 1) Collect all follower OpenIDs
+ all_openids: List[str] = []
+ next_openid = ""
+ while True:
+ endpoint = "/cgi-bin/user/get"
+ if next_openid:
+ endpoint += f"?next_openid={next_openid}"
+ page = _make_wechat_request("GET", endpoint)
+ data_block = page.get("data", {}) if isinstance(page, dict) else {}
+ openids = data_block.get("openid", []) if isinstance(data_block, dict) else []
+ if openids:
+ all_openids.extend(openids)
+ next_openid = page.get("next_openid", "") if isinstance(page, dict) else ""
+ if not next_openid:
+ break
+
+ # 2) Build and send batches
+ results: List[Dict[str, Any]] = []
+ if not all_openids:
+ return {
+ "total_openids": 0,
+ "batches": 0,
+ "results": results,
+ }
+
+ def build_payload(openid_batch: List[str]) -> Dict[str, Any]:
+ payload: Dict[str, Any] = {
+ "touser": openid_batch,
+ }
+ if msgtype == "text":
+ payload["msgtype"] = "text"
+ payload["text"] = {"content": content}
+ elif msgtype in ("image", "voice"):
+ payload["msgtype"] = msgtype
+ payload[msgtype] = {"media_id": content}
+ elif msgtype == "video":
+ # Mass API expects mpvideo
+ payload["msgtype"] = "mpvideo"
+ payload["mpvideo"] = {"media_id": content}
+ if clientmsgid:
+ payload["clientmsgid"] = clientmsgid
+ if send_ignore_reprint is not None:
+ payload["send_ignore_reprint"] = send_ignore_reprint
+ return payload
+
+ for i in range(0, len(all_openids), batch_size):
+ batch = all_openids[i : i + batch_size]
+ payload = build_payload(batch)
+ resp = _make_wechat_request(
+ "POST",
+ "/cgi-bin/message/mass/send",
+ headers={"Content-Type": "application/json"},
+ json=payload,
+ )
+ results.append(resp)
+
+ return {
+ "total_openids": len(all_openids),
+ "batches": (len(all_openids) + batch_size - 1) // batch_size,
+ "results": results,
+ }
+ def get_tools(self) -> List[FunctionTool]:
+ r"""Returns toolkit functions as tools."""
+ return [
+ FunctionTool(self.send_customer_message),
+ FunctionTool(self.get_user_info),
+ FunctionTool(self.get_followers_list),
+ FunctionTool(self.upload_wechat_media),
+ FunctionTool(self.get_media_list),
+ FunctionTool(self.send_mass_message_to_all),
+ ]
\ No newline at end of file
diff --git a/examples/toolkits/wechat_official_toolkit.py b/examples/toolkits/wechat_official_toolkit.py
new file mode 100644
index 000000000..d56bc3332
--- /dev/null
+++ b/examples/toolkits/wechat_official_toolkit.py
@@ -0,0 +1,218 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+from camel.agents import ChatAgent
+from camel.models import ModelFactory
+from camel.toolkits import WeChatOfficialToolkit
+from camel.types import ModelPlatformType, ModelType
+
+def main():
+ # Initialize WeChat toolkit
+ wechat_toolkit = WeChatOfficialToolkit()
+
+ # Create model
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.DEFAULT,
+ model_type=ModelType.DEFAULT,
+ )
+
+ # Create agent with WeChat toolkit
+ agent = ChatAgent(
+ system_message="You are a WeChat Official Account assistant. Help manage WeChat operations.",
+ model=model,
+ tools=wechat_toolkit.get_tools(),
+ )
+
+ # Example 1: Get followers and send a text message
+ response = agent.step(
+ "Get the list of followers, then send a welcome message to the fifth follower."
+ )
+ print("Text Message Response:", response.msg.content)
+ print("Tool calls:")
+ for i, tool_call in enumerate(response.info['tool_calls'], 1):
+ print(f" {i}. {tool_call.tool_name}({tool_call.args})")
+ print()
+
+ # Example 2: Upload and send an image
+ image_path = "/home/lyz/Camel/CAMEL_logo.jpg" # Update this path as needed
+ response = agent.step(
+ f"Upload the image at '{image_path}' as temporary media, then send this image to the fifth follower."
+ )
+ print("Image Upload and Send Response:", response.msg.content)
+ print("Tool calls:")
+ for i, tool_call in enumerate(response.info['tool_calls'], 1):
+ print(f" {i}. {tool_call.tool_name}({tool_call.args})")
+ print()
+
+ # Example 3: Get detailed user information
+ response = agent.step(
+ "Get detailed information about the fifth follower, including their language preference and subscription details."
+ )
+ print("User Info Response:", response.msg.content)
+ print("Tool calls:")
+ for i, tool_call in enumerate(response.info['tool_calls'], 1):
+ print(f" {i}. {tool_call.tool_name}({tool_call.args})")
+ print()
+
+ # Example 4: Upload permanent media and get media list
+ response = agent.step(
+ f"Upload the image at '{image_path}' as permanent media, then get the list of all image media files."
+ )
+ print("Permanent Media Upload Response:", response.msg.content)
+ print("Tool calls:")
+ for i, tool_call in enumerate(response.info['tool_calls'], 1):
+ print(f" {i}. {tool_call.tool_name}({tool_call.args})")
+ print()
+
+
+if __name__ == "__main__":
+ main()
+
+"""
+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})
+
+"""
\ No newline at end of file
diff --git a/test/toolkits/test_wechat_official_toolkit.py b/test/toolkits/test_wechat_official_toolkit.py
new file mode 100644
index 000000000..0b34db0a2
--- /dev/null
+++ b/test/toolkits/test_wechat_official_toolkit.py
@@ -0,0 +1,84 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from camel.toolkits.wechat_official_toolkit import (
+ WeChatOfficialToolkit,
+ _get_wechat_access_token,
+)
+
[email protected](autouse=True)
+def set_env_vars(monkeypatch):
+ """Set up environment variables for testing."""
+ monkeypatch.setenv("WECHAT_APP_ID", "test_app_id")
+ monkeypatch.setenv("WECHAT_APP_SECRET", "test_app_secret")
+
+
+def test_toolkit_init():
+ """Test toolkit initialization."""
+ toolkit = WeChatOfficialToolkit()
+ assert toolkit.base_url == "https://api.weixin.qq.com"
+
+
+def test_get_tools():
+ """Test getting available tools."""
+ toolkit = WeChatOfficialToolkit()
+ tools = toolkit.get_tools()
+ assert len(tools) == 6
+
+
+@patch('camel.toolkits.wechat_official_toolkit.requests.get')
+def test_get_access_token(mock_get):
+ """Test access token retrieval."""
+ mock_response = MagicMock()
+ mock_response.json.return_value = {
+ 'access_token': 'test_token',
+ 'expires_in': 7200
+ }
+ mock_get.return_value = mock_response
+
+ token = _get_wechat_access_token()
+ assert token == 'test_token'
+
+
+@patch('camel.toolkits.wechat_official_toolkit._make_wechat_request')
+def test_send_message(mock_request):
+ """Test sending customer message."""
+ mock_request.return_value = {'errcode': 0}
+
+ toolkit = WeChatOfficialToolkit()
+ result = toolkit.send_customer_message('test_openid', 'Hello', 'text')
+ assert 'Message sent successfully' in result
+
+
+@patch('camel.toolkits.wechat_official_toolkit._make_wechat_request')
+def test_get_user_info(mock_request):
+ """Test getting user information."""
+ expected_data = {'openid': 'test_openid', 'nickname': 'Test User'}
+ mock_request.return_value = expected_data
+
+ toolkit = WeChatOfficialToolkit()
+ result = toolkit.get_user_info('test_openid')
+ assert result == expected_data
+
+
+def test_missing_credentials(monkeypatch):
+ """Test initialization with missing credentials."""
+ monkeypatch.delenv("WECHAT_APP_ID", raising=False)
+
+ with pytest.raises(ValueError, match="WeChat credentials missing"):
+ WeChatOfficialToolkit()